[SOLVED] What is the correct way to use postMessage?

I have readed some of this and i made a little code but not work still. :thinking::thinking:

This is the code in the site window parent that am using

<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
</head>

<body>

  <form id="form">
    <input type="text" placeholder="Enter message" name="message">
    <input type="submit" value="Click to send">
  </form>

  <iframe src="https://playcanv.as/p/eG4R85w7/" id="iframe"></iframe>

  <script>
    form.onsubmit = function() {
      iframe.contentWindow.postMessage(this.message.value, '*');
      return false;
    };
  </script>

</body>
</html>

And this is the code attached to an entity in Playcanvas

var Listen = pc.createScript('listen');

// initialize code called once per entity

Listen.prototype.update = function ListenMessages()
{
  
    window.onmessage = function(e)
    {
        alert("message recieved in  Playcanvas: " + e.data.content + " from origin: " + e.origin);
    };
    console.log("OK");
};

Hi @Luis_Mb,

On your parent page code, are you defining somewhere the iframe variable?

Otherwise that call would fail, try adding an id and using it to target the iframe in your JS:

  <iframe src="https://playcanv.as/p/eG4R85w7/" id="iframe"></iframe>

  <script>
    form.onsubmit = function() {
      document.getElementById('iframe').contentWindow.postMessage(this.message.value, '*');
      return false;
    };
  </script>

Edit: I see you already had an id defined at the end of the iframe element, the issue most likely it’s elsewhere.

Stepping through with the debugger can you check if indeed the onsubmit handler fires? You onmessage listener in the PlayCanvas side seems to be correct.

Hi @Leonidas. Thanks for answering, I have solved it by adding an extra “e” to the url of playcanvas:

playcanv.as/e/p/eG4R85w7

Finally, all works fine.

1 Like

I was trying to add a basic rotation script, I hoped it would be enough to remove alert () and write that there. Am I writing in the right place?

//Code within Playcanvas
// Listen.js
window.onmessage = function(dt)
    {
        this.entity.rotate(0*dt,  30*dt, 0*dt);
    };

I was easier to use

this.entity.rotateLocal (0, 30, 0); 

I don’t know why the above script caused problems since it was written the same way. Now it’s solved

In the above script, were you pass in dt as a parameter and were you calling it every frame?