Communication with web page, iframe to parent

Hi everyone,
I’m currently trying to get my playcanvas app to interract with my web app.
In the doc i can see how to send informations to playcanvas using the postMessage method, but there is nothing about the iframe using postMessage to the parent.
Did anyone already manage to get the iframe to send a message to a web app using window.parent.postMessage() ?
Thanks a lot

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