我使用以下代码从内容脚本发送示例消息:
function sendjsontrue()
{
var arrCars = new Array("Toyota", "Mercedes", "BMW");
jsonStr = JSON.stringify(arrCars);
chrome.extension.sendRequest({greeting: jsonStr}, function(response){
console.log(response.farewell);
});
console.log("Message with header=greeting has been sent...");
}
我的popup.html中用于处理内容脚本发送的消息的代码如下所示 -
<script>
chrome.extension.onRequest.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"});
else
sendResponse({notfarewell:"Not goodbye"}); .
});
</script>
我得到的错误如下 -
Port error: Could not establish connection. Receiving end does not exist.
chrome/EventBindings:184Error in event handler for 'undefined': TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://nkmkgjckmjekpbghhildcfdlnbjeglkd/obtainformdata.js:81:25
at chrome/RendererExtensionBindings:238:13
at [object Object].dispatch (chrome/EventBindings:182:28)
at Object.<anonymous> (chrome/RendererExtensionBindings:134:27)
我在这里做错了什么?
答案 0 :(得分:3)
您应该在后台页面而不是弹出窗口中编写接收器代码。默认情况下,内容脚本与后台页面通信。
如果您需要合适的文档,请查看:
答案 1 :(得分:3)
当我从 option.html听取请求时,我遇到了同样的问题。我找到了以下解决方案:
您还可以在弹出页面中编写接收者代码,但限制是仅当popup.html处于活动状态时, chrome.extension.onRequest.addListener()才会听取您的请求。
所以,如果你想要一直听你的请求,你必须写下
chrome.extension.onRequest.addListener()
在后台页面中,将此页面注册到 manifest.json 。