我正在制作一个简单的 Chrome 扩展,其中包含一个简单的开/关开关,如下所示:
每当我启用此开关时,我希望新的开/关状态能够反映在所有其他活动选项卡/新选项卡/chrome 实例中。
目前还没有发生这种情况,如果我在一个选项卡中启用它,它在另一个选项卡中仍然被禁用。
我的方法如下:
为交换机添加事件监听器
切换值,并将新值存储在 chrome.storage 中
Send a chrome.runtime
向后台脚本发送消息,并更新所有 chrome 实例。
问题:每当我切换开关时,我都会收到以下错误:
另外,由于某种原因,我的background.js从未初始化,可能与上面的错误有关。
这是我的
背景.js(监听要发送的消息,以便我可以更新其他选项卡)
console.log('?! loading background js !?') // this never fires :(
// Whenever a message has been passed, such as toggling the enable/disable switch, communicate that with other Chrome tabs/instances.
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
// todo: update all chrome tabs with new switch state
console.log('reached Background message handler!')
}
);
popup.js(监听点击事件,执行切换 chrome.storage 切换值的脚本)
// when the toggle is updated, run our script
document.getElementById('enable-site-blocking').onclick = executeBlocking;
function executeBlocking() {
chrome.tabs.executeScript({
code: "setToggleState()"
});
}
内容脚本.js(单击切换按钮时执行,设置存储状态并发送运行时消息)
setToggleState();
function setToggleState() {
chrome.storage.sync.get(['isExtensionActive'], function (storage) {
const invertedState = !storage.isExtensionActive;
chrome.storage.sync.set({
isExtensionActive: invertedState
});
console.log('sending message')
// send an update to all other Chrome processes
chrome.runtime.sendMessage({
greeting: "hello"
}, function (response) {
console.log("done sending message");
});
});
}
所以,我的问题如下:
- 对于维护跨选项卡切换开关的状态,我的方法是否正确?如果不是,我应该改变什么?
- 导致上述错误的原因可能是什么?
- 为什么我的background.js永远不会执行?
抱歉,如果问题很简单,我是 Chrome 扩展的新手!
For additional context, here are the content_scripts/background in my manifest.json
感谢您的任何帮助