I have an extension to block websites that are not in the allow list when the extension is enabled. I made a setInterval, but it seems to unload if I close my laptop, the only way to bring it back is to reload the extension. Any thoughts?
var allowonlywebsitesglobal = false;
var websitestoallowglobal = "";
// every time chrome starts
chrome.runtime.onStartup.addListener(function () {
// Interval to run every 5000ms to get data from chrome storage local
setInterval(function () {
// Get the value of allowonlywebsites in chrome storage local
chrome.storage.local.get("allowonlywebsites", function (result) {
// If the result is not undefined
if (result != undefined) {
var allowonlywebsites = result.allowonlywebsites;
saveDataToVar("allowonlywebsites", allowonlywebsites);
}
});
// Get the value of websitestoallow in chrome storage local
chrome.storage.local.get("websitestoallow", function (result) {
// If the result is not undefined
if (result != undefined) {
var websitestoallow = result.websitestoallow;
saveDataToVar("websitestoallow", websitestoallow);
}
});
}, 5000);
function saveDataToVar(dataName, dataValue) {
if (dataName == "allowonlywebsites") {
allowonlywebsitesglobal = dataValue;
} else if (dataName == "websitestoallow") {
websitestoallowglobal = dataValue;
}
}
// Interval to run every 3000ms to check if the user is on a website that is not allowed
setInterval(function () {
// If the user has enabled the option to allow only websites
if (allowonlywebsitesglobal == true) {
// Check if the user is on a website that is not allowed
checkIfWebsiteIsAllowed();
}
}, 3000);
function checkIfWebsiteIsAllowed() {
// Get the value of websitestoallow in chrome storage local
chrome.storage.local.get("websitestoallow", async function (result) {
// If the result is not undefined
if (result != undefined) {
// If the result is not empty
if (result.websitestoallow != "") {
// Split the value of websitestoallow in chrome storage local
var split = result.websitestoallow.split(",");
// Get the current url
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
if (tab === undefined) {
return;
}
if (tab.url.toString().includes("chrome://")) {
return;
}
if (tab.url.toString().includes("chrome-extension://")) {
return;
}
// Get only host of url without any subdomains
var url = new URL(tab.url);
var host = url.hostname;
host = host.replace("www.", "");
console.log(`Checking if - ${host} - is in the array of websites to allow`)
// Check if the host is in the array of websites to allow
if (split.includes(host)) {
// If the host is in the array of websites to allow, do nothing
console.log("DOMAIN OK")
} else {
// If the host is not in the array of websites to allow, redirect to the options page
chrome.tabs.update({ url: "/pages/blocked.html" });
}
}
}
});
}
});