0

I am trying to get the HTML postMessage function working?

I have a found a few sites giving the example but for some reason a struggling.

The code for the 2 pages is shown below, any help would be apprecaited.

Thanks and Regards, Ryan

test.php

<iframe src="postmessage-target.html" id="iframe"></iframe>
 <form id="form">
   <input type="text" id="msg" value="Message to send"/>
   <input type="submit"/>
 </form>
 <script>
 window.onload = function(){
         var win = document.getElementById("iframe").contentWindow;
         document.getElementById("form").onsubmit = function(e){
                 win.postMessage( document.getElementById("msg").value );
                 e.preventDefault();
         };
 };
 </script>

postmessage-target.html

<div id="test">Send me a message!</div>
 <script>
 document.addEventListener("message", function(e){
         document.getElementById("test").textContent =
                 e.domain + " said: " + e.data;
 }, false);
 </script>

Thanks again in advance.

Ryan

UPDATE

Is this correct as per user advice?

test.html

<iframe src="postmessage-target.html" id="iframe"></iframe>
 <form id="form">
   <input type="text" id="msg" value="Message to send"/>
   <input type="submit"/>
 </form>
 <script>
 window.onload = function(){
         var win = document.getElementById("iframe").contentWindow;
         document.getElementById("form").onsubmit = function(e){
                 win.postMessage( document.getElementById("msg").value, "*"); 
                 e.preventDefault();
         };
 };
 </script>

postmessage-target.html

<div id="test">Send me a message!</div>
 <script>
 document.addEventListener("message", function(e){
 document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
 }, false);
 </script>
Smudger
  • 9,353
  • 27
  • 97
  • 178

2 Answers2

2

The norm specifies that you should provide the targetOrigin to the postMessage function :

 win.postMessage( document.getElementById("msg").value, "*");

I don't think there is a e.domain. Try e.origin in the listener :

 document.getElementById("test").innerHTML = e.origin + " said: " + e.data;

(I also replaced the non standard textContent by innerHTML)

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
0

To get this to work, I ended up having to change document.addEventListener to window.addEventListener- I think you're adding the receiving code to the transmitting document instead of the iframe when you do it that way.