'Sending message from a page to Chromium (Edge) extension returns an error

There're a number of similar questions here, but none of them seem to apply to sending messages from a regular web page directly to an extension.

Chrome docs state that this is possible without using content scripts.

I've allowed external callers in manifest.json:

  "externally_connectable": {
    "matches": [
      "http://localhost/*",
      "http://host.local/*"
    ]

But performing a call as follows yields Uncaught Error: Attempting to use a disconnected port object:

port = chrome.runtime.connect(editorExtensionId);
port.postMessage(editorExtensionId, { connect: true },
    function (response) {
        console.log(response.message);
    });

On the other hand, sending messages directly works via chrome.runtime.sendMessage(editorExtensionId, ...) , but in this case I can only reply once, as there's no port with a longer lifetime.

Inside the extension - in background.js - I'm using chrome.runtime.onMessageExternal.addListener. Strangely, I usually get another error message after the first one: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

The page is hosted on http://host.local in both cases.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source