'Script doesnt read checkbox
I'm trying to make chrome extension to refresh site every specified time when checkbox is selected. At this point I'm facing problem that my site isn't refreshed when checkbox is selected so neither it relunch after timeout time. Could you help me with this? html
<input type="checkbox" class="timer" name="timer" value="yes" id="timer" onclick="validate">
js
function validate() {
if (document.getElementById('timer').checked) {
for (var i = 0; i < 6; i++) {
setTimeout(function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, { code: code });
});
}, 501);
}
}
}
What is worth noting i have prepared script to hold information if checkbox is clicked or not so it doesn't disapear after reclicking on popup
(function zzz() {
// variable to store our current state
var cbstate;
window.addEventListener('load', function () {
cbstate = JSON.parse(localStorage['CBState'] || '{}');
for (var i in cbstate) {
var el = document.querySelector('input[name="' + i + '"]');
if (el) el.checked = true;
}
var cb = document.getElementsByClassName('timer');
for (var i = 0; i < cb.length; i++) {
cb[i].addEventListener('click', function (evt) {
if (this.checked) {
cbstate[this.name] = true;
}
else if (cbstate[this.name]) {
delete cbstate[this.name];
}
localStorage.CBState = JSON.stringify(cbstate);
});
}
});
})();
Solution 1:[1]
2 things. Put the parens next to your function name and put some logic in your function so that it clears the timeout and resets it. Otherwise you could end up with numereous timers going off if someone unchecks/checks
<input ... onclick="validate()">
In your script, I didn't understand the role for the FOR loop, so I omitted it here.
let timerInt;
function validate() {
clearTimeout(timerInt)
if (document.getElementById('timer').checked) {
timerInt = setTimeout(function() {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, {code: code});
});
}, 501);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kinglish |
