1

I have a chrome MV3 extension . In the background script i am sending a message to the new tab opened onTabUpdated . In content script I am responding to message.

background.js

chrome.tabs.onUpdated.addListener(function (tabId, info, tab) {
        chrome.tabs.sendMessage(tabId, { message:"hellofrombackground" })
});

content-script.js

chrome.runtime.onMessage.addListener(function(e)
{
    if (e.message === "hellofrombackground") console.log(e);
})

manifest.json(relevant)

{
    "manifest_version": 3,
    "permissions": [
        "storage",
        "activeTab",
        "tabs",
    ],
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "content-script.js"
            ]
        }
    ],
}

Now i am getting the below error . It suggests that I am sending message where content script isnt there which is definitely not the case as the new tab i open has the content script and is even logging the message from background.js.

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

Surprisingly when I do the exact same thing in MV2 with minor necessary changes to manifest.json there is no error. What am i missing here?

  • 1
    Your code is incorrect because onUpdated event is fired several times for url and status before the content script is injected both in MV2 and MV3. The fact that it worked for you is weird and may be due to a bug. Depending on what you want to achieve a more reliable approach is to use sendMessage in the content script and listen to onMessage in the service worker. You also need to [re-inject content scripts explicitly](/q/10994324) after reloading/installing the extension. – wOxxOm Jul 26 '23 at 06:55

0 Answers0