I am working on a Chrome extension and about to implement some message passing between my background page and the content script, it will require about 3 messages (content -> background -> content -> background) which all occur in a synchronized order.
I'm not sure what message passing API i should use for this since i don't really understand the difference between the Port API and the normal chrome.runtime
API. is there something i can't do with the runtime.sendmessage
that i can do with the Port.postMessage
? any major differences that might make me choose one over the other?
Port is a reusable, bidirectional connection.
Single messages follow the same scheme, and don't care about the state between invocations:
sendMessage
-> onMessage
(optionally ->) sendResponse
-> callback of sendMessage
You can do most anything by that scheme.
There are maybe three aspects of Ports that make them interesting that I can think of.
sendMessage
is a broadcast operation.
In case of runtime.sendMessage
, it's sent to all active pages that are part of the extension. Oftentimes, only one will listen (the background page), but everyone will receive it. So if you have, say, a popup, or an options page open - everyone receives that. You could use a Port to save a tiny bit of resources, or isolate an instance of a page.
In case of tabs.sendMessage
, it will by default send to all frames within that tab. You can specify a frameId
if you know it, but suppose you don't, and you're broadcasting to all frames, then determine which frame is correct - you can maintain a Port to that frame.
An open Port keeps an Event Page awake. This can be useful if you're doing something asynchronous that risks unloading the Event Page. This is also a disadvantage if you don't really care about the Event Page staying awake - it prevents the improvement provided by
A Port is a "death alarm": in case the context that's on the other end ceases to exist (e.g. the page with the context script was unloaded), you'll be notified by onDisconnect
.
Unless you need any of the above, you can go with the simpler sendMessage
-onMessage
communication.
For your purposes, it would be two calls to sendMessage
from the content script (as it initiates the connection) and replies from background in sendResponse
. Don't forget the nuance about async responses if you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With