【发布时间】:2020-06-19 17:32:17
【问题描述】:
我正在制作一个简单的 Chrome 扩展程序,其中包含一个简单的开/关开关,见下文:
每当我启用此开关时,我希望它新的开/关状态反映在所有其他活动选项卡/新选项卡/chrome 实例中。
目前没有发生这种情况,如果我在一个选项卡中启用它,它仍然在另一个选项卡中被禁用。
我的做法如下:
向开关添加事件监听器
切换值,并将新值存储在 chrome.storage 中
向后台脚本发送
chrome.runtime消息,并更新所有 chrome 实例。
问题:每当我切换开关时,都会收到以下错误:
另外,由于某种原因,我的 background.js 从未初始化,可能与上述错误有关。
这是我的
background.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()"
});
}
content-script.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 扩展程序的新手!
有关其他上下文,这里是我的 manifest.json 中的 content_scripts/background
感谢您的帮助
【问题讨论】:
-
感谢@elegant-user ,它导致了一个新错误:无法建立连接。接收端不存在。我肯定会使用 chrome.extension.onMessage 发送消息。我刚刚发现如何调试background.js,没有错误,并且“正在加载后台js!”正在开火
-
我想我在找到背景调试后得到了答案,你的回答顺便让我找到了答案!谢谢
-
作为修改后的问题@elegant-user ,如果您想回答的话。你认为我应该切换 Background.js 中的按钮吗?或者我应该在我的 content-script.js 中执行此操作。随时发布答案作为回复,以便我接受
-
或者更确切地说,我应该在我的 popout.js 或我的内容脚本中切换按钮。不确定这里的最佳做法是什么
-
chrome.extension.onMessage 已于 5 年前弃用,请不要传播过时信息。
标签: javascript google-chrome google-chrome-extension