Iframes get a bad wrap for everything from security problems, to usability and SEO issues. Despite this, they are one of the tools at our disposal, and knowing how to use them effectively could open the door to new solutions to old problems. Being able to send data between the iframe and the parent page is a useful trick for delivering more integrated solutions, rather than the traditional boring “page-in-a-page” way iframes get used.

Image for post

Photo by Sai Kiran Anagani on Unsplash

The method examined here isn’t just for iframes though, it will work in any case where you have access to another page’s window object (so popups and embedded web-browsers can join in on the fun too). Iframes are easy to play with, though, so we will use them for this example.

Establishing 2-way communication between a child page and its parent can be done a few ways. Still, generally, the recommended approach is to use window.postMessage, if the technologies you are using support it (sorry IE users).

So let’s create a basic page to act as our parent.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Parent Page</title>
  </head>
  <body>
    <h2>Container</h2>
    <textarea id="output" cols="30" rows="10" disabled>awaiting data...</textarea>
    <div>
      <input type="text" id="field" value="type something fun here" />
      <button id="send">Send</button>
    </div>
    <div>
      <iframe
        height="500px"
        id="inner"
        src=""
        frameborder="0"
      ></iframe>
    </div>
  </body>
</html>

Here we have a very basic page. I will use a disabled textarea for showing data from incoming messages from the embedded page, and an input and button for sending messages to said page. Aside from that, we have the guest of honour, the iframe itself, currently with no source for it, because we need to make a page to embed first. Let’s do that.

#learn-to-code #programming #html #web-development #javascript

How to easily send and receive data with an iframe
1.50 GEEK