我在使用chrome.runtime.sendMessage
(在我的内容脚本中)和chrome.runtime.onMessage.addListener
(在我的背景HTML页面中)发出http请求时遇到了麻烦。
这里的问题是没有进行http resquest,我从未正确接收回调responseText
,在chrome.runtime.sendMessage
中总是以 undefined 的形式出现。
所以,我想要任何帮助尝试解决这个问题。
这是我的所有代码:
内容脚本
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"
}