Could not establish connection. Receiving end does not exist

269 views
Skip to first unread message

Najam Khan

unread,
Mar 5, 2025, 1:36:05 PM3/5/25
to Chromium Extensions
I'm building an extension and trying to do message passing between browser and webpage. I've an event that's emitted from my site `<foo.com>`. The event is implemented something like this:

```javascript
window.postMessage('solar:message', ...)
```

I want to get that message and show it in panel.html i.e, the browser devtools tab similar to how you see the logging information under "Console" tab.

I've pretty much looked at all possible reasons for this issue and seems a bit unique scenario in my case or something very stupid. Everytime I refresh I get the following error: `Could not establish connection. Receiving end does not exist`

Here's the code sample if anyone likes to look into it.
https://gist.github.com/najamkhn/b58c7e3fce7861a92d4a7491be47ef30


woxxom

unread,
Mar 5, 2025, 5:40:11 PM3/5/25
to Chromium Extensions, Najam Khan
  1. When your content script runs and your devtools panel is not open, connect() fails because there's nothing to connect to. The simplest solution is to use chrome.runtime.sendMessage instead.
  2. No need for the background script here because the panel can send messages directly to the content script or use devtools.js instead as shown in https://stackoverflow.com/a/72902614
  3. When you reload the extension in chrome://extensions page it breaks connection with the old content scripts so they can't open ports or send messages. The solution is to reinject the content scripts into open tabs (https://stackoverflow.com/a/11598753) and unregister the listeners in the orphaned content scripts which you can do by checking whether chrome.runtime.id became undefined:
addEventListener('message', function onMessage(event) {
    removeEventListener('message', onMessage);
    return;
  }
  .........
});

Najam K

unread,
Mar 6, 2025, 4:21:48 AM3/6/25
to Chromium Extensions, woxxom, Najam Khan
Thank you so much, it 1 & 2 solved the issue related to connection. However, about point-3, I need it to capture the events emitted from DOM (via `window.postMessage('solar:...')`) so thats why I've a listener in content.js however it doesn't seem to able to capture anything emitted from DOM unless I manually run postMessage in console.

woxxom

unread,
Mar 6, 2025, 5:30:10 PM3/6/25
to Chromium Extensions, Najam K, woxxom
Sounds like you didn't re-inject the content script after reloading the extension, see the link in #3: https://stackoverflow.com/a/11598753
Reply all
Reply to author
Forward
0 new messages