Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add an on/off switch to your Chrome extension, you can follow these steps:

  1. Open your manifest.json file and add a "background" property with a value of "background.js".
  2. Create a background.js file and add the following code:
let isEnabled = true;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === "toggle") {
    isEnabled = !isEnabled;
  }
});

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ isEnabled });
});

chrome.browserAction.onClicked.addListener((tab) => {
  isEnabled = !isEnabled;
  chrome.storage.sync.set({ isEnabled });
  chrome.tabs.sendMessage(tab.id, { message: "toggle", isEnabled });
});

  1. In your popup.html file, add a button element with an id of "toggle-btn" and the text "On" or "Off" depending on the initial state.
<button id="toggle-btn">On</button>
  1. Add the following code to your popup.js file to handle button clicks:
function toggle() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { message: "toggle" }, (response) => {
      updateUI(response.isEnabled);
    });
  });
}

function updateUI(isEnabled) {
  const toggleBtn = document.getElementById("toggle-btn");

  if (isEnabled) {
    toggleBtn.textContent = "Off";
  } else {
    toggleBtn.textContent = "On";
  }
}

document.addEventListener("DOMContentLoaded", () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { message: "getIsEnabled" }, (response) => {
      updateUI(response.isEnabled);
    });
  });

  document.getElementById("toggle-btn").addEventListener("click", toggle);
});

  1. Finally, update your content script file to listen for the "toggle" message and update the extension's behavior accordingly. For example, you could add the following code to disable or enable a certain feature depending on the extension's enabled/disabled state:
let isEnabled;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.message === "toggle") {
    isEnabled = request.isEnabled;
    // Disable or enable feature depending on isEnabled
  } else if (request.message === "getIsEnabled") {
    sendResponse({ isEnabled });
  }
});

With these changes, your extension should now have an on/off switch that allows users to toggle its behavior.