Click here to Skip to main content
11,935,664 members (62,186 online)
Click here to Skip to main content
Add your own
alternative version


35 bookmarked

HTML5 WebMessaging Experiment

, 5 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
HTML5 WebMessaging provides a simple, efficient, elegant and secure solution for Cross-Domain communication in client side, this article is an experiment for it.


As web developers, sometimes we easily encounter one problem: Cross-Domain communication, conforming Same-Origin-Policy, JavaScript code cannot access code stay in different domain (or sub-domain) or protocol (HTTP/HTTPs) or port, so there was no direct (or I can say: simple) way to achieve Cross-Domain Communication. However, those kinds of requirements do happen: page A and page B are in different domains,  B is "embedded" in A, i.e., there is an "iframe" in page A whose "src" is page B's URL, now page A wants to control page B and vice-versa. 

By limiting the solution to be done by 100% client JavaScript, beforehand HTML5, there are a number of tricky "hacks", such as:

  1. URL long polling: Container page A changes the iframe page B's URL hash, and B periodically checks the hash, once the hash changed, it takes action according to the contracted hash value. [BTW, the pattern can be revised to be non-polling by HTML5 onchashchange event]
  2. CrossFrame, a Safe Communication Mechanism Across Documents and Across Domains.
  3. Window Size Monitoring: Update the iframe's window size once, and the containing window subscribes its "onresize" event then takes corresponding action(s). Google Mapplets adopted this pattern.

Well, personally I really don't like all of them... either inelegant, or violates the original functionalities of DOM elements, or too complicated. I believe many people don't like them too even the pattern inventors I bet... That why WHATWG created Cross-Domain communication in HTML5: Web Messaging.

As an HTML5 crazy advocator I like it very much, complete client communication, no server impact, efficient, secure (at least in theory).

How To

"Child" can be an iframe or an popup window by invoking, "parent page" A contains source code like below:

<iframe id="ifr" src=""  onload="sendCommand();">
	No frame!

Notice, make sure to post message only when the iframe is loaded, otherwise the contentWindow will be still in the same domain with the container page.

Child page B contains code like below:

<input type="button" value="Cross domain call"  onclick="sendMsg();" />

window.addEventListener("message", receiveMessage, false);

