HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging

In the origin of web standards, HTML5 has been emerged in very dramatic way and the reason behind this is the incorporation of distinct impressive features that include video playback, drag-and-drop and geolocation. HTML5 enables developers to build rich internet applications even without entangle the third party browsers plug-ins and APIs.

Therefore, in context of powerful HTML5 features, in the coming next section of this post HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging we are going to discuss about HTML5 Web Messaging.

Web messaging is an excellent method to share a document without DOM in context of separate browser as well as being revealed to baleful cross-origin scripting. Web messaging never used to expose DOM directly in contrast of other cross-site communication (cross-domain XML Http request as well as insertion of dynamic script. Let’s take a look over this illustration. If you are supposed to send some data to an advertise contained in an iframe, which is being hosted by third-party server. However, within the iframe, when the parent document attempt to read variables or vice-versa, the browser will drive a security exception. Hence, the web messaging make us enable to confer with this through sending or delivering the data across as message event.

However, before we proceed further, let me put some more lights on web messaging about which this tutorial post HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging has been targeted. So, we can say that web messaging as an integration of two slightly distinct system, named Cross Document Messaging and Channel Messaging. Cross-document messaging is referred by its syntax as window.postMessage() as well as channel messaging is also called as MessageChannel.

Now, go ahead to take a look over this HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging in detail that might be proved as highly useful and worthy for you and most probably reduce your lot of efforts towards this endeavor.

Message Events

In the bottom line of web messaging, first of all I would recommend to understand the object of message events that will be verily helpful to you. Basically, message events are fired by Cross-document messaging, MessageChannel, web sockets and server-sent events. Message events is the Message Event Interface that incorporates five read only facets:

Data: comprises an arbitrary data string that is sent by originating script.

Origin: referred as string that incorporates document’s scheme origin, name of the domain and port e.g. https://domain.example:80

lastEventId: this string has contains an unique identifier towards the current message event.

Source: This also may be referred as WindowProxy object. It is the reference of the origin of document’s window.

Ports: it is an array constituting a MessagePort with sent message.

When, we conferred with cross-document messaging events and channel messaging, we found the lastEventId value is always an empty sting; however employed to server-sent events. In case of no ports with sent message, the value of ports attributes will concord as an array of zero length. However, Message events are not cancelable, don’t bubble and have no default action.

Cross-Document Messaging

As we have took a look over Message event, let’s proceed with cross-document messaging.

Sending a cross-document message

In order to send a cross-document message, the first effort you would like to put is to create a new browsing context. You may accomplish it either by referencing an iframe or by generating a new window. Now, you can successfully send a message via it employing the postMessage() method, which requires two arguments for cross-document messaging.

Message: the message to send.
TargetOrigin: the origin of the message to be send.

However, the parameters of messages are not limited only upto strings, but structured and data objects (like File and ArrayBuffer), or arrays may be also sent as messages. One thing should be marked the IE 8 and 9 as well as Firexfox 3.6 and below can support strings.

The origin of the receiving documents is known as targetOrigin. Until the origin of the receiving browsing context do not affirm with one provided in targetOrigin, browser will not send any message. Even, it is possible to circumvent the condition in account of * wild card character. But it is potential to leak the information, however, you are required to designate a specific target origin.
Also, it is possible to limit sending of message to the same origin via setting the targetOrigin argument to /, however, only Opera supports this at the time of publication.

Now, take a look over this illustration, here you can send a message from your parent document to an iframe contained document. Even your document would share the same origin, you would required to set the targetOrigin value to rather than of /, to achieve cross-browser compatibility. Using the origin as the target of your lived document on another domain, you can send a message.

Receiving a cross-document message

Sending an event is of course not sufficient but is only half of the process. However, you would also required to employ these events in a receiving document. As we discussed above, that postMessage() also called message event is delivered in the receiving document. Further, we can consider for the message event as displayed below.

Detecting When the receiving document is ready

In the above example we discussed above, window.postMessage() adjure in event employer which required user interaction. However, to employ this in better way, you are supposed to ensure that the scripts designated in target browsing context are ready to receive our messages. In context of confirmation, you can send a message event to parent document whenever you are supposed to load a new document.

Now, go through this sample code where, we are about to open a new window. When the document loads in that window, it will send a message to the opening window. You may also assume that your markup incorporates a button element, that’s it through which we will open a new window.

When the button is clicked, the clickhandler feature will open a new window as well as your messageHandler function tends the listener to listen the message in newly opened window. This point should be marked that event.source is a object of WindowProxy and represents the opened window.

In the newly opened window, you will be able to listen DOMContnetLoaded event – as seen below. Further, when it is fired, it will implement window.postMessage() in order to “notify” the opening document which is accessible to receive messages.

Channel Messaging

Channel Messaging offer two-way and direct communication between browsing contexts. The DOM is not directly exposed with cross-document messaging but at each end there is a port. The data being sent from one port is the input in other and vice-versa.

Primarily, Channel Messaging is worthy for multiple origins communication. Take a look over this scenario. We have a document at http://socialsite.example constituting the content from http://games.example embedded in one iframe, and content from http://addressbook.example in another.

Now, you are supposed to send a message to your games site from your address book site. You might employ the proxy of social site. However, it stands out with same level of trust as of your social site. Next, your social site would either has to trust for every request or filter them for you.

However, http://addressbook.example and http://games.example might communicate directly in account of channel messaging.

The MessageChannel and MessagePort Objects

When you buil a MessageChannel object, in the mean time you are creating two interrelated ports. First one remain open at your sending side as well as another will be carried to other browsing context.

Each port is a object of MessagePort incorporating three distinct available methods.

  • postMessage(): posts a message by the channel.
  • start(): Begins the dispatch of messages received on the port.
  • close(): Closes and deactivates the port.

MessagePort objects also comprises onmessage event attribute, that is useful to define an event handler function rather than of including an event listener.

Sending ports and messages

Let’s take a look over an illustration that concerns with communicating with channel messaging. Here, we are going to employ a scenario of same as described above; a document having two iframes. We will send messages from one iframe to another with account of MessageChannel objects and ports.

All documents in the examples linked above have the same origin, however, the process is the same for cross-origin communication.

In the first iframe, we follow below listed steps.

  • Create a new MessageChannel object
  • Transfer one MessageChannel port to parent document where it will be carried out to other iframe.
  • For remaining port define an event listener to cultivate the messages sent from other iframe.
  • In order to receive messages open our port.

Now, we will assign a function for everything that will be adjure when DOM is ready.

Now, we will listen incoming message and associated port in our parent document. If it is being received, we will post a message to our second iframe, and forwarded our port with that message.

Finally, in account of our second iframe, we are capable to manage the message from our parent document as well as post a message to the port. The portMsgHandler will handle the message being sent from from this port and function in our first document.

Hopefully, this post HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging might be very valuable and useful tutorial for Web messaging using HTML5. As it not only reduce your efforts but also saves your precious time. Finally, I would like to conclude that In practice, you must analyze for MessageChannel whether it supported. Also, check your message event was sent by an origin you expect.


HTML5 Web Messaging: Fresh Tutorial for Cross Document Messaging

Steven Bowen

Steven Bowen is an ardent team member of No-refresh - Web to Print Design Tool Provider Company bestowed with professionalism in to develop fully-functional solutions. Having adroitness in this arena, he has served an array of blogs that are basically based on the technology advancement & improve the end users’ information level.