Last Updated: February 25, 2016
·
1.566K
· benjycook

Easy Helper functions for PostMessage

Makes managing messaging to frames alot easier.
WebWorkers too.
Uses JSON.stringify and parse to allow you to send objects, simple string commands, or both.

/**************************
    Message Passing to frame
*************************/

function postMsgToFrame(cmd, msg) {
    var frame = document.getElementById("myIframe");
    if (!msg || msg == null || msg == undefined) {
        msg = null;
    }
    var packet = { "cmd": cmd, "msg": msg }
    console.log("sending to client", JSON.stringify(packet));
    frame.contentWindow.postMessage(JSON.stringify(packet), "*");
}


/**************************
    Message recieving from frame
**************************/

function recieveMessage(e) {
    var packet = JSON.parse(e.data);
    console.log("new cmd packet", packet);
    if (packet.cmd == something) {
        doSomething();
    } else if (packet.cmd == something_else) {
        doSomethingElse();
    } else {
        console.warn('bad packet', packet);
    }
};

window.addEventListener("onmessage", recieveMessage, false);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside