Friday, March 29, 2024

Working with Channel Messaging APIs in HTML5

Channel messaging is a HTML5 specification that specifies that compliant browsers will support enabling code running in different contexts to communicate directly via ports.

 

Communication happens over pipes (channels), with a port at either end, which allows messages sent in one port are received at the other.

Messages are delivered as DOM events.

 

Compliant browsers implement the following interfaces.

  • ·         The MessageChannel Interface which is defined as:

[Constructor]

interface MessageChannel {

  readonly attribute MessagePort port1;

  readonly attribute MessagePort port2;

};

 

where port1 is the first port and port2 is the second port.

  • ·         The MessagePort interface which is defined as:
interface MessagePort : EventTarget {
  void postMessage(any message, optional sequence<Transferable> transfer);
  void start();
  void close();
 
  // event handlers
  [TreatNonCallableAsNull] attribute Function? onmessage;
};
MessagePort implements Transferable;

 

The postMessage API is used to post a message through the channel.

The start API beings dispatching messages.

The close API disconnects the ports.

 

  • ·        onmessage event – which is triggered when message data is received.

 

How channel messaging works

A channel object is created by calling the constructor of MessageChannel class.

var newChannel = new MessageChannel();

 

Once the channel is created, the other port is sent to the remote code, using the postMessageAPI. The other port is retained as the local port.

The remote port can sent as under:

otherBrowsingContext.postMessage(‘hello – take this port’, ‘http://foobar.com’, [newChannel.port2]);

 

Now, we can send messages by calling the API postMessage on port1.

newChannel.port1.postMessage(‘hello from port1’);

 

To receive messages, we need to listen to message events.

newChannel.port1.onmessage = handleMessageFunction;

function handleMessageFunction(event)

{

alert(“Message received : “ + event.data)

}

 

 

When MessagePorts are not used, it is recommended to call close() API to allow resources to be recollected.

 

 

Support for Channel messaging

As of April 2014, channel messaging is supported by latest versions of all browsers except Firefox, Opera Mini and Firefox for Android.

 

Summary

In this article, we learned about channel messaging. I hope you have found this information useful.

 

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured