contentscript.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"});
});
background.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 を一時停止するとイベント リスナーが停止するかのように)