Last Updated: February 25, 2016
·
1.222K
· 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);