runtime.Port

A Port object provides a dedicated messaging channel between two specific endpoints.

You can use a Port to communicate:

  • within your extension (for example, between content scripts running in a particular tab and your extension's background scripts)
  • with other extensions
  • with web pages.

You create a Port object by calling runtime.connect() or, if you are connecting to content scripts running in a tab, by calling tabs.connect().

The other end can listen for the new port using runtime.onConnect for intra-extension ports, or runtime.onConnectExternal for extension-to-extension or page-to-extension ports.

Each end can then send messages using Port.postMessage() and receive messages using Port.onMessage.

Each 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.

Type

Values of this type are objects. They contain the following properties:

name
string. The port's name, defined in the runtime.connect() or tabs.connect() call that created it.
disconnect
function. Disconnects a port. One end can call this when they have finished with the port. It will cause onDisconnect to be fired at the other end. This is useful if the other end is maintaining some state relating to this port, which can be cleaned up on disconnect.
onDisconnect
events.Event. This has the addListener() and removeListener() functions common to all events in WebExtensions. Listener functions will be called when the other end has called Port.disconnect(). This event will only be fired once for each port.
onMessage
events.Event. This has the addListener() and removeListener() functions common to all events in WebExtensions. Listener functions will be called when the other end has called Port.postMessage(). The listener will be passed the JSON object that the other end passed to Port.postMessage().
postMessage
function. Send a message to the other end. This takes one argument, which is a JSON object representing the message to send. It will be delivered to anyone listening to the port's onMessage event.
senderOptional
runtime.MessageSender. Contains information about the sender of the message. This property will only be present on ports passed to onConnect/onConnectExternal listeners.

Browser compatibility

EdgeFirefoxChromeOpera
Basic support?45.0Yes33
Firefox
Basic support48.0

Acknowledgements

This API is based on Chromium's chrome.runtime API. This documentation is derived from runtime.json in the Chromium code.

Document Tags and Contributors

 Contributors to this page: wbamberg
 Last updated by: wbamberg,