chrome.tabs.onUpdated.addListener gives “Could not establish connection”-error

I’m learning how to make Chrome-extensions (manifest v3) and I’m trying to understand how “addListener” works, more specifically “chrome.tabs.onUpdated.addListener”.

One thing I don’t understand is why Chrome throws this error at me all the time:

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

I feel that I’m missing something very important on how messages work between backgrounds.js and content.js. Any suggestions?

In backgrounds.js I have this code:

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

  if (changeInfo.status === 'complete' && tab.status === 'complete' && tab.url) {
    chrome.tabs.sendMessage(tab.id, { type: "RELOADED" });
    
  }
});

And in my content.js I have this code:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "RELOADED") {

    let prismicUrl = document.location.href;
    
    const prismicUrlMustExist = /~b/; // Normal
    const prismicUrlMustExist2 = /&b=/; // Efter sökning
    const articleUrlMustExist = /--ec/;
   
    if (prismicUrlMustExist.test(prismicUrl) || prismicUrlMustExist2.test(prismicUrl)) {
      console.info("Hittade artikel. Väntar en sekund.");
      setTimeout(() => {  initiate(); }, 1000);
      console.info("Försöker hitta sidebar.");
    } else if (articleUrlMustExist.test(prismicUrl)) {
      console.info("Hittaden artikel på sajten.");
      setTimeout(() => {  initiate_article(); }, 1000);
    } else {
      console.warn("Error: hittade ingen kompatibel sida.");
    }
  }
});```

Feel free highlight any improvements I can make to do this in a more effective way, or tell if you need more information about the code.


Well, I'm stuck. I have tried reading on the subject and understand how to do it differently, but I didn't find anything that stuck well enough for me.