我正在使用以下代码从内容脚本发送示例消息:

function sendjsontrue()
{

        var arrCars = new Array("Toyota", "Mercedes", "BMW");
            jsonStr = JSON.stringify(arrCars);
        chrome.extension.sendRequest({greeting: jsonStr},     function(response){
            console.log(response.farewell);
            });
        console.log("Message with header=greeting has been sent...");
}


我的popup.html中用于处理内容脚本发送的消息的代码如下:

<script>
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
  if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  else
      sendResponse({notfarewell:"Not goodbye"}); .
  });

</script>


我得到的错误如下:

Port error: Could not establish connection. Receiving end does not exist.
chrome/EventBindings:184Error in event handler for 'undefined': TypeError: Cannot read     property 'farewell' of undefined
at chrome-extension://nkmkgjckmjekpbghhildcfdlnbjeglkd/obtainformdata.js:81:25
at chrome/RendererExtensionBindings:238:13
at [object Object].dispatch (chrome/EventBindings:182:28)
at Object.<anonymous> (chrome/RendererExtensionBindings:134:27)


我在这里做错了什么?

最佳答案

您应该在后台页面而不是在弹出窗口中编写接收器代码。默认情况下,内容脚本与后台页面通信。

如果您需要不错的文档,请查看:


Chrome extension methods
Background pages

关于javascript - 谷歌浏览器扩展名-无法将消息从内容脚本传递到同一扩展名中的弹出页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8037470/

10-08 23:55