A Port
object represents one end of a connection between two specific contexts, which can be used to exchange messages.
One side initiates the connection, using a connect()
API. This returns a Port
object. The other side listens for connection attempts using an onConnect
listener. This is passed a corresponding Port
object.
Once both sides have Port
objects, they can exchange messages using Port.postMessage()
and Port.onMessage
. When they are finished, either end can disconnect using Port.disconnect()
, which will generate a Port.onDisconnect
event at the other end, enabling the other end to do any cleanup required.
You can use this pattern to communicate between:
- different parts of your extension (for example, between content scripts and background scripts)
- between your extension and a native application running on the user's computer.
- between your extension and a different extension
You need to use different connection APIs for different sorts of connections, as detailed in the table below.
Connection type | Initiate connection attempt | Handle connection attempt |
---|---|---|
Background script to content script | tabs.connect() |
runtime.onConnect |
Content script to background script | runtime.connect() |
runtime.onConnect |
Extension to native application | runtime.connectNative() |
Not applicable (see Native messaging). |
Extension to Extension | runtime.connect() |
runtime.onConnectExternal |