Using runtime.sendMessage API from webpages

webextensions-api

(Murat Toygar) #1

I am currently migrating a chrome extension to firefox by using mozilla’s webextension-polyfill library. The problem is that firefox addons cannot communicate with webpages using runtime.message API. In chrome, one can specify externally_connectable URL’s and send message to background script’s listener.

When I look up the docs&forums for an alternative, the suggested way is to send a window message from webpage and listening it from the content scripts. However, even mozilla docs discourage this implementation. (source: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Using_window.postMessage_in_extensions)

Moreover, we also need to return the result of background message listener to the webpage. With window.sendMessage API doing this is not so inspiring. Chrome does this by sending response to the callback function which is a parameter of runtime.sendMessage.(callbacks are also not inspiring :slight_smile: )

Is there any other way to communicate with a specified webpage from addon or is there any plan of adding webpage messaging support to addons?


(Martin Giger) #2

You could of course have a dedicated API your extension could use (think rest/websocket) - however authenticating that it is actually your extension has similar issues like postMessage.

You can find the bug to implement externally_connectable at https://bugzilla.mozilla.org/show_bug.cgi?id=1319168


(Murat Toygar) #3

Hi Martin,

I actually didn’t quite get what you mean. What do you mean by having a dedicated API? Should I write a simple messaging API based on window.postMessage? I also didn’t get the authentication part.


(Martin Giger) #4

I meant having a “server side API” - but as I said, this is mostly as reliable as having a postMessage communication protocol. The problem is to verify authenticity, thus authentication.


(Murat Toygar) #5

I have a server side API and can authenticate to it through extension. But a communication between extension and webpage through a server brings to much latency and complexity. I do not want that if it is possible.

Also, I look over for the bug that you quoted and try to exploit it. However, the global browser variable is only accessible from extension side, my webpage script cannot access it. Therefore I cant even call, browser.runtime.sendMessage from the webpage.


(Martin Giger) #6

The bug I linked is specifically to add the API you’re asking about. So yes, nothing to use yet.


(Murat Toygar) #7

According to the comment above this bug might be unlikely to resolve :slightly_frowning_face:


(Juraj Masiar) #8

Regarding the window.postMessage - the issue here is only if you would transfer some sensitive data or if your API would allow to perform some “dangerous” operations. But if this is used only for some basic communication, like setting a label name or registering button click, I would say it’s a good solution.