XDM Child (sender)

by Jacob Quant

HTML

<h1>Child</h1>
<input id="message-for-parent" type="text" value="" placeholder="(message for parent)">
<button id="child-to-parent-button">Send to parent</button>
<br>
<p id="child-message"></p>

CSS

h1 {
    font-size: 20px;
    }

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

JavaScript

// ( use parent fiddle: http://jsfiddle.net/quant/HfKQz/ )

// child_on_message(e) will handle the reception of postMessages (a.k.a. cross-document messaging or XDM).
function child_on_message(e) {
    console.log("child_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-child') {
            $("p#child-message").html(returned_pair[1]);
        }
        else
            console.log("Child received invalid message");
    }
}

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


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

        
});