21 hours ago

How can I create a toggle button to enable/disable a script or function in a Chrome extension?

I am developing a grade calculator extension that requires a checkbox to turn on/off the functionality within the extension. The default state of the checkbox should be off and should remain on until the user manually presses the button again to turn it off. However, when the checkbox is turned on, it remains off and disappears once the popup page is closed. I am looking to implement a script or function that runs only when the button is turned on and not when it is turned off. It should be noted that I am not attempting to implement an extension turn on/off button, but rather, I just want to execute a specific script or function. The code includes popup.html, content1.js, and manifest.json files. In content1.js, the function updateExtensionState() enables or disables the extension based on the checkbox state. However, I am encountering issues with the functionality of the checkbox and have been unable to find a solution on the web using chatgpt. Can you help me with this problem?
21 hours ago
Verified Answer
To keep your checkbox turned on even after refreshing or closing the popup, you need to store its state in the Here are the changes you need to make in your code: In popup.html, remove the checked attribute from the checkbox input.
In content1.js, update the value to match the toggle switch state.
const toggleSwitch = document.getElementById('toggleSwitch');
  toggleSwitch.checked = data.toggleState || false;

document.getElementById('toggleSwitch').addEventListener('change', function(event) {
  const toggleState =;
  updateExtensionState(toggleState);{ 'toggleState': toggleState });

function updateExtensionState(enabled) {
  if (enabled) {
    alert('Extension is enabled');
    // Add your code or function that should run when the checkbox is turned on
  } else {
    alert('Extension is disabled');
    // Add your code or function that should run when the checkbox is turned off
Make sure that you have added "storage" permission in the manifest.json.