google-chrome-extensionservice-workercontent-scriptchrome-extension-manifest-v3

Background script: Error: Could not establish connection. Receiving end does not exist


I am trying to send a message from background script to content script in my chrome extension. But it looks like the message gets send before the content script is loaded?

This is the error I get when I am using my extension normally:

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

This is my background script with the tabs.onUpdated function:

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {

    if (changeInfo.url) {
        console.log(changeInfo.url, tabId)
        chrome.tabs.sendMessage(tabId, {
            url: changeInfo.url,
            type: 'URL_CHANGE'
        });
    }
});

This is my content script receive function:

chrome.runtime.onMessage.addListener((obj, sender, response) => {
    console.log('received', obj)
    if (obj.type === 'URL_CHANGE') {
        console.log('testestsetst')
        getAuth()
        getUrlType(obj.url)
    } else if (obj.type === 'AUTH') {
        getAuth()
    } else if (obj.type === 'UN-AUTH') {
        removeAuth()
    }
});

Whenever I run the extension normally I don't see an output from my content script and I get the error as stated above. However, when I debug the background script and step through the code, I get no error and my content script prints everything correctly. Could this be due to the page needing to load? And if so, how do I solve this?


Solution

  • Solved it by checking for tab complete and sending the url through the tab parameter as follows:

    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
        if (changeInfo.status === 'complete') {
            chrome.tabs.sendMessage(tabId, {
                url: tab.url,
                type: 'URL_CHANGE'
            });
        }
    });