如何在Chrome扩展程序中通过Chrome.storage API存储用户首选项? [英] How and where do I store user preferences with the Chrome.storage API in a chrome extension?
问题描述
我正在尝试将复选框的值存储在 popup.html
文件中.我的 popup.js
文件中有这两个函数:
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);
});
}
我的第一个问题是:
如果我尝试保存变量 isHighlighting
的真/假值,然后将保存的值设置为 highlightedCheckBoxVal
,这两个函数会做到这一点吗?正确吗?
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?
我的第二个问题是:
该在哪里调用这两个函数?我应该将它们保留在 popup.js
中还是应该将其放置在 background.js
中?
Where do I call these two functions? Should I keep them in popup.js
or should I put one in background.js
?
我的第三个问题是:
我是否会在每次选中/取消选中复选框时使用Chrome.storage.onChanged函数更新这些值?
我们非常感谢您的帮助,如果您需要更多详细信息,请告诉我.
Any help is greatly appreciated, and please let me know if you need any more details.
推荐答案
试图保存对/错
set()很好.
get()没什么用,所以它的回调需要类似
get() does nothing useful so its callback needs something like
$("#highlightedCheckbox").prop('checked', result.isHighlighting)
我在哪里调用这两个函数
Where do I call these two functions
在弹出窗口中.
背景脚本在单独的具有其空DOM的隐藏背景页面中运行.
The background script runs in a separate hidden background page with its own empty DOM.
使用Chrome.storage.onChanged函数
use the Chrome.storage.onChanged function
否.
注册一个 change
或 click
侦听器,该侦听器调用set()来存储新值.
Register a change
or click
listener that calls set() to store the new value.
在脚本开头执行此操作,并添加getUserPrefs()调用以在每次打开弹出窗口时加载数据:
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();
这篇关于如何在Chrome扩展程序中通过Chrome.storage API存储用户首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!