【问题标题】:passing info to chrome extension from website从网站将信息传递给 chrome 扩展
【发布时间】:2014-09-20 15:06:13
【问题描述】:

我正在尝试将数据从网站 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");” 我得到'未定义'。

提前谢谢!!!

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    发送响应需要传递给监听器的sendResponse参数,也就是第三个参数:

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

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


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2011-03-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      相关资源
      最近更新 更多