Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作

Chrome extension: can't get message passing to work between background script and content script

本文关键字:脚本 之间 常工作 工作 Chrome 程序 后台 消息传递 扩展      更新时间:2023-09-26

我本质上是试图通过使用后台脚本中的localStorage对象来为我的chrome扩展程序获取持久存储。

这是设置:

我有一个后台脚本和一个内容脚本。内容脚本需要从扩展的localStorage中获取/设置数据。

但是,我无法将消息发送到后台脚本。

下面是后台脚本中的代码:

chrome.runtime.onMessage.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"});
});

和内容脚本:

setTimeout(function () {
  chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
}, 5000);

理想情况下,后台脚本应输出from a content script: [some url],内容脚本应输出goodbye 。相反,我收到以下错误:

Port: Could not establish connection. Receiving end does not exist. 

任何帮助/建议不胜感激!

谢谢:)

编辑:清单

{
  "manifest_version": 2,
  "name": "Helios",
  "description": "Helios chrome extension.",
  "version": "0.0.1",
  "permissions": [
    "https://secure.flickr.com/",
    "storage"
  ],
  "background": {
    "page": "background.html"
  },
  "browser_action": {
    "default_icon": {
      "19": "img/icon-19.png",
      "38": "img/icon-38.png"
    },
    "default_title": "Helios",
    "default_popup": "popup.html"
  },
  "content_scripts":[
    {
      "matches": ["*://*/*"],
      "css": ["css/main.css"],
      "js": [
        "js/vendor/jquery-1.9.1.js",
        "js/vendor/handlebars-1.0.0-rc.4.js",
        "js/vendor/ember-1.0.0-rc.7.js",
        "js/vendor/d3.v3.js",
        "js/vendor/socket.io.min.js",
        "js/templates.js",
        "js/main.js"
      ],
      "run_at": "document_end"
    }
  ],
  "web_accessible_resources": [
    "img/**",
    "fonts/**"
  ]
}

编辑:铬版本

Google Chrome   29.0.1547.65 (Official Build 220622) 
OS  Mac OS X 
Blink   537.36 (@156661)
JavaScript  V8 3.19.18.19
Flash   11.8.800.170
User Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36

来自 onMessage 文档。

当事件侦听器返回时,此函数将变为无效,除非 从事件侦听器返回 true,以指示您希望发送 异步响应(这将使消息通道保持打开 另一端,直到调用发送响应)。

所以你的代码应该看起来像

chrome.runtime.onMessage.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"});
    return true;
  }
});