Search code examples
javascriptfirefoxcheckboxfirefox-addon-webextensionswebextension-storage

Firefox extensions: How to save the value of a javascript variable to local storage?


The popup of my extension has a checkbox:

<div id="popup-content">
  <input id="checkBox" type="checkbox">
</div>

The way it's set up now, if I click on the extension icon on the toolbar and check the checkbox in the popup, the value of the checkbox isn't saved when the popup disappears i.e. if I open the popup again it shows that the checkbox is unchecked. I did some searching around and found out that I needed to use the storage api and store the variable in the storage, but I'm not sure how to proceed. I saw the examples in the storage api documentation, but all of them use keys and values instead of simple variables. This is what my js file looks right now:

document.getElementById('checkBox').addEventListener('change', function() {
  var m = document.getElementById("checkBox").checked;
  browser.storage.local.set(m);
  alert(browser.storage.local.get("m"));
});

I'm obviously doing something wrong here because I'm not getting any alert message stating the value of the checkbox. What am I doing wrong? Also, this is only half of the problem. How do I set it up such that if I reopen the popup, the checkbox will show checked if it was checked before?


Solution

  • Firstly, browser.storage.local.set is asynchronous, so your alert is doomed to failure

    secondly, according to the documentation you actually linked to, the usage is as follows

    document.getElementById('checkBox').addEventListener('change', function() {
      var m = document.getElementById("checkBox").checked;
      browser.storage.local.set({m})
      .then(() => browser.storage.local.get({m:''}))
      .then(({m}) => alert(m));
    });
    

    when the popup opens, you would do something like the following

    browser.storage.local.get({m:''}).then(value => document.getElementById("checkBox").checked = !!value);
    

    Though I'm a bit vague as to where in your code you do that