Chrome 扩展在所有选项卡中设置切换开关状态

Edo*_*don 1 javascript google-chrome google-chrome-extension

我正在制作一个简单的 Chrome 扩展程序,其中包含一个简单的开/关开关,见下文:

在此处输入图片说明

每当我启用此开关时,我都希望它的新开/关状态反映在所有其他活动选项卡/新选项卡/chrome 实例中。

这目前没有发生,如果我在一个选项卡中启用它,它仍然在另一个选项卡中被禁用。

我的方法如下:

  1. 将事件侦听器添加到交换机

  2. 切换值,并将新值存储在 chrome.storage 中

  3. 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!')
    }
);
Run Code Online (Sandbox Code Playgroud)

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()"
    });
}
Run Code Online (Sandbox Code Playgroud)

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");
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题如下:

  1. 我的方法是否正确,用于跨选项卡保持切换开关的状态?如果不是,我应该改变什么?
  2. 上面显示的错误可能是什么原因?
  3. 为什么我的 background.js 永远不会执行?

对不起,如果这很简单,我是 Chrome 扩展程序的新手!

有关其他上下文,这是我的manifest.json中的 content_scripts/background 在此处输入图片说明

感谢您的任何帮助

wOx*_*xOm 5

不需要 background.js 或消息传递,只需在 popup.js 中设置值并在内容脚本中使用 chrome.storage.onChanged 侦听器。

popup.js:

function setToggleState() {
  chrome.storage.sync.get('isExtensionActive', storage => {
    chrome.storage.sync.set({
      isExtensionActive: !storage.isExtensionActive,
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

background.js:没有必要

内容.js:

chrome.storage.sync.get('isExtensionActive', storage => {
  toggleSomething(storage.isExtensionActive);
});

chrome.storage.onChanged.addListener(changes => {
  if (changes.isExtensionActive) {
    toggleSomething(changes.isExtensionActive.newValue);
  }
});

function toggleSomething(state) {
  console.log('new state:', state);
  // ........... do something
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 后台脚本在一个单独的隐藏后台页面中运行,该页面有自己的 devtools

  • 弹出窗口也是单独窗口中的单独页面,因此它具有单独的开发工具:在弹出窗口内右键单击,然后单击“检查”。