I'm building a firefox web extension and I'd like to give its users some options that they can check/uncheck. The state of the checkboxes is saved locally via the WebExtensions storage API, but I'm not quite sure how to restore the saved state for each option.
Here is the options.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form method="post">
<fieldset>
<legend>My favorite veggies</legend>
<input type="checkbox" name="eggplant" id="eggplant" />Eggplant<br />
<input type="checkbox" name="zucchini" id="zucchini" />Zucchini<br />
<input type="checkbox" name="tomatoe" id="tomatoe" />Tomatoe<br />
<input type="submit" value="Submit" />
</fieldset>
</form>
<script src="options.js"></script>
</body>
</html>
The options.js file that saves/restores the state of the checkboxes is as follows:
function onError(error) {
console.log(`Error: ${error}`);
}
function saveOptions(e) {
// List of search engines to be used
let eggplant = {
name: "Eggplant",
imageUrl: "http://ift.tt/2uFjpJX",
show: form.eggplant.checked
};
let zucchini = {
name: "Zucchini",
imageUrl: "http://ift.tt/2uoBbFV",
show: form.zucchini.checked
};
let tomatoe = {
name: "Tomatoe",
imageUrl: "http://ift.tt/2uFE2G5",
show: form.tomatoe.checked
};
let setting = browser.storage.sync.set({
eggplant,
zucchini,
tomatoe
});
setting.then(null,onError);
e.preventDefault();
}
function restoreOptions() {
var gettingItem = browser.storage.sync.get({
'show'
});
gettingItem.then((res) => {
document.getElementById("eggplant").checked = eggplant.show;
document.getElementById("zucchini").checked = zucchini.show;
document.getElementById("tomatoe").checked = tomatoe.show;
});
}
document.addEventListener('DOMContentLoaded', restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
Aucun commentaire:
Enregistrer un commentaire