XDM Parent

Made for SO question #12477917

by Jacob Quant

HTML

<h1>Parent window</h1>
<input id="message-for-child" type="text" value="" placeholder="(message for child)">
<button id="parent-to-child-button">Send to child</button>
<br>
<p id="parent-message"></p>
<br>
<iframe id="child" src="http://fiddle.jshell.net/quant/G2uq6/show/"></iframe>

CSS

h1 {
    font-size: 20px;
    }

form ul {
    list-style-type: none;
    }

JavaScript

// parent_on_message(e) will handle the reception of postMessages (a.k.a. cross-document messaging or XDM).
function parent_on_message(e) {
    console.log("parent_on_message event fired: ", e);
    // You really should check origin for security reasons
    // https://developer.mozilla.org/en-US/docs/DOM/window.postMessage#Security_concerns
    if (e.origin.search(/^http[s]?:\/\/.*\.jshell\.net/) != -1
        && !($.browser.msie && $.browser.version <= 7)) {
        var returned_pair = e.data.split('=');
        if (returned_pair.length != 2)
            return;
        if (returned_pair[0] === 'message-for-parent') {
            $("p#parent-message").html(returned_pair[1]);
        }
        else
            console.log("Parent received invalid message");
    }
}

jQuery(document).ready(function($) {
    // Setup XDM listener (except for IE < 8)
    if (!($.browser.msie && $.browser.version <= 7)) {
        // Connect the parent_on_message(e) handler function to the receive postMessage event
        if (window.addEventListener)
            window.addEventListener("message", parent_on_message, false);
        else
            window.attachEvent("onmessage", parent_on_message);
    }


    $("button#parent-to-child-button").on("click", function(e) {
        console.log("Sending: " + $("input#message-for-child").attr("value"));
        $("iframe#child").get(0).contentWindow.postMessage('message-for-child=' + $("input#message-for-child").attr("value"), '*');
        
    });

        
});