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

一世执手 提交于 2021-01-29 14:51:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!