The WebChannel.jsm
JavaScript code module provides an abstraction that uses the Message Manager and Custom Events APIs to create a two-way communication channel between chrome and content code for specific origins (using a specific origin passed to the constructor or a lookup with nsIPermissionManager while also ensuring the scheme is HTTPS).
Components.utils.import("resource://gre/modules/WebChannel.jsm");
listen(Function callback); |
stopListening(); |
send(Object message, EventTarget target); |
id |
String | WebChannel id |
Registers the callback for messages on this channel. Registers the channel itself with the WebChannelBroker.
callback
function(id, message, senderContext)
parameters..send()
methodResets the callback for messages on this channel. Removes the channel from the WebChannelBroker.
Sends messages over the WebChannel id using the "WebChannelMessageToContent" event.
message
senderContext
senderContext
parameter passed to the .listen method.let channel = new WebChannel(webChannelId, Services.io.newURI("https://mozilla.org", null, null)); // receive messages channel.listen(function (webChannelId, message, senderContext) { // send messages channel.send({ data: { greeting: true } }, senderContext); });
Receive Messages from an existing WebChannel in content code
window.addEventListener("WebChannelMessageToContent", function(e) { // receive messages console.log(e.detail); }, true);
Send Messages to an existing WebChannel in chrome code
window.dispatchEvent(new window.CustomEvent("WebChannelMessageToChrome", { detail: { id: webChannelId, message: { something: true } } }));