Changing Size of Iframe Automatically to Fit Content

Use-Cases of this Tutorial

  • You have a iframe embedded in your page, whose content keeps on changing. This causes scrollbars to be seen in the main page. You want to solve this problem.
  • Know how to communicate between an iframe and the parent.

Iframes are of great use, but when scrollbars appear in it, the look of the page goes down. These scrollbars are generally caused due to the content being changed in the iframe.

Using a bit of Javascript, you can get rid of the scrollbars. You can be sure that whenever the content inside the iframe changes, the height and width of the <iframe> element will change automatically.

This is done by passing messages from the iframe to the parent at regular intervals. A script inside the iframe informs the parent that the size of the content has changed. The parent on receiving such a message updates the CSS width and height of the <iframe> element, thus preventing scrollbars from coming up.

The same technique is used in Facebook canvas applications. The application is loaded from your server inside an iframe in Facebook. There is a function in Facebook Javascript SDK (which you use in your code), through which the height of the Facebook iframe is automatically resized.

Same-Domain or Cross Domain

The below codes will work both for same domain as well as cross domain iframes.

Demo

Click here to see the demo

Codes for the demo can be downloaded at the end of the tutorial.

Javascript Inside the Iframe

You can use the setInterval function to send a message at regular intervals informing the parent about the size of the iframe content. Such messages can be sent via window.postMessage function.

// Send message to the top window (parent) at 500ms interval
setInterval(function() {
    // first parameter is the message to be passed
    // second paramter is the domain of the parent 
    // in this case "*" has been used for demo sake (denoting no preference)
    // in production always pass the target domain for which the message is intended 
    window.top.postMessage(document.body.scrollHeight, "*");
}, 500); 

document.body.scrollHeight refers to the height of the iframe content

Javascript Inside the Parent

The parent must catch the message passed, so that it can update CSS height and width of the <iframe> element.

window.addEventListener('message', function(e) {
	// message passed can be accessed in "data" attribute of the event object
	var scroll_height = e.data;

	document.getElementById('iframe-container').style.height = scroll_height + 'px'; 
} , false);

Download Sample Codes

Download
(Note that even though the files contain only HTML, you must run them from a server)

How to Communicate Between Parent and Child Windows in Javascript