postMessage in HTML5 to send messages between windows and iframes

Ever had the need to communicate between windows or the current window and an inner iframe? Across domains as well? I bet you have, but now we have a nice option for doing that!

The solution is called postMessage and is part of the HTML5 Web Messaging specification. What makes it cool, and very easy to use, is that all you need to trigger it is to call a method and add an event handler:

  1. Call the postMessage method of the window/iframe element you want to send the information to.
  2. Specify origin. Should be a domain or a wildcard "*"
  3. In the receiving window, just add an event listener for the message event.
  4. Optional: add an origin check for security reasons.

The code to do this

In this example we will have one containing page with a form, posting a message to an iframe in that page.

Code used in the containing page

<form id="the-form" action="/">
	<input type="text" id="my-message" value="Your message">
	<input type="submit" value="postMessage">
</form>

<iframe id="da-iframe" src="postMessageTarget.html"></iframe>
	window.onload = function () {
		var iframeWin = document.getElementById("da-iframe").contentWindow,
			form = document.getElementById("the-form"),
			myMessage = document.getElementById("my-message");

		myMessage.select();	

		form.onsubmit = function () {
			iframeWin.postMessage(myMessage.value, "https://robertnyman.com");
			return false;
		};
	};

Code used in the iframe

	<p id="received-message">I've heard nothing yet</p>
	function displayMessage (evt) {
		var message;
		if (evt.origin !== "https://robertnyman.com") {
			message = "You are not worthy";
		}
		else {
			message = "I got " + evt.data + " from " + evt.origin;
		}	
		document.getElementById("received-message").innerHTML = message;
	}

	if (window.addEventListener) {
		// For standards-compliant web browsers
		window.addEventListener("message", displayMessage, false);
	}
	else {
		window.attachEvent("onmessage", displayMessage);
	}

Web browser support

The nice thing is that this is supported in:

  • Internet Explorer 8.0+
  • Firefox 3.0+
  • Safari 4.0+
  • Google Chrome 1.0+
  • Opera 9.5+

Demo and my HTML5 playground

You can see the above code in action at my postMessage demo, which is part of a new testing ground on my web site, HTML5 – Information and samples for HTML5 and related APIs which displays various HTML5 examples, the code to run them and web browser compatibility..

Play around and enjoy! 🙂

9 Comments

Leave a Reply to Marc Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.