私は最初のChrome拡張機能を作成するJavaScriptの初心者であり、メッセージパッシングで立ち往生しています。私の拡張機能には、バックグラウンドスクリプト、ブラウザアクションアイコン、およびコンテンツスクリプトが含まれています。コンテンツスクリプト(タブで費やされた秒数を測定するタイマー)は、バックグラウンドスクリプトを更新し、タブが閉じられたときにアイコンを変更する必要がありますが、コンテンツスクリプトはタブonRemove
イベントにアクセスできないため、メッセージをリッスンする必要がありますバックグラウンドスクリプトから。
閉じたタブをリッスンするようにバックグラウンドスクリプトリスナーを設定する方法は次のとおりです。
// Listen for closed tabs.
chrome.tabs.onRemoved.addListener(function(tab) {
send_closed_message();
});
function send_closed_message () {
chrome.tabs.getSelected(null, function(tab) {
console.log("sending tab_closed to tab " + tab.id);
chrome.tabs.sendRequest(tab.id, {close: true},
function(response) {
console.log(response.timer_stop); });
});
}
そして、これがこのメッセージをリッスンするコンテンツスクリプトの関数です。
function main () {
console.log("main()");
timer = new Timer();
timer.start();
// Listen for window focus
window.addEventListener('focus', function() { timer.start(); } );
// Listen for window blur
window.addEventListener('blur', function() { timer.stop(); } );
// Listen for tab close
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url:
"from the extension");
if (request.close === true) {
sendResponse({timer_stop: "stopped"});
timer.stop();
}
});
}
バックグラウンドスクリプトコンソールにコンテンツスクリプトからの応答が表示されません。タブを閉じているため、コンテンツスクリプトコンソールを表示できません。メッセージはどこで間違っていますか?これをデバッグするためのより良い方法はありますか?タブが閉じたときにコンテンツスクリプトがリッスンする別の方法はありますか?