There have been quite a few similar questions on setInterval in background.js in a Chrome extension but none of the answers worked for me. I have a simple extension that checks connectivity to a server by calling an API and checking whether there is a 200 response and then updating the extension icon in the tray accordingly.
background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.browserAction.setIcon({path: "/images/checking.png"});
console.log('VPN check extension started');
// main block - make API calls periodically and monitor the server response
async function ping() {
try {
const response = await axios.get('http://[IP]/api/v1/ping', {
timeout: 4000
});
access = response.status;
if (access == 200) {
chrome.browserAction.setIcon({path: "/images/OK_53017.png"});
} else {
chrome.browserAction.setIcon({path: "/images/not_OK.png"});
}
} catch (error) {
chrome.browserAction.setIcon({path: "/images/not_OK.png"});
}
}
window.setInterval(ping, 1000 * 10);
});
chrome.runtime.onStartup.addListener(() => {
chrome.browserAction.setIcon({path: "/images/checking.png"});
console.log('VPN check extension started');
// main block - make API calls periodically and monitor the server response
async function ping() {
try {
const response = await axios.get('http://[IP]/api/v1/ping', {
timeout: 4000
});
access = response.status;
if (access == 200) {
chrome.browserAction.setIcon({path: "/images/OK_53017.png"});
} else {
chrome.browserAction.setIcon({path: "/images/not_OK.png"});
}
} catch (error) {
chrome.browserAction.setIcon({path: "/images/not_OK.png"});
console.log('error');
}
}
window.setInterval(ping, 1000 * 10);
});
Neither onStartup nor onInstalled works well - when I restart Chrome or switch windows the extension becomes unresponsive.
Manifest
{
"name": "Access status",
"version": "0.0.3",
"description": "Chrome extension to check if access to the network is provided.",
"background": {
"scripts": ["axios.min.js", "background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/checking.png"
},
"icons": {
"16": "images/checking.png"
}
},
"permissions": ["<all_urls>"],
"manifest_version": 2,
}
content.js is empty
Any suggestion how to make it work, regardless of which tab is in focus or which window is open and get it to set the interval when fresh Chrome opens? Thanks