[SOLVED] Interaction between PlayCanvas and web app

Hi everyone,

I’m building a website that contains a PlayCanvas game inside an iframe.
I want to pass differnt variables from the game to other script of my website.
I saw some solutions using postMessage but i’m not sure how to use it and get access to PlayCanvas variables.

Thanks for helping!

Did you read this page in the User Manual:


We recently needed a similar solution to run PC as iframes in richmedia ad units. We used the Messaging API mentioned in the manual successfully. One thing you need to be sure to do is extract the true URL from the PC page you view when previewing your work.

Inspect the PC preview page and you’ll see they are iframing your project in another page. You want to use that iframe source as your source as well or else your project will actually be framed within a frame within a frame on your own page and the postMessage will not work correctly. I also suggest wrapping your postMessage calls in try catches until you have it working or else you wont get any feedback about DOM exceptions if you aren’t doing it correctly.

Thanks for your replies guys! Will, it seems that I’ve missed this manual.
In a brief view it looks exactly what I need. I’ll give it a try and let you know if it works.

Hey Will!

I recently had to do something like that for my Ludum Dare game. That manual link is definitely helpful. Although one thing I couldn’t figure out (and maybe should be included in the manual?) is how to destroy a running PlayCanvas instance in a page?

For my use case, I know how to initialize it (by copying the code in the __loading.js and such) but then when the game ends, and the player is taken back to the “lobby”, I just remove the canvas element, but that doesn’t seem to fully stop/restart everything.

I have tried to use this tutorial http://developer.playcanvas.com/en/user-manual/publishing/web/communicating-webpage/6 , to communicate with my PlayCanvas application but having some problem. I’ve download the PC app and hosting it in my own iframe. All files located in the same project directory and working on same localhost.

This is the global function in pc script:

window.getScore = function() {
    var app = pc.Application.getApplication();
    var entity = app.root.findByName("Playbot");

And this is how i’m trying to access it:

function onGameFinish() {
    var element = document.getElementById("game-frame");
    var iframe = element.contentWindow;

    var score = iframe.window.getScore();

For some reason, score value that I get is undefined.
Does anyone know what’s wrong?

You might have already figured this out, but it looks like your window.getScore function doesn’t actually return anything. So that might be why?

Yeah Omar, thanks I forgot to update about it.

1 Like