Tutorial - Javascript code for automatically iframe resizing | Vevioz Developers

Tutorial Javascript code for automatically iframe resizing


Linux Systems Engineer
Oct 18, 2019
Reaction score
Novosibirsk, Russia
Paste above the iframe youtube converter api code

<!-- Put the Library in your <head> tag -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.2/iframeResizer.min.js"></script>
<!-- Put the resizer code after your <iframe> tag -->
<script>iFrameResize({ log: false, minHeight: 360 }, '#buttonApi')</script>

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.

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.


Our child file will contain a simple dummy text generator, where people can click a button to add another paragraph of lorem ipsum text.

As this tutorial is about the iframe, and not the functionality of what’s in it, feel free to copy and paste the following into child.html.
Top Bottom