我在使用chrome.runtime.sendMessage(在我的内容脚本中)和chrome.runtime.onMessage.addListener(在我的backgroud html页面中)发出http请求时遇到了麻烦。

这里的麻烦是没有进行HTTP请求,并且我从不正确接收回调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"
}

最佳答案

我不确定,但这可能是同步问题还是异步问题。 This解释了两者之间的区别。可能值得一试。

10-07 19:04
查看更多