Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
How to toggle switch chrome extension

I am new to developing chrome extensions. I am trying to build a simple extension and I want that extension to be toggle between on and off states via the icon.

Here is the code I am using so far for achieving this:

(background.js)

var enabled = 1;
chrome.action.onClicked.addListener(function () {
    console.log(enabled);
    if (enabled == 0) {
        enabled = 1;
        chrome.action.setIcon({
            path: "images/on.png"
        });
    } else {
        enabled = 0;
        chrome.action.setIcon({
            path: "images/off.png"
        });
    }
});

And then in the same file, I am doing the stuff I want to do. This works so far but the problem is, yes the thing works with an if statement:

if(enabled == 1){
do this...}

But after a while because of a reason that I couldn't understand (I've done console log debugs with the "enabled" variable, it works fine), the extension keeps working since its in the disabled state and the icon shows its disabled...

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The background script is terminated after 30 seconds since the last event such as onClicked, so you can't rely on global variables as they will be reset when the background script starts again for a new event after it was terminated.

One solution is to change the hash part of the popup's file name, meaning that the same popup file will be shown, however its location.hash will be different:

background script:

chrome.action.onClicked.addListener(async () => {
  const popup = await chrome.action.getPopup({});
  const enabled = popup.includes('#off'); // new value of `enabled`
  const newPopup = popup.split('#')[0] + (enabled ? '' : '#off');
  chrome.action.setIcon({path: `images/${enabled ? 'on' : 'off'}.png`});
  await chrome.action.setPopup({popup: newPopup});
});

popup script:

const enabled = !location.hash.includes('#off');
//document.body.prepend('Enabled: ' + enabled);

Another solution is to store the state in chrome.storage.local:

chrome.action.onClicked.addListener(async () => {
  const enabled = !(await chrome.storage.local.get('enabled')).enabled;
  const path = `images/${enabled ? 'on' : 'off'}.png`;
  chrome.action.setIcon({path});
  await chrome.storage.local.set({enabled});
});

manifest.json:

  "permissions": ["storage"]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda