HTML5 Cross Document Messaging Tutorial

Source

(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">
	<head>
	   <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" />

	<title></title>
	<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>
	</head>

	<body>
	</body>
</html>

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.

CSS

#chat{
	padding-left: 1.5em;
}

#ifmsg{
	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.

Javascript

function msgThis(){
	var ifObj = document.getElementById("ifmsg").contentWindow;
	var msgInput = document.getElementById("msg").value;
	var o = document.getElementsByTagName("ifmsgel");
	o.postMessage(msgInput, "http://127.0.0.1:8020/");
}

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>
        </div>

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 == "http://127.0.0.1:8020/") { 
          var msgOutput=document.getElementById("msgRec");
          msgOutput.textContent+= evt.origin + ": " + evt.data + "\n"; 
      } else {
          // If the message is coming from an untrusted origin, just ignore it :)
      }
}
</script>

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);">
		
		<div>
			<header>
				<h1>ifdoc</h1>
			</header>
			<p>output message</p>
			<div id="msgRec">

			</div>

			<footer>
				<p>
					&copy; Copyright  by Kevin Languedoc
				</p>
			</footer>
		</div>
	</body>

Conclusion

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

More by this Author


Comments 2 comments

user 2 years ago

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


klanguedoc profile image

klanguedoc 2 years ago from Canada Author

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

Submitting comments has been temporarily disabled.

Click to Rate This Article
working