简体   繁体   English

如何使用 Chrome.storage API 在 Chrome 扩展程序中存储用户首选项?

[英]How and where do I store user preferences with the Chrome.storage API in a chrome extension?

I am trying to store the value of a checkbox in the popup.html file.我正在尝试将复选框的值存储在popup.html文件中。 I have these two functions in my popup.js file:我的popup.js文件中有这两个函数:

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?如果我尝试保存变量isHighlighting的真/假值,然后将保存的值设置为highlightedCheckBoxVal这两个函数是否会正确执行此操作?

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 ?我应该把它们放在popup.js还是应该放在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?每次选中/取消选中复选框时,我会使用 Chrome.storage.onChanged 函数更新这些值吗?

Any help is greatly appreciated, and please let me know if you need any more details.非常感谢任何帮助,如果您需要更多详细信息,请告诉我。

trying to save the true/false试图保存真/假

set() is fine. set() 没问题。

get() does nothing useful so its callback needs something like get() 没有任何用处,所以它的回调需要类似的东西

$("#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.后台脚本在一个单独的隐藏后台页面中运行,它有自己的空 DOM。

use the Chrome.storage.onChanged function使用 Chrome.storage.onChanged 函数

No.不。

Register a change or click listener that calls set() to store the new value.注册一个调用 set() 的changeclick侦听器来存储新值。

Do it at the beginning of the script and add getUserPrefs() call to load the data every time the popup opens:在脚本开头执行并添加 getUserPrefs() 调用以在每次弹出窗口打开时加载数据:

$("#highlightedCheckbox").change(storeUserPrefs)
getUserPrefs();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM