Chrome Extension: Remembering a checkbox value when popup is reopened

前端 未结 3 1926
醉酒成梦
醉酒成梦 2020-12-20 01:49

Newbie here so sorry if this is pretty elementary. I\'m making an extension that simply has a checkbox/switch when loaded. It is to be unchecked the first time you open it b

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 02:23

    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.

提交回复
热议问题