2014-09-20 109 views
0

我想从网站JavaScript发送数据到我的Chrome扩展。 我读了约sending msgs from website,我无法使它工作。将信息传递给网站的Chrome扩展

在我的网站

$("#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“);” 我正在'未定义'。

在此先感谢!

回答

3

发送响应,你需要将它传递给听众,这是第三个参数的sendResponse参数:

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

有一点需要注意:如果sendResponse将被异步调用,你有到return true;


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

相关问题