Post message not working Properly

Hi, hope you doing well. I’m trying to add the post message and communicate it with an iframe but I’m getting the issue. Even I created a build project but not work. Need your help Thanks

Sender:

document.getElementById('mainIframe').contentWindow.postMessage("hello world", '*');

Receiver:


window.addEventListener("message", function(event) {
    console.log(event);
});

Hi @Zillo,

How are you adding your build project in your parent page? Note that the build url you are getting is already inside an iframe, so you need to remove that first. Check this manual page:

https://developer.playcanvas.com/en/user-manual/publishing/web/communicating-webpage/#embedded-in-iframe

so we have to put the link on both sides for communication like this one “https://playcanv.as”?

Not sure what you mean, but my point was that instead of using the build url you got from PlayCanvas, e.g.

https://playcanva.as/b/4543665

You need to add /e to get a the raw window with no iframe, so you can add it in your parent page:

https://playcanva.as/e/b/4543665

so this link i have to put it in there right if you have to communicate from parent to iframe


var message = "hello world";
var targetOrigin = "https://playcanv.as/e/p/4mwh7nFe/"; 
mainIframe.contentWindow.postMessage(message, targetOrigin);
type or paste code here

and from the reciever side in iframe it should be like this right ?

window.addEventListener("message", function (event) {
    if (event.origin === "https://playcanv.as/e/p/4mwh7nFe/") { // always check message came from your website
        //var score = event.data.score;
        console.log(
            '---------------\n' + 
            '[PLAYCANVAS] Received an event' + '\n' + 
            'From: ' + event.origin + '\n' + 
            'Data: ' + event.data + '\n' + 
            '---------------'
        );
        // call API method one:
      //  window.setScore(score);

        // call API method two:
      //  var app = pc.Application.getApplication();
      //  app.fire("score:set", score);
    }
}, false);

Hey, you need to use the build link (/b/) not the project link (/p/). Try clicking on your build in the builds link, a new window will open and copy that. That link will work with the /e/ param.

1 Like

working thanks

1 Like