function receiveMessage(evt) {
    console.log("Page B received message from origin: %s.", evt.origin);
    console.log("Event data: %s",;
    //evt.source will be a window who sent the message,
    //it can be used to post message to it

    // Take action(s)

The demo code above is one direction: parent sends message to child (iframe), actually bi-directional message transfer can also be done, similar with "Parent control child", child page posts message to container window, the only difference is to call "parent.postMessage".

function receiveMessage(evt) {
    evt.source.postmessage("Hello caller");
    // or parent.postmessage("Hello parent");

Web Messaging Essential

In a nutshell, HTML5 Web Messaging is a suite of JavaScript API exposed by web browser, to communicate between different browsing context, when JavaScript code in one browser tab/window tries to deliver a message to another tab/window, web browser locates the target tab/window under the specified domain, and file a MessageEvent (which inherits from DOMEvent) to the target tab/window, so if the target tab/window already subscribed the message event, it will gets notified, eventually the message got delivered through

Live Demo

I've done a demo in my dev machine, I override my local hosts file to let,, and all point to

I prepared a Container page which contains the code below:

<h3>HTML5 Cross-Domain post message demo</h3>

<p id="infoBar">

<div id="wrapperA">
		<input type="text" id="txtA" />
		<input type="button" value="Post Message"  
		onclick="postMsgToIfr('A');" />
		<iframe id="ifrA" src=""></iframe>

<div id="wrapperB">
		<input type="text" id="txtB" />
		<input type="button" value="Post Message"  
		onclick="postMsgToIfr('B');" />
		<iframe id="ifrB" src=""></iframe>

<div id="wrapperC">
		<input type="text" id="txtC" />
		<input type="button" value="Post Message"  
		onclick="postMsgToIfr('C');" />
		<iframe id="ifrC" src=""></iframe>

<div style="CLEAR: both">

	<script type="text/javascript">
	window.addEventListener("message", receiveMessage, false);

	var infoBar = document.getElementById("infoBar");
	function receiveMessage(evt) {
		infoBar.innerHTML += evt.origin + ": " + + "";

	function postMsgToIfr(domain) {
		switch (domain) {
			case "A":
				var ifr = document.getElementById("ifrA");
				("txtA").value, "");
			case "B":
			    var ifr = document.getElementById("ifrB");
			    ("txtB").value, "");
			case "C":
			    var ifr = document.getElementById("ifrC");
			    ("txtC").value, "");
			    throw ("No such domain!");

And three pages: A.htm located in, B.htm located in, C.htm located in, physically they are all located under C:\inetpub\wwwrooot, while in the browser I manually type DomainA/B/ to make the cheat Smile | :) , the code in the A/B/C pages are similar, shown below:


 <input type="button" value="Cross domain call"  onclick="doClick();" />

<div id="d"></div>

     window.addEventListener("message", receiveMessage, false);
     function doClick() {
         parent.postMessage("Message sent from " +, "");
     var d = document.getElementById("d");
     function receiveMessage(evt) {
         d.innerHTML += "Received message \"<span>" + + "</span>\" from domain: " 
				+ evt.origin + "";

I recorded a GIF image below to demonstrate the Cross-Domain messaging:

HTML5 Cross-Domain Messaging Demo

See the message passed through different domains in bi-direction? Isn't it cool?


To support independent communication under different browsing context, HTML5 introduced Message Channel to post message independently, its official definition is shown below:

Communication channels in this mechanisms are implemented as two-way pipes, with a port at each end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are asynchronous, and delivered as DOM events.

I spent about half a day investigating the Message Channel and finally got it working, my code is shown below.

Container page source code

 <iframe id="ifr" src=""  

iframe page source code

<div id="info"></div>

The entire process can be described as:

  1. Container page (A) embedded an iframe whose src is pointing to a page (B) in different domain.
  2. Once the iframe loaded, the container posts a message to page B with a MessagePortArray.
  3. Page B received the message as well as the array containing a list of MessagePort objects.
  4. Page B registers onmessage event on port instance.
  5. Page B invokes port.postmessage to send a message to page A through this MessageChannel.
At this timestamp, I seems only Opera correctly supports MessageChannel, Google Chrome and IE10 Platform Preview 2 failed to deliver the ports array, Safari cannot gets the onmessage event fired. Firefox 7.0 beta event doesn't support MessageChannel object.
Note: Ports can also enable communication between HTML5 Web Workers.

One more thing (plagiarize Steve Jobs Smile | :) ), to use Message Channel one noticeable point is, web developer should explicitly close the channel once there is no need, otherwise there will be a strong reference between two pages, as W3 official page emphasizes below:

Authors are strongly encouraged to explicitly close MessagePort objects to disentangle them, so that their resources can be recollected. Creating many MessagePort objects and discarding them without closing them can lead to high memory usage.

Further Reading

Originally posted at Wayne's Geek Life


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Wayne Ye
Software Developer (Senior) SAP Labs Shanghai
China China
Wayne is a software developer, Tech Lead and also a geek. He has more than 6 years' experience in Web development(server: ASP.NET (MVC), Web Service, IIS; Client: HTML/CSS/JavaScript/jQuery/AJAX), Windows development (Winform, Windows Service, WPF/Silverlight, Win32 API and WMI) and SQL Server. Deep understanding of GOF Design Patterns, S.O.L.i.D principle, MVC, MVVM, Domain Driven Design, SOA, REST and AOP.

Wayne's Geek Life

Infinite passion on programming!

You may also be interested in...

Comments and Discussions

Questionhow to send message in offline Pin
venkatrami reddy20-Nov-15 3:11
membervenkatrami reddy20-Nov-15 3:11 
QuestionFailed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://:8585') does not match the recipient window's origin ('http://'). Pin
‫محم د‬‎22-Nov-14 3:36
member‫محم د‬‎22-Nov-14 3:36 
BugDont work Cross domain call Pin
prometeo849-Mar-14 8:42
memberprometeo849-Mar-14 8:42 
QuestionVery helpful Pin
Yuriy Loginov27-Feb-14 9:25
staffYuriy Loginov27-Feb-14 9:25 
GeneralMy vote of 5 Pin
Ahmed Ibrahim Assaf24-Dec-12 22:47
memberAhmed Ibrahim Assaf24-Dec-12 22:47 
GeneralThank you Pin
Emre Guldogan6-Sep-11 13:06
memberEmre Guldogan6-Sep-11 13:06 
GeneralMy vote of 4 Pin
ruilima6-Sep-11 5:11
memberruilima6-Sep-11 5:11 
QuestionNice! Pin
XiaoChuan Yu5-Sep-11 9:56
memberXiaoChuan Yu5-Sep-11 9:56 
AnswerRe: Nice! Pin
Wayne Ye5-Sep-11 16:55
memberWayne Ye5-Sep-11 16:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 5 Sep 2011
Article Copyright 2011 by Wayne Ye
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid