Path: blob/main/files/en-us/mozilla/add-ons/webextensions/api/runtime/onconnect/index.md
6565 views
------{{AddonSidebar()}}
Fired when a connection is made with either an extension process or a content script.
Syntax
Events have three functions:
addListener(callback): Adds a listener to this event.
removeListener(listener): Stop listening to this event. The
listenerargument is the listener to remove.
hasListener(listener): Checks whether a
listeneris registered for this event. Returnstrueif it is listening,falseotherwise.
addListener syntax
Parameters
function: A callback function that will be called when this event occurs. The function will be passed the following arguments:
port: A {{WebExtAPIRef('runtime.Port')}} object connecting the current script to the other context it is connecting to.
Browser compatibility
{{Compat}}
Examples
This content script:
connects to the background script, and stores the
Portin a variablemyPortlistens for messages on
myPort, and logs themsends messages to the background script, using
myPort, when the user clicks the document
The corresponding background script:
listens for connection attempts from the content script
when it receives a connection attempt:
stores the port in a variable named
portFromCSsends the content script a message using the port
starts listening to messages received on the port, and logs them
sends messages to the content script, using
portFromCS, when the user clicks the extension's browser action
{{WebExtExamples}}
Note: This API is based on Chromium's
chrome.runtimeAPI. This documentation is derived fromruntime.jsonin the Chromium code.