Skip to content Skip to sidebar Skip to footer

Chrome Extension Set Toggle Switch State In All Tabs

I am making a simple Chrome Extension that contains a simple on/off switch, see below: Whenever I enable this switch, I want it the new on/off state to reflect in all other active

Solution 1:

There's no need for background.js or messaging, simply set the value in popup.js and use chrome.storage.onChanged listener in the content script.

popup.js:

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

background.js: not necessary

content.js:

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

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

functiontoggleSomething(state) {
  console.log('new state:', state);
  // ........... do something
}

Notes:

  • The background script runs in a separate hidden background page which has its own devtools.

  • The popup is also a separate page in a separate window so it has separate devtools: right-click inside the popup, then click "inspect".

Post a Comment for "Chrome Extension Set Toggle Switch State In All Tabs"