I’m experimenting with javascript’s postMessage command with PlayCanvas. (see code below).
All I am doing in the code below is loading a PlayCanvas app into an iframe and using a button on the host page to send a message to the PlayCanvas app. When the app recieves the message it hides/shows the 3D object.
This works fine when I download the PlayCanvas app code and web host it in IIS. The problem comes when I try to send a message to a app hosted on PlayCanvas. (It’s unclear if we want to host the application ourselves or have PlayCanvas host it)
Is PlayCanvas hosting blocking postMessage somehow or might it be because PlayCanvas already hosts the actual application in an iframe?
Javascript Code on the page that contains an iframe with the PlayCanvas application:
function btnClick(){
var iframe = document.getElementById('pc');
iframe.contentWindow.postMessage('message_text', '*');
}
PlayCanvas Script:
pc.script.create(‘ui’, function (app) {
// Creates a new Ui instance
var Ui = function (entity) {
this.entity = entity;
};
Ui.prototype = {
// Called once after all resources are loaded and before the first update
initialize: function () {
var capsule = app.root.findByName("Capsule");
//querystring test
this.qs_val = window.location.toString().split('=')[1]; //querystring
if(this.qs_val){
console.log(this.qs_val);
}
//respond to messages test
this.messaging_test = function(e) {
console.log(e.data);
capsule.enabled = !capsule.enabled;
};
//listen for message test
window.addEventListener('message', this.messaging_test, false);
},
// Called every frame, dt is time in seconds since last update
update: function (dt) {
}
};
return Ui;
function listener(e){
//I removed the origin check but will add it later
console.log("--> MESSAGE");
var msg = JSON.parse(e.data);
console.log(msg.animation);
console.log(msg.entity);
}
console.log("START");
window.addEventListener('message',listener,false);
Problem is that nothing happens. No error. No message. No console.log() from the listener function.
right after the addEventListener() call the function is nicely called.
Can it be that on the hosting page I’m calling .postMessage() on the wrong element of the iframe?
EDIT:
Ok it works if I use the URL of the inner frame as stated by the original poster. I’m using
http://playcanv.as/index/SsH8Gsv0
is it correct? is this URL going to change throughout the lifespan of my project?