I am trying to make a chrome extension that blocks certain sites for a specified time based on user input. The timer stops when the popup is closed, so I tried to send the user defined input from the content script to the background script, and have the background script send the updated time back to the content script to be displayed. However, I keep getting "cannot read property of id of undefined" error when using chrome.tabs.sendMessage in the background script.
//background.js
chrome.runtime.onMessage.addListener((request) => {
let blockRequest = function() {
return {cancel: true};
}
if (request) {
chrome.webRequest.onBeforeRequest.addListener(
blockRequest,
{urls: ["https://github.com/"]},
["blocking"]
);
let seccount = (request.msg) / 1000; //request.msg is time sent by content script
let starttime = new Date().getTime();
let intId = setInterval(sectimer, 100);
function sectimer() {
let remaining = Math.floor((seccount*1000 - (new Date().getTime() - starttime))/1000);
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {msg: remaining}) //error here, cannot read property of undefined
});
if (remaining <= 0) {
clearInterval(intId);
}
}
//main.js (content script)
chrome.runtime.onMessage.addListener((request) => {
if (request) {
let min = Math.floor(request.msg / 60);
let seconds2 = (request.msg) % 60;
document.getElementById("button1").innerHTML=min + " minutes " + seconds2 + " seconds left!";
}
})
I am not even sure if this is the best way to update the html each second with the correct time, so feel free to comment on that as well.