A port acts as a versatile, two-way connection.
Individual messages follow a consistent pattern and do not rely on the state between interactions:
sendData
-> onReceive
(optional ->) respondToRequest
-> callback of sendData
You can achieve a wide range of tasks using this approach.
There are several unique characteristics of ports that I find intriguing.
sendData
functions like a broadcast operation.
When utilizing runtime.sendMessage
, the message is distributed to all active pages within the extension. While typically only one page (the background page) will respond, every page receives the message. This feature allows for resource optimization or the isolation of specific instances of a page.
If you use tabs.sendMessage
, the message is automatically sent to all frames within the tab. If necessary, you can specify a frameId
to target a specific frame. However, when broadcasting to all frames without specifying, you can establish a port to maintain communication with the correct frame.
An open port keeps an Event Page active. This can be beneficial in scenarios where asynchronous tasks could potentially unload the Event Page. On the other hand, if maintaining the Event Page's activity is unnecessary, it may hinder performance improvements provided by...
A port serves as a "death alarm": if the counterpart context ceases to exist (e.g., the page containing the context script unloads), the onDisconnect
event will notify you.
Unless any of these features are required, a straightforward sendData
-onReceive
communication setup suffices.
In your scenario, initiating the connection from the content script would involve two calls to sendData
, with responses from the background script in respondToRequest
. It is essential to consider the... intricacies of async responses.