如何将消息从后台脚本传递到内容脚本?

时间:2020-05-26 08:29:25

标签: javascript google-chrome google-chrome-extension message-passing

我正在关注官方文档https://developer.chrome.com/extensions/messaging,但没有用。表示接收端没有退出的错误。

内容脚本:

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

背景脚本:

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"});
  });

Manifest.json

{
  "manifest_version": 2,
  "name": "name",
  "author": "author",
  "description": "Pilot towards chrome Extension.",
  "version": "1.0.0",

  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["jquery.js", "content.js"]
  }],

  "background": {
    "persistent": false,
    "scripts": ["background.js"]

  },

  "icons": {
    "128": "icon_128.png"
  },

  "permissions": [
    "storage",
    "activeTab",
    "<all_urls>",
    "contextMenus",
    "tabs",
    "alarms"
  ]
}

我仍然遇到错误,指出接收端不存在。

0 个答案:

没有答案