Menu Bar

Friday, May 27, 2016

Passing messages from "iframe" to Parent frame in JavaScript

PARENT - JavaScript (Parent.html)
    window.addEventListener('message', function (event) {
        console.log("Hello from -> " + event.data);

        // Ignores messages from untrusted domains.
        //if (event.origin != 'URL of Iframe') return;

    });

IFRAME - JavaScript (child.html)
        function keep_alive() {
            http_request = new XMLHttpRequest();
            http_request.open('GET', "Child.html");
            http_request.send(null);
            parent.postMessage("Refreshing Page in child frame", "*");
        };

        function keep_push() {
            parent.postMessage("Timeout Message", "*");
        };

        setInterval(keep_alive, 1000);
        setTimeout(keep_push, 5000)

        parent.postMessage("child frame (Initial Page Load)", "*");
Soruce Code: https://github.com/vijayanandrp/programs/tree/master/javascript/message-from-iframe-to-parent-window---POC

No comments:

Post a Comment