Window.postMessage part 2 – an example

In Part 1 of the series, I talked about the basics of Window.postMessage and showed some sample code.  This post will show some real code with a demo link.   This code purposefully has some security issues which will be addressed in the third and final post of the series.

The demo code found at is –
<iframe src="" style="width:100%; height:50%;"></iframe>
<script language="javascript">
function sendMessage()
var txt = document.getElementById("msg").value;
window.frames[0].postMessage(txt, "*");
return false;
<form method="#" method="post" onsubmit="return sendMessage()">
<input type="text" maxlength="128" name="msg" id="msg">
<input type="submit">

What it does is load in an iframe that is 50% of the height of the window and 100% of the width.  It then has a form where you can specify text and when you hit submit, it sends a message to the iframe with the text that is specified in the form.

The code for is –
<script language="javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
var cont = document.getElementById('container');
cont.innerHTML = cont.innerHTML + + "<br/>";
<div id="container" name="container" style="width:100%; height:100%;"></div>

It first creates registers a function(receiveMessage) to handle the “message” event and creates a div.  When a message is received it, it  appends the text to the div.

This entry was posted in Javascript, Security. Bookmark the permalink.