runtime.onUserScriptMessage
Use this event to listen for messages sent from one of the extension's USER_SCRIPT worlds.
In Firefox, this event requires the userScripts permission. In Chrome, the event is always present, including in extensions that don't declare the userScripts permission.
A user script can only send messages using runtime.sendMessage from a USER_SCRIPT world that is configured by userScripts.configureWorld() with messaging set to true.
Along with the message, the listener is passed:
- a
senderobject with details about the message sender. - a
sendResponsefunction the listener can use to send a response back to the sender.
Syntax
browser.runtime.onUserScriptMessage.addListener(listener)
browser.runtime.onUserScriptMessage.removeListener(listener)
browser.runtime.onUserScriptMessage.hasListener(listener)
Events have three functions:
addListener(listener)-
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
listener-
The function called when this event occurs. The function is passed these arguments:
message-
object. The message. This is a JSON-ifiable object. sender-
A
runtime.MessageSenderobject representing the sender of the message. sendResponse-
A function to call, at most once, to send a response to the message. The function takes one argument, which is any JSON-ifiable object. This argument is passed back to the message sender.
If you have more than one
onUserScriptMessagelistener in the same document, then only one can send a response.To send a response synchronously, call
sendResponsebefore the listener function returns. To send a response asynchronously, do one of these:- keep a reference to the
sendResponseargument and returntruefrom the listener function. You can then callsendResponseafter the listener function has returned. - return a
Promisefrom the listener function and resolve the promise when the response is ready.
- keep a reference to the
Examples
In this example, a user script in a USER_SCRIPT world with the ID myScriptWorld sends a message to the extension that registered it:
// The user script
// Send a message to the extension that registered the user script
browser.runtime.sendMessage("my message");
// The extension that registered the user script
function handleMessage(message, sender) {
// check that the message originated from "myScriptWorld" world
if (sender.userScriptWorldId === "myScriptWorld") {
// process message
console.log(message);
}
}
browser.runtime.onUserScriptMessage.addListener(handleMessage);
Example extensions
Browser compatibility
Loading…