Konubinix' opinionated web of thoughts

PostMessage() and Iframes

Fleeting

iframe

two way communication and send something back from our outer window to the iFrame?

https://www.ilearnjavascript.com/plainjs-postmessage-and-iframes/

The content of the iframe:

<!DOCTYPE html>
<html lang="de">

  <head>
    <meta charset="utf-8">
    <title>iframe</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
    <h1>iframe</h1>
    <button>Trigger postMessage</button>

    <div id="innerContainer"></div>
  </body>

  <script>
    document.querySelector("button").addEventListener("click", function() {
        top.postMessage("message from iframe", 'https://konubinix.eu');
    });

    window.addEventListener("message", receiveMessage, false);

    function receiveMessage(event) {

        if(event.origin === "https://konubinix.eu"
           && event.data === "message from window"
           && event.data.length === 19
           && typeof event.data === 'string') {
            console.log("event.origin: ", event.origin);
            console.log("event.data: ", event.data);
            console.log("event.source: ", event.source);

            document.getElementById("innerContainer").innerText = `
    Message from window:
    event.origin: ${event.origin}
    event.data: ${event.data}
    event.source: ${event.source}
    pathname: ${event.source.location.pathname}
    // open also console to inspect objects
    `
        }
    }
  </script>

</html>

The content of the main page

<!DOCTYPE html>
<html lang="de">

  <head>
    <meta charset="utf-8">
    <title>window</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
    <h1>window</h1>

    <div id="outerContainer"></div>

    <iframe width="500" height="250" src="URLIFRAME"></iframe>

    <script>
      // function that gets triggered when message event is triggered
      function receiveMessage(event) {
          if( event.origin === "https://konubinix.eu"
              && event.data === "message from iframe"
              && event.data.length === 19
              && typeof event.data === 'string') {

              console.log("event.origin: ", event.origin);
              console.log("event.data: ", event.data);
              console.log("event.source: ", event.source);

              document.getElementById("outerContainer").innerText = `
      Message from iFrame:
      event.origin: ${event.origin}
      event.data: ${event.data}
      event.source: ${event.source}
      // open also console to inspect objects
      `

              // I delayed the response only for the effect
              setTimeout(function() {
                  event.source.postMessage("message from window", event.origin);
              }, 1000);
          }
      }

      // event listener for message event
      window.addEventListener("message", receiveMessage, false);
    </script>
  </body>

</html>

The result:

window