Javascript Chrome扩展:重新打开弹出窗口时记住复选框值

Javascript Chrome扩展:重新打开弹出窗口时记住复选框值,javascript,google-chrome-extension,state,Javascript,Google Chrome Extension,State,这里的新手很抱歉,如果这是很基本的。我正在制作一个扩展,在加载时它只是有一个复选框/开关。第一次打开它时,它将被取消选中,但当扩展关闭并重新打开时,我希望它显示是否已选中 该复选框启动background.js中的计时器,取消选中该复选框将停止该计时器。除了保存复选框的状态外,所有这些都可以正常工作 弹出窗口的相关HTML <div class="onoffswitch"> <input type="checkbox" name="onoffswitch

这里的新手很抱歉,如果这是很基本的。我正在制作一个扩展,在加载时它只是有一个复选框/开关。第一次打开它时,它将被取消选中,但当扩展关闭并重新打开时,我希望它显示是否已选中

该复选框启动background.js中的计时器,取消选中该复选框将停止该计时器。除了保存复选框的状态外,所有这些都可以正常工作

弹出窗口的相关HTML

<div class="onoffswitch">
            <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="notification" />
            <label class="onoffswitch-label" for="notification">
                <span class="onoffswitch-inner"></span>
                <span class="onoffswitch-switch"></span>
            </label>
        </div>
在html中,我的复选框设置为未选中。我只是想把它放到popup.js里

var switchState = document.getElementById("notification").checked;
    chrome.storage.sync.set({
        'value' : switchState
    }, function () {
        console.log("Switch Saved as " + switchState);
    });
我想这将保存复选框值,以便在关闭并重新打开扩展时使用它。我的问题是,当我打开扩展时,html接管并从头开始创建复选框,未选中

如果我知道扩展名以前已经打开过一次,因此现在应该使用上次打开时的复选框值,那么如何覆盖它?

您可能希望添加一个,它将复选框的状态保存在变量中

也是一个选项。

从复制代码并将其转换为适合您的代码:

// 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;
    });
}
然后您的
DOMContentLoaded
处理程序变为:

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

请注意,
chrome.storage.sync
的使用不仅会在您机器上的不同chrome运行中存储复选框的状态,而且会在所有与此人同步的运行中存储复选框的状态。您可能希望使用
chrome.storage.local
将复选框状态的存储限制在该机器上。此外,当Chrome启动时,您可能希望清除扩展首次运行时的状态。

删除了我以前的响应,因为我看到我再次出错的地方,我使用的代码如下

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;
    });
}
几乎完全符合建议的内容,以及谷歌选项页面中的内容(我确实读过,但当时没有理解)。如果存储器没有一个值,而这个值在我第一次启动扩展时解决了我的问题,那么我就错过了将“initialValue”设置为false的位置


现在终于完全清楚了。再次感谢您的帮助

在弹出式JavaScript中,在
DOMContentLoaded
事件处理程序中,您将复选框状态设置为存储状态。如果使用,
chrome.storage
,则需要读取存储数据的当前状态。有很多例子,包括中的一个,只需将其作为
默认的\u弹出窗口
,它就可以成为一个弹出窗口。
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;
    });
}