Mozilla's getting a new look. What do you think? https://mzl.la/brandsurvey

WebChannel.jsm

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");

Constructor

WebChannel(String webChannelId, nsIURI originOrPermission);
2nd argument is a valid origin that should be part of requests for this channel.
WebChannel(String webChannelId, string originOrPermission);
2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. Note that in addition to the permission manager check, the request must be made over https.

Method overview

listen(Function callback);
stopListening();
send(Object message, EventTarget target);

Attributes

id String WebChannel id

Methods

listen()

Registers the callback for messages on this channel. Registers the channel itself with the WebChannelBroker.

Parameters
callback
Callback function containing function(id, message, senderContext) parameters.
  • id - WebChannel id of the incoming messages
  • message - incoming message object
  • senderContext - incoming message context - this should be treated as an opaque object and passed to the .send() method

stopListening()

Resets the callback for messages on this channel. Removes the channel from the WebChannelBroker.

Parameters
None

send()

Sends messages over the WebChannel id using the "WebChannelMessageToContent" event.

Parameters
message
The message object that will be sent
senderContext
The senderContext parameter passed to the .listen method.

Examples

Setting up a WebChannel between chrome code and a webpage

Chrome code

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);
});

Webpage code

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
    }
  }
}));

See also

Document Tags and Contributors

Tags: 
 Contributors to this page: Markh, oyiptong, greiner, mnoorenberghe, vladikoff
 Last updated by: Markh,