1
chrome.runtime.sendMessage
(コンテンツスクリプト内)とchrome.runtime.onMessage.addListener
(私のバックグラウンドhtmlページ内)を使用してhttpリクエストを作成する際に問題が発生しています。Chrome拡張機能:chrome.runtime.sendMessageおよびXMLHttpRequest();
ここでのトラブルは、http resquest作られていないと私は正しく、コールバックresponseText
を受けたことがないことを、常にchrome.runtime.sendMessage
に未定義として付属しています。
だから、私はこれを解決するための任意の助けが必要です。
コンテンツスクリプト
chrome.runtime.sendMessage({
method: "GET",
action: "xhttp",
url: "http://www.example.net/echo.php?getecho",
data: ""
}, function(responseText) {
alert(responseText);
});
背景ページのHTML
<!DOCTYPE html>
<html style=''>
<head>
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.onload = function() {
callback(xhttp.responseText);
};
xhttp.onerror = function() {
callback();
};
xhttp.open(method, request.url, true);
if (method == 'POST') {
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhttp.send(request.data);
return true;
}
});
</script>
</head>
<body>
</body>
</html>
:ここ
はすべて私のコードですPHPスクリプト
<?php
if (isset($_GET["getecho"]))
{
echo "Hello i'm php script!";
}
?>
マニフェストファイル
{
"background": {
"page": "popup.html",
"persistent": true
},
"description": "Foo example",
"manifest_version": 2,
"name": "Foo",
"icons": {
"128" : "picture/wmp128.png",
"48" : "picture/wmp48.png"
},
"web_accessible_resources": [
"popup.js"
],
"content_scripts": [
{
"matches": ["<all_urls>", "*://*/*", "http://*/*", "https://*/*"],
"js": ["popup.js"],
"run_at": "document_end",
"all_frames": true
}
],
"permissions": [ "tabs", "background", "activeTab", "<all_urls>", "webNavigation", "webRequest", "http://*/*", "https://*/*", "*://*/*" ],
"version": "2.0"
}
クロム拡張機能にHTML埋め込みコードは使用できません。 background.htmlの代わりにjsスクリプトファイル([ドキュメントを参照](https://developer.chrome.com/extensions/event_pages#manifest))を使用してください。 – wOxxOm
@wOxxOm、解決済み!どうもありがとうございました。 –
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch –