内容脚本中的chrome.runtime.sendMessage不发送消息

时间:2014-05-11 19:29:37

标签: javascript google-chrome-extension

我有以下文件(gist以便于访问):

的manifest.json

{
  "name": "testmessage",
  "version": "0.1",
  "manifest_version": 2,
  "externally_connectable": {
    "matches": ["*://www.google.com/*"]
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "content_scripts": [
    {
      "matches": ["*://www.google.com/*"],
      "js": ["content.js"]
    }
  ]
}

content.js

chrome.runtime.sendMessage(
    "eldkfaboijfanbdjdkohlfpoffdiehnb", // PUT YOUR EXTENSION ID HERE
    "foo",
    function (response) {
        console.log(response);
    }
);
console.log("this is content.js reporting for duty");

background.js

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        console.log("background.js got a message")
        console.log(request);
        console.log(sender);
        sendResponse("bar");
    }
);
console.log("this is background.js reporting for duty");

我可以在相应的控制台中看到“...报告职责”消息。但background.js加载时content.js没有收到消息。 undefined中的第5行在google.com的控制台中打印chrome.runtime.sendMessage("eldkfaboijfanbdjdkohlfpoffdiehnb", "foo");

当我在google.com控制台中运行{{1}}时,它会显示在background.js控制台中。

我做错了什么?

1 个答案:

答案 0 :(得分:18)

你做错了什么让它过于复杂。两次。

首先,您不需要声明可以外部连接,因为您从内容脚本而不是网页本身发送消息。

其次,它也不是外部消息。外部邮件用于连接不同的扩展名,而不是一个扩展名内的邮件。

您的代码应如下所示:

<强> content.js

chrome.runtime.sendMessage(
    "foo",
    function (response) {
        console.log(response);
    }
);

<强> background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log("background.js got a message")
        console.log(request);
        console.log(sender);
        sendResponse("bar");
    }
);
相关问题