问题
I am trying to store the value of a checkbox in the popup.html
file. I have these two functions in my popup.js
file:
function storeUserPrefs() {
var isHighlighting = false;
var highlightedCheckBoxVal = $("#highlightedCheckbox").is(":checked");
chrome.storage.sync.set({isHighlighting: highlightedCheckBoxVal}, function() {
console.log("saved " + isHighlighting + "as " + highlightedCheckBoxVal);
})
}
function getUserPrefs() {
chrome.storage.sync.get(['isHighlighting'], function(result) {
console.log('Value is currently ' + result.isHighlighting);
});
}
My first question is:
If I am trying to save the true/false value of the variable isHighlighting
and then set the saved value to the highlightedCheckBoxVal
will these two functions do that correctly?
My second question is:
Where do I call these two functions? Should I keep them in popup.js
or should I put one in background.js
?
My third question is:
Would I use the Chrome.storage.onChanged function to update these values every time the checkbox is checked/unchecked?
Any help is greatly appreciated, and please let me know if you need any more details.
回答1:
trying to save the true/false
set() is fine.
get() does nothing useful so its callback needs something like
$("#highlightedCheckbox").prop('checked', result.isHighlighting)
Where do I call these two functions
In the popup.
The background script runs in a separate hidden background page with its own empty DOM.
use the Chrome.storage.onChanged function
No.
Register a change
or click
listener that calls set() to store the new value.
Do it at the beginning of the script and add getUserPrefs() call to load the data every time the popup opens:
$("#highlightedCheckbox").change(storeUserPrefs)
getUserPrefs();
来源:https://stackoverflow.com/questions/60641541/how-and-where-do-i-store-user-preferences-with-the-chrome-storage-api-in-a-chrom