Monday, 6 December 2021

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.



from Firefox extension - save boolean to storage

No comments:

Post a Comment