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

时间:2016-11-01 18:08:33

标签: javascript google-chrome-extension state

新手在这里很抱歉,如果这是非常基本的。我正在进行扩展,加载后只需要一个复选框/开关。首次打开它时要取消选中,但是当扩展程序关闭并重新打开时,我希望它显示是否已选中。

复选框在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>

popup.js的相关部分

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

function runTimer() {...

在html中,我的复选框设置为未选中。我正把它放进popup.js

var switchState = document.getElementById("notification").checked;
    chrome.storage.sync.set({
        'value' : switchState
    }, function () {
        console.log("Switch Saved as " + switchState);
    });

我认为这会保存复选框值,所以如果我关闭并重新打开扩展程序,我可以使用它。我的问题是,当我打开扩展程序时,html接管并从头开始创建复选框,取消选中。

如果我知道扩展程序之前已经打开一次,我该如何覆盖它,所以我现在应该使用上次打开时的复选框值?

3 个答案:

答案 0 :(得分:1)

您可能希望添加background script,其中包含变量中复选框的状态。

Storing a variable也是一种选择。

答案 1 :(得分:1)

Google's options example复制代码并将其转换为适合您的代码:

// 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启动时首次运行扩展程序时清除状态。

答案 2 :(得分:1)

删除了之前的回复,因为我看到我再次出错的地方,我使用的代码位于

之下
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;
    });
}

几乎完全是建议的内容,以及谷歌选项页面中的内容(我确实阅读了它,但当时还没有得到它)​​。我错过了&quot; initialValue&#39;如果存储没有修复我第一次启动扩展时的问题的值,则设置为false。

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