Communicating react code with playcanvas

Hi yall, so I need a bit of help regarding the postmessage api which lets your playcanvas code communicate with react. I don’t really understand how i would go about doing this so a little demo would be really helpful. I have merged my playcanvas build with react using iframe, I just now need communication between them so any help is appreciated Thanks.

Hey, the following thread may help in implementing the post-message api communication.

Thanks for sharing it, the controls of the game I have iframed do not seem to be working like this I don’t see how I can implement input controls with this. Like for instance keyboard press movement or something like that.

Hi @Umer_Younas,

For keyboard press controls why not catch them directly from the PlayCanavs side, from inside the iframe?

https://developer.playcanvas.com/en/tutorials/keyboard-input/

hmm that is what I am doing on the playcanvas side, controls are working fine in the editor but not in the iframe. Is this not supposed to happen???

Actually no, the iframe should receive events normally. Maybe you have some special CSS applied to it that prevents events from firing?

You can check how PlayCanvas hosted builds have their iframe styled. They do something similar to your setup, a container window and the build is running on an iframe.

Build your project and open the url, from there you can inspect the iframe with the browser dev tools.

Yeah you were right, I had z-index of iframe applied at -1 which was the problem which brings me to another question as long as I don’t click on the screen the controls don’t work this is not a behavior I want. Can anyone confirm that is this a valid outcome??

Hmm, not sure about it. I’ve tried the following demo build from the terrain tutorial and as soon as it loads the iframe receives keyboard input.

If I click on the grey footer (parent window) the iframe loses focus and doesn’t accept any keyboard input (expected). If I click back on it, it works again.

@yaustar any idea what triggers this behavior (iframe focused by default)?

Yeah I really want to know if the iframe is in focus by default or not

You can always attempt to focus any HTML element using JS (React most likely can do something similar):

document.getElementById('iframeId').contentWindow.focus();

We have a bit of code on the parent page that focuses the iframe on load:

1 Like