krakenjs / post-robot

Cross domain post-messaging on the client side using a simple listener/client pattern.
Apache License 2.0
741 stars 92 forks source link

Sending Messages from Parent to IFrames seems to not work #95

Open shabeesh opened 3 years ago

shabeesh commented 3 years ago

Hi,

I have a child page running at localhost:8080/apps/child.html, as below.

<!DOCTYPE html>
<script src="https://unpkg.com/post-robot@10.0.1/dist/post-robot.js"></script>
<div>
    <p id="content">child page</p>
</div>

<script>
 listener=postRobot.on('getUser',{domain: 'http://localhost:8080'}, function(event) {
    console.log(event)
return {
    id:   1234,
    name: 'Zippy the Pinhead',
  };
});
console.log("listener is registered here ")
console.log(listener)
</script>

I have a parent page where the child is included in an iFrame.

<!DOCTYPE html>

<script src="https://unpkg.com/post-robot@10.0.1/dist/post-robot.js"></script>
<h1> Parent Sending Page</h1>

<iframe src='./Child.html' frameborder="0" id='123'></iframe>
<button onclick=sendMessage()>iFrame Test</button>

<script>
  function sendMessage(){
    let poFrame=document.getElementsByTagName("iframe")[0]
    let poAppSpot=poFrame.contentWindow.parent

    console.log(poFrame)
    console.log(poAppSpot)
  /////
  postRobot.send(
    poAppSpot,'getUser', { id: 1337 } ,  {domain: 'http://localhost:8080'}).
    then(
        function(event) {
          console.log("*** expecting response HERE *** ")
          console.log(event)
          console.log("*** expecting response *** ")
    }).catch(function(err) {

    // Handle any errors that stopped our call from going through

    console.error(err);
});

}
</script>

The scenario is simple, when thebutton testIFrame is clicked, it triggers the sendMessage() method which post the getUser to the Iframe.

    let poFrame=document.getElementsByTagName("iframe")[0]
    let poAppSpot=poFrame.contentWindow.parent // tried with .top as well.

This results in an error No handler found for post message: getUser from http://localhost:8080 in http://localhost:8080/apps/index.html. Testing in Chrome Version 90.0.4430.212

Do let me know what I am missing as I can't find documentation with regards to sending to iframe.

ryandoll commented 2 years ago

Instead of let poAppSpot=poFrame.contentWindow.parent just try let poAppSpot=poFrame.contentWindow