0

I'm writing a chrome extension, but can't send messages from the background script to the content script. I keep getting the error Could not establish connection. Receiving end does not exist.

I have read the chrome.runtime and chrome.tabs docs, but it doesn't work as expected.

This is my manifest file:

{
  "name": "chrome extension",
  "version": "1.0.0",
  "description": "Extension",
  "icons": {
    "16": "images/16.png",
    "32": "images/32.png",
    "48": "images/48.png",
    "128": "images/96.png"
  },
  "manifest_version": 3,
  "author": "",
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "permissions":[
    "bookmarks",
    "storage",
    "tabs",
    "activeTab"
  ],
  "action":{
      "default_popup": "index.html",
      "default_title": "Extension"
  },
  "commands": {
    "switch-to-folder-1": {
      "suggested_key": "Ctrl+Shift+1",
      "description": "Switch folder 1"
    }
  }
}

This method is written in the background script:

chrome.commands.onCommand.addListener(async (command) => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true})
  const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
  console.log(response);
});

and this one in the content script (which is included programmaticaly, not via the manifest file):

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log(
    sender.tab
      ? 'from a content script:' + sender.tab.url
      : 'from the extension'
  );
  if (request.greeting === 'hello') sendResponse({ farewell: 'goodbye' });
});

So I expect that when I press Ctrl+Shift+1, that the command fires, which does work. Then it should send a message to the content script and log the response to the console which should be { farewell: 'goodbye' }.

What I get instead is an Uncaught (in promise) error: Could not establish connection. Receiving end does not exist. Regardless of which tab I am on, how many times I reload the extension... always this error.

  • "which is included programmaticaly": how have you done this because this will most likely be the cause? – Andy May 23 '23 at 10:39
  • @Andy I just included the script in the index.html file like this `` this should have the same effect no? – AspiringMainframeDev May 23 '23 at 10:43
  • From [this answer](https://stackoverflow.com/questions/12265403/passing-message-from-background-js-to-popup-js) it's because the pop up doesn't have a tab id. You might find following the recommended answer useful. – Andy May 23 '23 at 10:54
  • Doesn't work like that, but thanks anyway – AspiringMainframeDev May 23 '23 at 11:04
  • You don't have any content scripts now. The popup is not the web page so its scripts aren't content scripts. You need to inject the content script via chrome.scripting.executeScript. Then you can send a message. – wOxxOm May 23 '23 at 15:41

0 Answers0