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は、次のようにクロム ストレージで「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」をデフォルトでオンにするのに苦労しています。拡張機能を追加するたびに、「popup.html」の下の「checkbox」入力で宣言「checked」にもかかわらず、「onoffswitch」がオフになります。

ありがとう、イド。

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 に答える