0

I'm creating a Google Extension and I'm on the step to set the options page from my extension.

I've create a toggle switch using this website which uses a css styled checkbox. Since I'm early stages of programming and extension development, I struggled a bit but was able to attached some jquery commands to the checkbox switch to set a var to either 1 when it's on and 0 when it's off, and the code works just fine, as bellow:

$("input:checkbox[name=onoffswitch]").change(function() {
  if ($(this).is(':checked')) {
    chrome.storage.sync.set({'varMenuSwitch': '1'}, function(toggleOn){
      console.log('Switch is ON - Var set to 1');
    });
  } else {
    chrome.storage.sync.set({'varMenuSwitch': '0'}, function(toggleOff){
      console.log('Switch is OFF - Var set to 0');
    });
    }
});

Now I just need to 'save' and persist the current state of the checkbox switch (on or off) along with the VAR, which right now is always ON when the page loads. I don't have any idea how to accomplish that. Any directions?

Here is the HTML:

<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>
</div>
SoMeGoD
  • 135
  • 5
  • 13
  • [Save chrome extension options to chrome.storage?](http://stackoverflow.com/q/21234676) - see if you can figure out your solution from this answer. – wOxxOm Jul 16 '16 at 06:23
  • The `syncForm` method of [webext-options-sync](https://github.com/fregante/webext-options-sync) makes it completely transparent because it auto-saves and auto-restores the state of the form. – fregante Jul 25 '19 at 19:47

1 Answers1

1

You could call chrome.storage.sync.get after page loads, retrieve the value of varMenuSwitch and set true or false to $("input:checkbox[name=onoffswitch]").

chrome.storage.sync.get('varMenuSwitch', function (result) {
    $("input:checkbox[name=onoffswitch]").prop('checked', result.varMenuSwitch === '1');
});

You could wrap above code into somewhere the page loads event is triggered, such as window.onload.

Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
  • Thanks so much for the reply. I don't know if it was the best way, but I've created a function to be triggered at dom load `document.addEventListener('DOMContentLoaded', gacUserSettings);` and then I call the sync.get as you mentioned, adding `$('#myonoffswitch').prop('checked', 'true or false here');` it worked :) – SoMeGoD Jul 16 '16 at 16:25