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.