Chrome扩展程序:chrome.runtime.sendMessage和XMLHttpRequest();

时间:2016-08-09 13:04:22

标签: javascript google-chrome-extension

我在使用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"
}

1 个答案:

答案 0 :(得分:0)

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