ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

HTML5 Cross Document Messaging Tutorial

Updated on June 18, 2013

(c) 2013 kevin languedoc (klanguedoc)

A HTML5 feature that doesn’t get a lot of media attention is the Cross Document Messaging API and its Channel Messaging API. This HTML5 feature allows two pages to communicate with each other across domains and sources. In other words Cross Document Messaging is a web messaging API that provides a “chat” API for web pages.

Cross-Document Messaging allows users from different locations to chat with each other like many of the popular web application like Google GMail, Google Chat, Facebook to name but a few apps that offer in app messaging. Others types of techniques for cross document messaging can include the infamous XmlHttpRequest and dynamic scripting insertion. However Cross Document Messaging is much more safer by keeping the DOM hidden. Most latest versions of the most popular browsers support HTML5 messaging, including partial support in IE9 and IE10 for iframes but not new windows.

This tutorial will explore the API and provide examples on how to use it in a web application that we let two browser windows to send and receive text from one to the next.

Overview of the API

HTML5 messaging has two types of implementations: cross document messaging and channel messaging. When you use cross document messaging, you are using the postMessage method to send messages. You don’t receive messages, but wait for the other window or iframe to send a message in turn. With channel messaging you are using the channelMessage to channel a message. Channel messages uses asynchronous mechanisms to create two-way pipes between two windows. This way the Channel Message will use the browsing context and ports to send and receive messages asynchronously.

Typically for both types of messaging mechanisms you would implement an event handler so that each window can detect incoming messages.

Setting Up the Cross Document Project

This first example will use a main page and an embedded page using an iframe. The information will be sent from the parent document to its sibling. You can use an HTML editor as long as it supports HTML5. There are a number of open source ones like Blue Griffon, Aptana, coffeecup, amaya and web matrix just to name a few. However doing a quick search with Google will provide a surprisingly good selection.

Create an HTML page and open the source editor. Make sure that doctype is in HTML5 as in the following code:

<!DOCTYPE html>
<html lang="en">
	   <meta charset="utf-8" />

	<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the .htaccess -->
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

	<meta name="description" content="" />
	<meta name="author" content="Kevin Languedoc" />

	<meta name="viewport" content="width=device-width; initial-scale=1.0" />

	<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
	<link rel="shortcut icon" href="/favicon.ico" />
	<link rel="stylesheet" href="stylesheet.css">	
	<script type="text/javascript" src="javscriptFile.js"></script>


In the head element add or change the title element inner html value to Cross Document Example. This will appear on the tab of most browsers. Next add a stylesheet using the link element as in the code snippet above. Open the css file and add the following code from the CSS section below.

The textarea resize vertical style will add a handle to the lower right corner to allow users to resize the textarea field as needed. The padding-left will add a margin of 1.5em to the left. For this simple example, no other styling is needed but you are free to add any styling to your own app.


	padding-left: 1.5em;

	padding-left: 1.5em;

textarea {
    resize: vertical;

Also add a javascript file using the script element. The script element requires the type attribute which must be set to text/javascript. Also set the src attribute to the path of the javascript file unless you plan on adding inline javascript within the body of the script element. For this simple example, I will create a function called msgThis as in the code snippet below. First I will create a window object from the iframe element using the getElementById and the contentWindow. Then assign the value of the msg textarea element to the msgInput variable. Then get a handle on the iframe using the getElementsByTagName, passing in the name from the iframe element. Finally call the postMessage method and pass the msgInput and the originating domain.


function msgThis(){
	var ifObj = document.getElementById("ifmsg").contentWindow;
	var msgInput = document.getElementById("msg").value;
	var o = document.getElementsByTagName("ifmsgel");
	o.postMessage(msgInput, "");

In the body element add a div element with the id attribute set to chat. The styling will done in the css file. In the div add a textarea element as in the following code segment. The textarea id attribute value will be msg. Also add a button to send a message to the HTML page or document that will be added to the iframe. The name the button Send a Message with the id attribute set to sendMsg. Finally for the iframe element, set the id to ifmsg and the src attribute to ifdoc.html. I also set the name value of the iframe to ifmsgel.

Parent Body Code Snippet

 <!--Code for Cross Docuemnt EXample goes here-->
        <div id="chat">
        	   <!-- Add your site or application content here -->
        <p>Cross Document Messaging Sample App</p>
        <p>Enter some text in the following field and click on the "Chat" button to send it to the other window</p><br/>
        <textarea placeholder"Enter a message" id="msg"></textarea><br/>
        <button id="sendMsg" onclick="msgThis()">Send</button>
        <p>This is an iframe</p><br/>
        <iframe id="ifmsg" name="ifmsgel" src="ifdoc.html"></iframe>

iframe document

For the iframe document, create another HTML5 file, naming it ifdoc.html. In the head section add a script element setting the type to text/javascript. However I will add the code directly to inner html (between the opening and closing elements). Add a function called processMsg with an event handler. First check to see if the origin is from the originating domain. Then get a handle on the msgRec div element and then assign the incoming message data to the div element.

<script type="text/javascript">						
function processMsg(evt){		
      if (evt.origin == "") { 
          var msgOutput=document.getElementById("msgRec");
          msgOutput.textContent+= evt.origin + ": " + + "\n"; 
      } else {
          // If the message is coming from an untrusted origin, just ignore it :)

Add a div element to the body. Name this element msgRec. To add the event handler to memory, add the window.addEventListerner, see code below, to the onload event of the body element.

<body onload="window.addEventListener("message", processMsg);">
			<p>output message</p>
			<div id="msgRec">


					&copy; Copyright  by Kevin Languedoc


Cross document is a handy tool, especially for gamers but also for live chatting for customer support which is becoming more and more widespread.


    0 of 8192 characters used
    Post Comment

    • klanguedoc profile image

      Kevin Languedoc 3 years ago from Canada

      Sorry I don't have the complete code for this tutorial anymore

    • profile image

      user 3 years ago

      Is there a complete file download such as to avoid the copy/paste ?