Communication with web page, iframe to parent

Super late here, but I managed to get a message send from the iframe holding the files of playcanvas to the parent site. (window.top)

This is the script inside PlayCanvas, I made it so everytime I press X the message is sent (for test purposes):

//This script sends the message to the parent site. This is located inside Playcanvas.

var MessageSender = pc.createScript('messageSender');

MessageSender.prototype.sendMessage = function(mes)
{
    window.top.postMessage({content: mes}, '*');
};

MessageSender.prototype.update = function (dt){
    if (this.app.keyboard.wasPressed(pc.KEY_X))
    {
      console.log("send event fired.");  
      this.sendMessage('hello, world!');
    }
};

And this is inside my index.js of the parent page:

function ListenMessages()
{
    //This script stays inside the .js located in the parent website.
    window.onmessage = function(e)
    {
        alert("message recieved in parent window: " + e.data.content + " from origin: " + e.origin);
    }
    console.log("listener for parent window has been registered.");
}

Apologies for the bump, but I tought it would be better to share this solution.

source: https://stackoverflow.com/questions/9153445/how-to-communicate-between-iframe-and-the-parent-site

4 Likes