0

I developed a Chrome Extension, and added an On/Off toggle to control the injection of the content scripts.

In my popup.html, the following div was added with a checkbox:

<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>

The popup.js is setting the 'onoffswitch' selection in chrome storage as follows:

$(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));
});

})

I am struggling to make the 'onoffswitch' turned ON as default upon initial Extension installation. Whenever adding the Extension, the 'onoffswitch' is turned OFF, despite the declaration 'checked' in the 'checkbox' input under 'popup.html'.

Thank you, Ido.

iDog
  • 137
  • 1
  • 7
  • If I'm understanding you properly would this not work: chrome.storage.sync.get('myonoffswitch', function(storage) { $('#myonoffswitch').prop('checked', (typeof storage.myonoffswitch === "undefined" || storage.myonoffswitch == true)); }) –  Oct 16 '16 at 12:34
  • Basically what I'm doing is if it's undefined therefore by default also set the prop of the checkbox also true –  Oct 16 '16 at 12:36
  • Thank you @andrew196. this worked perfectly! – iDog Oct 16 '16 at 12:54
  • Glad to hear. @iDog if you could mark the comment as the correct answer that would be great. –  Oct 16 '16 at 12:57

2 Answers2

0

If I'm understanding you properly would this would work:

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

Basically what I'm doing is if it's undefined therefore by default also set the prop of the checkbox also true

0

A more explicit way of doing this would be to set the default options in the extension installation callback:

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

This also has the benefit of decluttering the options access logic.

bklaric
  • 447
  • 6
  • 15