Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

HTML JS communication between iframes and Cross-document messaging

By Anonymous (not verified) , 14 June, 2016
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

  • JavaScript

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer