javascripthtmlgoogle-chromegoogle-chrome-extensionjtogglebutton

Chrome Extension - input Checkbox checked by default


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.


Solution

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