Skip to content

postMessage

page1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postMessage - sender</title>
</head>
<body>

<script type="text/javascript">
    var target1;
    var target2;

    function openPopupAsTab() {
        target1 = window.open(document.getElementById('target').value, "child");
    }
    function openPopupAsIfr() {
        target2 = document.getElementById('myframe');
        target2.src = document.getElementById('target').value;
    }

    function sendAsJson() {
        if(target1 != null) {
          target1.postMessage(JSON.parse(document.getElementById('message').value), "*");
        }
        if(target2 != null) {
          target2.contentWindow.postMessage(JSON.parse(document.getElementById('message').value), "*");
        }
    }
    function sendAsString() {

        if(target1 != null) {
          target1.postMessage(document.getElementById('message').value, "*");
        }
        if(target2 != null) {
          target2.contentWindow.postMessage(document.getElementById('message').value, "*");
        }
    }
</script>

<input id="target" value="page2.html">
<button onclick="openPopupAsTab()">Open in as tab</button>
<button onclick="openPopupAsIfr()">Open in as iframe</button>
<br/>
<textarea rows="5" cols="40" id="message">{"id":1}</textarea>
<button onclick="sendAsString()">Send message as string</button>
<button onclick="sendAsJson()">Send message as json</button>
<br/>
<iframe id="myframe" name="myframe" src="" width="100%" height="900px"></iframe>
</body>
</html>

page2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postmessage - listener</title>
</head>
<body>
<h1>postmessage - listener</h1>
<script type="text/javascript">
    window.addEventListener("message", function(event) {
        console.log("Parent", parent);
        console.log("Event", event);
    }, false);
</script>

</body>
</html>