Reputation: 742
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?
Upvotes: 0
Views: 1545
Reputation: 1
A complete solution to your problem might be as follows:
myObject = {};
function writeParameter(a) {document.getElementById("checkBox").checked = !!a.myObject.myKey;}
function saveOptions(e) {
t = document.getElementById("checkBox").checked;
myObject.myKey = t;
browser.storage.local.set({myObject}).this();
e.preventDefault();
}
function restoreOptions() {
browser.storage.local.get('myObject').then(writeParameter);
}
document.addEventListener('DOMContentLoaded', restoreOptions); //Restore defaults on DOM load...
document.getElementById('checkBox').addEventListener("change", saveOptions);
Note the use of `this()' within the browser.storage object. It's use might not be necessary in this case but it is with other forms of record. Also make sure that your manifest file has all the correct entries.
Upvotes: 0
Reputation: 1
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
Upvotes: 1