0

Consider that when accessing the example.com page the tabs.onUpdated event is executed three times.

background.js

function sendMsn(msn) {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { "message": msn });
    });
}

var cont = 0;

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if(changeInfo.status === 'complete') {
        // This runs 3 times
        if(cont === 0) {
            sendMsn('ok');//This line is not running
            cont++;
        } 
        sendMsn(cont);
    }
});

content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request);
});

The expected output would be:

Ok
1
2
3

However, what is printed is:

1
1
1

I don't know the reason for the error, but I suspect it's the scope of the cont variable.

John Simon
  • 107
  • 4
  • 1
    1) The background script unloads after several seconds of inactivity, see [this answer](https://stackoverflow.com/a/66618269). 2) Remove chrome.tabs.query and use tabId from the listener's parameters. – wOxxOm May 03 '22 at 12:11

0 Answers0