Chrome Extension: Remembering a checkbox value when popup is reopened

老子叫甜甜 提交于 2019-11-29 12:22:13

You would want to add a background script, that holds the state of the checkbox in a variable.

Storing a variable is also an option.

Deleted my previous response because I see where I went wrong again, code I used is below

function restoreOptions() {
    chrome.storage.sync.get({
        //False is the default value when first opening the extension
        'initialValue' : false
    }, function (items) {
        document.getElementById('notification').checked = items.initialValue;
    });
}

Pretty much exactly what was suggested, as well as what was in the google options page (I did read it but just didn't get it at the time). I missed the bit where the 'initialValue' was set to false if storage didn't have a value which fixed my issue for when I launched the extension for the first time.

It's all prefectly clear now, finally. Thanks again for your help

Copying the code from Google's options example and transforming it to fit your code:

// Restores checkbox state using the preferences stored in chrome.storage.sync
function restoreOptions() {
    // Use default value = false.
    chrome.storage.sync.get({
        value: false
    }, function (items) {
        document.getElementById('notification').checked = items.value;
    });
}

Then your DOMContentLoaded handler becomes:

document.addEventListener('DOMContentLoaded', function () {
    restoreOptions();
    document.getElementById("notification").addEventListener('click', runTimer);
    console.log("DOM Loaded");
});

Note that the use of chrome.storage.sync will store the state of the checkbox across not only different runs of Chrome on your machine, but all those which sync with that person. You may desire to use chrome.storage.local to limit storage of the checkbox state to that machine. In addition, you may desire to clear the state when the extension first runs when Chrome is started.

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