Sunday, April 3, 2016

HTML5 window.postMessage - communication between windows/frames hosted on different domains

window.postMessage allows safe communication between windows/frames hosted on different domains.

Concept is simple: Post a message from one window (origin) or another window (target) and check for any message received  in the target window.

An example:

<!doctype html>
<html>
<head>

<script>
window.onload=function(){

    var iframeNode = document.getElementById("iframe");
    var iframe = iframeNode.contentWindow;
    iframe.document.body.innerHTML = document.getElementById('hiddenTemplate').textContent;

    var parentButtonNode = document.getElementById("postMsgBtn");
    var childButtonNode = iframe.document.getElementById("postMsgBtn");
    
    //  Post a message from main window to the iframe
    parentButtonNode.addEventListener('click',function(){
        iframe.postMessage(document.getElementById("mailbox").value, "http://localhost");       
    });

    //  Post a message from iframe to the main window
    childButtonNode.addEventListener('click',function(){
        iframe.parent.postMessage(iframe.document.getElementById("mailbox").value, "http://localhost");       
    });

    //  Check in main window if you received a message from iframe
    window.addEventListener('message', function(event) {
        if (event.origin !== "http://localhost"){
            return;
        }
        document.getElementById("msg").innerHTML = "Received this from iframe<span style='color:red;'>: " + event.data + "</span>";
    });

    //  Check in iframe if you received a message from main window
    iframe.addEventListener('message', function(event) {
        if (event.origin !== "http://localhost"){
            return;
        }
        var msgNode = iframe.document.getElementById("msg");
        msgNode.innerHTML = "Received this from main window<span style='color:red;'>: " + event.data + "</span>";
    });
}
</script>
</head>
<body>

<!-- hidden HTML template that will be used inside iframe -->
<script id="hiddenTemplate" type="text/template">
    Type something: <input type="text" id="mailbox" />
    <button id="postMsgBtn">Send this message to main window</button>
    <div id="msg"></div>
</script>

<!-- iframe and it's content -->
<iframe id="iframe" src="about:blank" width="600px"></iframe>

<!-- Main page content -->
Type something: <input type="text" id="mailbox" />
<button id="postMsgBtn">Send this message to iframe</button>
<div id="msg"></div>

</body>
</html>

No comments:

Post a Comment