Example: postMessage with Hidden Iframe

This example shows how to send form data to a hidden iframe on another domain using postMessage. The document on the other domain does some validation of the form entries and sends back a message indicating whether the entries have been accepted or need modification.

Demo: postMessage

[Result will display here - demo disabled]

Note: We show the components of a working example, but don't provide a live demonstration due to the overhead of maintaining a second domain for this purpose.

JavaScript in Main Document

You need to be sure that the document in the iframe has finished loading before you try to send a message to it. Since the iframe onload event triggers before the containing document onload, you could set up these event handlers when the main document triggers onload or DOM ready.

We set up event handling for the example as shown below, including support for Internet Explorer 8:

// assign event handlers for onload and onmessage events
if ( window.addEventListener ) {
    window.addEventListener('load', handleForm, false);
    window.addEventListener('message', handleMessage, false);
} else if ( window.attachEvent ) { // ie8
    window.attachEvent('onload', handleForm);
    window.attachEvent('onmessage', handleMessage);

A handleForm function is assigned to the load event, and a handleMessage function is assigned to the message event, which is triggered when a message is received via postMessage.

In handleForm, a function is assigned to the form button's onclick property:

function handleForm() {
    // assign onclick handler to submit button
    document.getElementById('submitBtn').onclick = function(e) {
        // assign values in form fields to variables
        var user = this.form.elements['user'].value;
        var email = this.form.elements['email'].value;

        // convert object literal containing form entries to a string
        var msg = JSON.stringify( {'user': user, 'email': email} );

        // get reference to window in iframe 
        var win = document.getElementById('ifrm').contentWindow;
        // send msg to win
        win.postMessage( msg, 'http://www.example.com' );

First, we assign the values in the form fields to variables. Next we create a msg variable which consists of an object containing the form entries. We use JSON.stringify[1] to convert this object to a string since IE 8 and other older browsers do not support objects passed in postMessage. We get a reference to the window in the iframe and pass msg to this window.

Our handleMessage function first checks the origin of any messages received and displays the message (e.data) if it is from the expected origin:

// event handler for postMessage
function handleMessage(e) {
    // Get reference to display div
    var el = document.getElementById('display');
    // Check origin
    if ( e.origin === 'http://www.example.com' ) {
        el.innerHTML = e.data;  // Display message data

JavaScript in Iframe

The document in the iframe includes a function to handle the message sent when the button is clicked to submit the form:

// event handler for postMessage
function handleMessage(e) {
    // check origin of message
    if ( e.origin === 'http://www.your-domain.com' ) {
        var data = JSON.parse(e.data); // parse stringified data
        var msg = ''; // holds info on validity of entries
        // regexps to check data
        var re = /[a-zA-Z]{3,40}/; // 3 to 40 alpha chars
        // check entry for characters other than these
        var re2 = /[^-a-zA-Z0-9_]/;
        // email
        var re3 = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i;
        // validate entries
        if ( !re.test(data.user) ) {
            msg = 'Your user name is too short. '
        if ( re2.test(data.user) ) {
            msg += 'Username can only include alphanumeric characters, underscores, and hyphens. ';
        if ( !re3.test(data.email) ) {
            msg += 'Your email address is not valid.'
        if ( !msg ) { // msg still empty string?
            msg = 'Your entries have been processed.';
        // send reply using e.source and e.origin properties
        e.source.postMessage(msg, e.origin);

// assign handler for message events
if ( window.addEventListener ) {
    window.addEventListener('message', handleMessage, false);
} else if ( window.attachEvent ) { // ie8
    window.attachEvent('onmessage', handleMessage);

JSON.parse is applied to the message data which was stringified prior to being sent. Regular expressions are defined and used to validate the data. A msg variable holds the message that will be sent back to the source based on the results of validation.

More postMessage Examples

Additional postMessage examples show how to:

  • Set the height of an iframe to display all of its content when its document is on another domain.
  • Obtain information from and interact with objects and properties in documents on another domain.

Back to top

  1. Find information on JSON.stringify and JSON.parse in our tutorial on JavaScript Object Notation. ^