I am trying to create a chrome extension that only records user data when the checkbox is checked (visually, it is a slider but a checkbox nonetheless). However, I am having trouble saving the value of the checkbox after a user has clicked it. Whenever the popup closes the checkbox (or slider) goes back to unchecked.
I have tried adding (from background.js) the attribute 'checked' to the checkbox in popup.html when the value is true (checked) and then removing the attribute when the value is false (unchecked).
Then, I read something that the .attr in jquery is no longer supported and the new way to do it (as of jquery 3+) is to use .prop('checked', true);
//background.js
var switchStatus;
chrome.storage.onChanged.addListener(function(changes, areaName){
console.log('received');
chrome.storage.local.get('sS', function(status){
switchStatus = status.sS;
console.log(switchStatus);
if(switchStatus === true) {
$('#togBtn').prop('checked', true);
chrome.storage.local.set({'sS': true});
console.log('when checked ' + switchStatus);
}
if(switchStatus === false) {
$('#togBtn').prop('checked', false);
chrome.storage.local.set({'sS': false});
console.log('unchecked ' + switchStatus);
}
});
});
//popup.js
$(function() {
var switchStatus;
$("#togBtn").on('change', function() {
chrome.storage.local.get('sS', function(status){
switchStatus = status.sS;
});
if(($('#togBtn').is(':checked')) === true) {
switchStatus = $("#togBtn").is(':checked');
alert(switchStatus); //to verify
chrome.storage.local.set({'sS': true}, function(){
alert('saved' + ' : ' + switchStatus);
});
}
if(($('#togBtn').is(':checked')) === false) {
switchStatus = $("#togBtn").is(':checked');
alert(switchStatus); //to verify
chrome.storage.local.set({'sS': false}, function(){
alert('saved' + ' : ' + switchStatus);
});
}
});
});
//popup.html
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round" id="thisthing">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
</label>
Again, I'm trying to save the value of the checkbox after the popup is closed. So when a user clicks the checkbox, and the slider switches to green and 'on', if the user were to click out of the popup window or go to a new tab, the checkbox would still show green and 'on'