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

103
Visualizações
Firefox extension - save boolean to storage

In the Firefox extension, I want to implement a simple toggle switch that will enable/disable an extension. A basic idea is that the change of state will be saved as a boolean into browser (sync) storage. The state should be read every time, so an extension will know if should work or not. But - my Javascript knowledge is so poor that I came into trouble.

Here is simple HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="styles.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script> 
  </head>

  <body>
    <form id="form" class="ps-3 mt-3">
      <div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" id="flexSwitch">
        <label class="form-check-label" for="flexSwitch">Plugin ON/OFF</label>
      </div>
    </form>

    <label id="test"></label>
    <br>
    <script src="options.js"></script>
  </body>
</html>

And here is a simple JS file:

function CheckAndSave()
{
    var state = document.getElementById("flexSwitch");
    if(state.checked)
    {
        document.getElementById('test').innerHTML = 'ON';
        browser.storage.sync.set({ delovanje: 1 });
    }
    else
    {
        document.getElementById('test').innerHTML = 'OFF';
        browser.storage.sync.set({ delovanje: 0 });
    }
    restoreState();
}

function restoreState()
{
    //browser.storage.sync.get("delovanje", function(items) { console.log(items)});
    let getting4 = browser.storage.sync.get("delovanje");
    getting4.then(setCurrentChoice, onError);

    function onError(error) {
        console.log(`Error: ${error}`);
      }

    function setCurrentChoice()
    {
      var toggle = document.getElementsByName("flexSwitch");
      if (result.delovanje === 1)
        toggle.checked = true; 
      else
        toggle.checked = false;
    }
}

document.addEventListener("DOMContentLoaded", restoreState);
document.getElementById("flexSwitch").addEventListener('change', CheckAndSave);

What is wrong with my code? Is my way of saving Boolean ok? I tried to write to the console for "debugging", but I don't know how to do it - this is a pop-up after a user press an icon, and nothing is shown in the console.

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

0

Most of all you did a mistake here:

  function setCurrentChoice(result)
    {
      var toggle = document.getElementsByName("flexSwitch");
      if (result.delovanje === 1)
        toggle.checked = true; 
      else
        toggle.checked = false;
    }

In this case, toggle will be array like object, but not the element you expect. You should use document.getElementById("flexSwitch") as previously.

Another issue that you missed an argument in the setCurrentChoice function. It should take settings like this:

 function setCurrentChoice(result){...}

I would also suggest to hide the logic of getting element behind the scene by either wrapping it to the function:

const getToggle = () => document.getElementById("flexSwitch")

Or even move it to the separate class and encapsulate all logic there:

class Toggle {
  constructor() {
    this._el = document.getElementById("flexSwitch");
  }

  setCheck(value) {
    this._el.checked = value;
  }
}

Here is the working sample:

function CheckAndSave()
{
    var state = document.getElementById("flexSwitch");
    if(state.checked)
    {
        document.getElementById('test').innerHTML = 'ON';
        chrome.storage.sync.set({ delovanje: 1 });
    }
    else
    {
        document.getElementById('test').innerHTML = 'OFF';
        chrome.storage.sync.set({ delovanje: 0 });
    }
}

function restoreState()
{
    chrome.storage.sync.get("delovanje",setCurrentChoice );

    function setCurrentChoice(result)
    {
      var toggle = document.getElementById("flexSwitch");
      if (result.delovanje === 1) 
        toggle.checked = true; 
      else
        toggle.checked = false;
    }
}

document.addEventListener("DOMContentLoaded", restoreState);
document.getElementById("flexSwitch").addEventListener('change', CheckAndSave);

This approach will help you reduce the code and accidental mistakes.

P.S. Here is how I worked with the storage

about 4 years ago · Juan Pablo Isaza Relatório

0

I think the problem is that the change event is not fired when setting toggle.checked with JavaScript. Just call CheckAndSave(); from the end of setCurrentChoice.

about 4 years ago · Juan Pablo Isaza Relatório

0

The code seems okay, while there are some things I would change (for refactoring purposes to match my flavour) I think it should be working without much issue.

In any case verify the following.

  1. The browser.storage.sync API is only available from extensions, so check that the HTML and JS that you are posting are actually part of the extension that you are using.
  2. The manifest.json is what tells the browser what resources can your extension access, verify that you did add the "storage" permission on there here you can read more about it for chrome, though it will be the same for other browsers
  3. For debugging purposes always remember that the browser lets you have great tools. Read more about developer tools, but as a starter I would tell you to open them and put a debugger statement there where you feel like there's something that isn't working as expected. And then with the console start looking for the properties that you are not finding.
  4. To log items to the console use console.log('XXX') and it should show what you want
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