1

I am trying to send a message between two files that are in the same folder in localhost, main.php and iframe.php, but the iframe does not listen to it, I have tried to use many target origin like this:

mainpage.php


<body>
    <iframe src="iframe.php" class="iframe"></iframe>
</body>
<script>

    const iframe = document.querySelector('.iframe');
    
    iframe.contentWindow.postMessage("message sent from localhost/mainpage.php","http://localhost/iframe.php");

</script>

and inside the iframe.php to listen to the message i use

window.onmessage = function(event) {

    alert(event.data);
}
woodfile
  • 13
  • 4
  • Does this answer your question? [Invoking JavaScript code in an iframe from the parent page](https://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page) – disinfor Apr 09 '23 at 21:53
  • disinfor Hi, you don't answer my question. I want to know if the origin target is misspelled or not. How should I write the origin target, so that the message reaches the iframe? – woodfile Apr 09 '23 at 22:06
  • I don't need to send a function to the iframe, I want to send a message – woodfile Apr 09 '23 at 22:11
  • It should definitely be `"[scheme]://[host]:[port]"` so I assume in your case `"http://localhost"` or `"http://localhost:12345"` – Pieterjan Apr 09 '23 at 22:16
  • Pieterjan hello, I tried both alternatives without success (http://localhost:80 that is my server port) – woodfile Apr 09 '23 at 22:55
  • It’s possible you’re attempting to send the message before the iframe has loaded, before the `onmessage` handler is registered. – ray Apr 09 '23 at 23:20
  • ray Hello, I tried to use the – woodfile Apr 09 '23 at 23:44
  • Just to see if this is the problem wrap your postMessage call in a setTimeout to delay it for a few seconds. – ray Apr 10 '23 at 00:43
  • ray Thanks you have answered my question, to use setTimeout in postMessage and it worked, put this comment as an answer to validate it and that others can see it – woodfile Apr 10 '23 at 01:57
  • @woodfile Posted an answer with one of many possible ways to avoid this problem. – ray Apr 10 '23 at 17:16

1 Answers1

1

As discussed in the comments, you're invoking postMessage before your iframe content has loaded. There are numerous ways to solve this, one of which is to listen for a "load" event on the iframe before attempting it.

Would look something like this:

const iframe = document.querySelector('iframe');

iframe.addEventListener('load', () => {
  console.log('iframe loaded')
  
  // iframe has loaded; can post messages now.
  iframe.contentWindow.postMessage("message sent from localhost/mainpage.php","http://localhost/iframe.php");
});
<iframe src="//example.com"></iframe>
ray
  • 26,557
  • 5
  • 28
  • 27