0

我开发了一个 Chrome 扩展,并添加了一个开/关切换来控制内容脚本的注入。

在我的popup.html中,添加了以下 div 并带有一个复选框:

<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
<label class="onoffswitch-label" for="myonoffswitch">
    <span class="onoffswitch-inner"></span>
    <span class="onoffswitch-switch"></span>
</label>

popup.js在 chrome 存储中设置“ onoffswitch ”选择,如下所示:

$(document).ready(function() {
$('#myonoffswitch').on('change', function(e) {

    chrome.storage.sync.set({
        'myonoffswitch': ($(this).is(":checked"))
    }, function() {});
})
chrome.storage.sync.get('myonoffswitch', function(storage) {
    $('#myonoffswitch').prop('checked', (storage.myonoffswitch == true));
})

$('#myonoffswitch2').on('change', function(e) {

    chrome.storage.sync.set({
        'myonoffswitch2': ($(this).is(":checked"))
    }, function() {});
})
chrome.storage.sync.get('myonoffswitch2', function(storage) {
    $('#myonoffswitch2').prop('checked', (storage.myonoffswitch2 == true));
});

})

我正在努力使“onoffswitch”在初始扩展安装时默认打开。每当添加扩展时,“onoffswitch”都会关闭,尽管在“popup.html”下的“checkbox”输入中声明“checked”。

谢谢你,伊多。

4

2 回答 2

0

如果我正确理解您,这将起作用:

chrome.storage.sync.get('myonoffswitch', function(storage) {
   $('#myonoffswitch').prop('checked', (typeof storage.myonoffswitch === "undefined" || storage.myonoffswitch == true));
})

基本上我正在做的是如果它是未定义的,因此默认情况下也将复选框的属性设置为 true

于 2016-10-16T13:02:18.833 回答
0

一种更明确的方法是在扩展安装回调中设置默认选项:

chrome.runtime.onInstalled.addListener(function (details) {
    if (details.reason === "install") {
        chrome.storage.sync.set({
            'myonoffswitch': true
        }, function() {});
    }
});

这还具有整理选项访问逻辑的好处。

于 2016-10-16T13:30:02.600 回答