Set the height of iframe based on its content

In this short blog post, I show you how to set the height of an iframe based on its content.

The credit of this post goes to @themsaid. I saw it on twitter and thought it would benefit a few people.

The script loops through all the iframes and sets their heights based on the content height of their content.

const iframes = document.querySelectorAll('iframe');


function setIframeHeight(iframe) {
	let body = iframe.contentDocument.body;
	let html = iframe.contentDocument.documentElement;

	let height = Math.max(
          body.scrollHeight,
          body.offsetHeight,
          html.clientHeight,
          html.scrollHeight,
          html.offsetHeight
		);

	iframe.style.height = height + 1 + "px";

}

iframes.forEach(setIframeHeight)