0

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.

azs2020
  • 1
  • 2
  • Where is main.js? Is that a content script? – Rojo Dec 15 '20 at 18:11
  • Your active window is probably devtools (it doesn't have tabs). Switch to another window or close devtools. See also [Chrome tabs query returning empty tab array](https://stackoverflow.com/a/63886442) – wOxxOm Dec 15 '20 at 18:11
  • Going off of woxxom, add a `console.log(tab)` just before `sendmessage`. – Rojo Dec 15 '20 at 18:13
  • @Rojo yes, its a content script – azs2020 Dec 15 '20 at 23:29
  • @wOxxOm console.log(tabs) gives an empty array - i tried following the solution you linked, but the error remains – azs2020 Dec 17 '20 at 18:41
  • Well, this is as far as I can guess based on the posted code. Thing is, this fragment doesn't make sense to me in its current form - for example I would expect you to use sender.tab.id instead of chrome.tabs.query, see [onMessage description](https://developer.chrome.com/extensions/runtime#event-onMessage). – wOxxOm Dec 17 '20 at 18:49

0 Answers0