I am new to programming and i am building a simple add-on for firefox but i am using web extensions, my options page has a few check box's
I need to save the values of these checkbox's and then restore them, Sample code is appreciated.
function saveOptions(e) {
e.preventDefault();
browser.storage.local.set({
box1: document.querySelector("#box1").checked
});
}
function restoreOptions() {
var getting = browser.storage.local.get("box1");
function setCurrentChoice(result) {
document.querySelector("#box1").checked = result.box1 || false
}
function onError(error) {
console.log(`Error: ${error}`);
}
getting.then(setCurrentChoice, onError);
}
document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
<form>
<p><label>Box1<input id="box1" type="checkbox" /></label></p>
<p><label>Box2<input id="box2" type="checkbox" /></label></p>
<p><label>Box3<input id="box3" type="checkbox" /></label></p>
<p><label>Box4<input id="box4" type="checkbox" /></label></p>
<p><label>Box5<input id="box5" type="checkbox" /></label></p>
<p><button type="submit">Save</button></p>
</form>
<script src="options.js"></script>
The code i got from Firefox's example works in saving value of one check box, but how do i save and restore all the values of different box ?
This is what I use. My add-on also uses only checkboxes in options. As in your example, the options are identified by element id, so including the HTML would be redundant. I have no save button; changes are recorded in realtime whenever options are checked or unchecked. It's largely copied from the online documentation for this feature. Note that this variant uses jQuery, though.
// see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Implement_a_settings_page
// if one of the checkboxes is clicked, store the new value of the
// corresponding parameter:
$("input").click(function () {
var setting = {};
setting[$(this).attr("id")] = $(this).get(0).checked;
chrome.storage.local.set(setting);
});
function restoreOptions() {
// For each checkbox, see if stored value of setting has changed
$("input").each(function () {
var id = $(this).attr("id");
chrome.storage.local.get(id, function (setting) {
if (Object.keys(setting).length) {
$("#"+id).get(0).checked = setting[id] ? "checked" : undefined;
}
else {
// This block runs only the first time the settings page is opened.
init = {};
init[id] = true;
chrome.storage.local.set(init);
}
});
});
}
document.addEventListener("DOMContentLoaded", restoreOptions);
It's possible that, as @Mayken suggests, your problem might be with manifest.json. The example in the documentation instructs one to put options.html in a directory called settings, and declares this in manifest.json by setting options_ui.page
to "options.html"
. I found I had to spell it out as "settings/options.html"
to get it to work.