我正在尝试使用一个消息界面在弹出窗口之间传递一条消息到背景页面(我正在使用类似于谷歌示例中的代码)。
弹出:
chrome.extension.sendMessage( {msg: "this is popup's msg"}, function(b){
alert('this is popups callback func' +b.backgroundMsg);
});
这就是我在 background.js 中聆听(和回复)的方式:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
sendResponse({backgroundMsg: "this is background msg"});
});
现在,当我检查控制台中的所有内容时,消息交换正常,但出现以下错误:
Error in event handler for 'undefined': Cannot call method 'disconnect' of null TypeError: Cannot call method 'disconnect' of null
at chromeHidden.Port.sendMessageImpl (miscellaneous_bindings:285:14)
at chrome.Event.dispatch (event_bindings:237:41)
at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:250:22)
有什么想法吗?
最佳答案
复制您的代码示例并使用 list 和弹出结构填充空白会导致完全正常工作的扩展没有错误。不知道为什么您会收到您共享的错误。试试我的代码,看看你能不能摆脱这个错误。
提示
例子
list .json
{
"name": "Stackoverflow Message Passing Example",
"manifest_version": 2,
"version": "0.1",
"description": "Simple popup with message passing for Stackoverflow question",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
}
}
背景.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
sendResponse({backgroundMsg: "this is background msg"});
});
popup.html
<html>
<head>
<script src="popup.js"></script>
<style type="text/css" media="screen">
body { width: 100px; height: 100px; }
</style>
</head>
<body>
<p>Check the console</p>
</body>
</html>
popup.js
chrome.runtime.sendMessage( {msg: "this is popup's msg"}, function(b){
console.log('this is popups callback func ' + b.backgroundMsg);
});
运行示例截图
在浏览器窗口打开到 exampley.com 的情况下单击扩展按钮
扩展弹出的控制台日志
这是我使用的文件的 zip http://mikegrace.s3.amazonaws.com/stackoverflow/simple-popup.zip
关于javascript - 谷歌浏览器扩展简单消息传递错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981606/