HTML JS communication between iframes and Cross-document messaging

Submitted by Anonymous (not verified) on Tue, 06/14/2016 - 17:46
Question

How to communicate between iframe and the parent site ?

How to communicate between two iframes  ?

Example :

For example in the top window (Parent): (the_iframe.contentWindow.postMessage('data', 'domain');)

<html>
  <body>
    <iframe src="iframe.html" id="iframe1"></iframe>
  </body>
  <script>
    window.onload = function () {
      myIframe = document.getElementById('iframe1');
      myIframe.contentWindow.postMessage('hello', '*');
    }
  </script>
</html>

and in the iframe:

<html>
  <body>
    <div>The I frame</div>
  </body>
  <script>
    window.onmessage = function (e) {
      if (e.data == 'hello') {
        alert('It works!');
      }
    };
  </script>
</html>

On the iframe, You can also yse:
function postMessage(a, b){
}

Example 2 : Between two iframes

Get One iframe from another Iframe

var iframe2 = parent.document.getElementById('iframe2');

Parent:

<html>
  <body>
    <iframe src="iframe.html" id="iframe1"></iframe>
    <iframe src="iframe2.html" id="iframe2"></iframe>
  </body>
</html>

iFrame 1:

<html>
  <script>
    window.onmessage = function (e) {
        alert(e.data)
    };
  </script>
</html>

iFrame2:

<html>
  <script>
    parent.window.onload = function() {
      myIframe = parent.document.getElementById('iframe1');
      myIframe.contentWindow.postMessage(["name", "age", "city"], '*');
    }
  </script>
</html>

 

Note : You may have problems if you use different domains

 

Link : 

http://stackoverflow.com/questions/9153445/how-to-communicate-between-iframe-and-the-parent-site
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
http://www.dyn-web.com/tutorials/iframes/refs/
http://www.dyn-web.com/tutorials/iframes/refs/iframe-iframe.php

 

Tags

Add new comment