Member-only story
How to Automatically Resize an iframe
Use HTML and JavaScript to create dynamic iframes, acting as if they’re part of the parent window

The <iframe>
allows web developers to embed one HTML page inside another. It’s so useful because they’re a part of HTML so you can use them almost anywhere — in website builders like Wix and Squarespace or in your next full-stack project.
YouTube uses iframes to allow embedded videos, Google uses them for their OAuth2 authentication, and by SaaS companies such as Mailchimp, Typeform and Outgrow to offer embeddable content.
However, iframes can also cause their fair share of problems and we’ll discuss some of the most common ones in this article.
The Problem
By default, iframes have a fixed height. That’s fine if your content also has a fixed height but if your content’s height changes you could easily end up looking at a double-scrollbar monstrosity like this:

What if we wanted our iframe to behave like regular HTML elements, with content that wraps vertically?
To do this, we’d need to dynamically change the iframe’s height but security considerations mean it is impossible for a parent window to access elements within the iframe.
In this article, I’ll explain a foolproof way of achieving this effect, using vanilla JavaScript.
The Solution
Using the window.postMessage()
method, we can safely communicate between the iframe and the parent window. That way, we can send a height value from the iframe to the parent window. Then, in the parent window, we can set a simple script to dynamically update the height of the iframe.
The Code
For this tutorial, we’ll need two HTML files: a parent file where we put the iframe, and a child file containing the iframe’s contents.
child.html
Our child file will contain a simple dummy text generator, where people can click a button to add another…