Use this event to listen for messages from another part of your extension.
Some example use cases are:
- in a content script, to listen for messages from a background script.
- in a background script, to listen for messages from a content script.
- in an options page or popup script, to listen for messages from a background script.
- in a background script, to listen for messages from an options page or popup script.
To send a message that is received by the onMessage()
listener, use runtime.sendMessage()
or (to send a message to a content script) tabs.sendMessage()
.
Note: Avoid creating multiple onMessage()
listeners for the same type of message, because the order in which multiple listeners will fire is not guaranteed.
If you want to guarantee the delivery of a message to a specific end point, use the connection-based approach to exchange messages.
Along with the message itself, the listener is passed:
- a
sender
object giving details about the message sender. - a
sendResponse()
function that can be used to send a response back to the sender.
You can send a synchronous response to the message by calling the sendResponse()
function inside your listener. See an example.
To send an asynchronous response, there are two options:
- return
true
from the event listener. This keeps thesendResponse()
function valid after the listener returns, so you can call it later. See an example. - return a
Promise
from the event listener, and resolve when you have the response (or reject it in case of an error). See an example.
Note: You can also use a connection-based approach to exchange messages.