ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

HTML5 Cross Document Messaging Tutorial

Updated on June 18, 2013
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.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      4 years ago from Canada

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

    • profile image

      user 

      4 years ago

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

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)