Chrome extensions often need a way for their components (content scripts, service workers, and web pages) to communicate with each other. The messaging feature in chrome extensions enables this communication through message passing, allowing both extensions and content scripts to listen for and respond to messages on the same channel.
To send a single message to another part of a chrome extension and optionally receive a response, use the runtime.sendMessage()
or tabs.sendMessage()
methods. These methods allow sending a one-time JSON-serializable message from a content script to the extension or vice versa.
sendResponse()
is only valid if used synchronously or if the event handler returns true
for an asynchronous response.To create a reusable long-lived message passing channel, call runtime.connect()
or tabs.connect()
. Each end is assigned a runtime.Port
object for sending and receiving messages through that connection.
port.postMessage()
method to send messages through the connection.runtime.onConnect
event listener.runtime.Port.onDisconnect
event to handle connection closures.Chrome extensions can communicate with other extensions using the messaging API, allowing them to expose a public API. Use the runtime.onMessageExternal
and runtime.onConnectExternal
methods to listen for incoming requests and connections from other extensions.
runtime.sendMessage()
or runtime.connect()
."externally_connectable"
manifest key.runtime.onMessageExternal
or runtime.onConnectExternal
APIs.Chrome extensions can exchange messages with native applications registered as a native messaging host. This allows extensions to communicate with native applications running on the user's system.
When dealing with messaging in chrome extensions, it's important to consider the following security aspects:
JSON.parse()
and innerText
instead of eval()
and innerHTML
to avoid XSS vulnerabilities.Ask anything...