将信息传递给网站的Chrome扩展程序

时间:2014-09-20 15:06:14

标签: javascript google-chrome-extension

我正在尝试从网站javascript向我的Chrome扩展程序发送数据。 我读到sending msgs from website并且我无法使其发挥作用。

在我的网站上:

$("#button-id").click(function(){
    chrome.runtime.sendMessage("msg", {arg: "1"},
    function(response){alert("got response: " + response);});
});

并在background.js中(在chrome扩展名中)

chrome.runtime.onMessageExternal.addListener(
  function() {
        alert("in background");
        return "1";
    });

我也加入了清单:

   "externally_connectable": {
        "matches": ["*://localhost/project/public/*","http://localhost/project/public/*","*://*/*/*"]
    },

当我点击该按钮时,我得到的所有信息都表示"得到了未定义的响应"。

我试过的东西可能有助于弄明白: 当我在我的网站上,打开chrome开发者控制台,输入" chrome.runtime.sendMessage(" jjj");" 我得到了#undefined'。

提前致谢!!!

1 个答案:

答案 0 :(得分:3)

要发送响应,您需要将其传递给侦听器的sendResponse参数,这是第三个参数:

chrome.runtime.onMessageExternal.addListener(
  function(message, sender, sendResponse) {
    alert("in background");
    sendResponse("1");
  }
);

有一点需要注意:如果要异步调用sendResponse,则必须return true;


此外,从网页发送消息时,您必须提供扩展名的id作为第一个参数。在您的示例代码中,它是"msg":它必须是扩展ID。