How to control a variable in background script from page (popup) script?
To getting resource each 10 seconds, I am using setTimeout loop in the below code.
But below codes do not stop loop when I unchecked the checkbox in popup page (browser_action).
I expected that when I (check or uncheck) the checkbox in popup, the page_script send message to background script, if background receive stop_loop
message, the background script change settimeout_loop_controller
to false to stop settimeout loop.
But this codes do not react when I click checkbox.
How to communicate between two scripts?
let settimeout_loop_controller = true;
function fetching() {
if (settimeout_loop_controller) {
// if 'settimeout_loop_controller become false, the loop will stop.
fetch("http://url.com/example").then((getval) => { do_something })... ;
setTimeout(fetching, 10000);
} else {
return;
}
}
fetching();
chrome.runtime.onMessage.addListener((message) => {
if message.type === "stop_loop" {
settimeout_loop_controller = false;
}
else if (message.type === "start_loop") {
settimeout_loop_controller = true;
fetching();
}
});
popup script:
let checkbox = document.getElementById("checkbox");
checkbox.onchange((e) => {
if (checkbox.checked) {
chrome.runtime.sendMessage({"type": "start_loop"});
}
else {
chrome.runtime.sendMessage({"type": "stop_loop"});
}
});