内容脚本.js
chrome.runtime.onMessage.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"});
});
背景.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
});
这有时有效,有时无效。
无效的情况:
1)当我重新加载扩展并单击现有选项卡上的扩展图标时 2)当我在 background.js 中添加断点时
有效的案例:
1)当我重新加载扩展并重新加载/加载新选项卡并且在 background.js 中没有添加断点时
抛出的错误通常是:
Port: Could not establish connection. Receiving end does not exist. lastError:29
Error in event handler for 'undefined': Cannot read property 'farewell' of undefined TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://glbcapgiojbbnjhngjdmoglaamjbjjak/background.js:16:28
at <error: illegal access>
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27)
at Event.dispatch (event_bindings:362:17)
at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:258:27)
任何人都可以对此有所了解吗?我觉得特别奇怪的是断点会导致它失败(几乎就像暂停 background.js 会导致事件监听器死掉一样)