Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Communication Between Iframes

09 Dec 2021 »

index0.html

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <iframe id="iframe" src="index1.html"></iframe>
  <button type="button" id="button">send message</button>

  <script>
    const button = document.getElementById('button')
    const iframe = document.getElementById('iframe')

    button.addEventListener('click', () => {
      iframe.contentWindow.postMessage('hello', '*')
    })

    window.onmessage = function(e) {
      console.log('index0', e)
    }
  </script>
</body>
</html>

index1.html

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="button">bar</button>
  
  <script>
    const button = document.getElementById('button')
    button.addEventListener('click', () => {
      window.top.postMessage('hello from iframe', '*')
    })

    window.onmessage = function (e) {
      console.log('inside iframe', e)
    }
  </script>
</body>
</html>