Resizing an iframe based on content

I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.

How do I resize the iframes to fit the height of the iframes' content?

I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.

Update: Please note that content is loaded from other domains, so the same-origin policy applies.



We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.

There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.

There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:, which iframes
 |->, which iframes

then home.html can communicate with framed.html (iframed) and helper.html (same domain).

 Communication options for each page:
 |                         | home.html | framed.html | helper.html |
 |   |    N/A    |     YES     |     YES     |
 | |    NO     |     N/A     |     YES     |
 | |    YES    |     YES     |     N/A     |

framed.html can send messages to helper.html (iframed) but not home.html (child can't communicate cross-domain with parent).

The key here is that helper.html can receive messages from framed.html, and can also communicate with home.html.

So essentially, when framed.html loads, it works out its own height, tells helper.html, which passes the message on to home.html, which can then resize the iframe in which framed.html sits.

The simplest way we found to pass messages from framed.html to helper.html was through a URL argument. To do this, framed.html has an iframe with src='' specified. When its onload fires, it evaluates its own height, and sets the src of the iframe at this point to helper.html?height=N

There's an explanation here of how facebook handle it, which may be slightly clearer than mine above!


In, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):

  // Resize iframe to full height
  function resizeIframe(height)
    // "+60" is a general rule of thumb to allow for differences in
    // IE & and FF height reporting, can be adjusted as required..
    document.getElementById('frame_name_here').height = parseInt(height)+60;
<iframe id='frame_name_here' src=''></iframe>


<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>

<script type="text/javascript">
  function iframeResizePipe()
     // What's the page height?
     var height = document.body.scrollHeight;

     // Going to 'pipe' the data to the parent through the helpframe..
     var pipe = document.getElementById('helpframe');

     // Cachebuster a precaution here to stop browser caching interfering
     pipe.src = ''+height+'&cacheb='+Math.random();


Contents of

This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content 
  <body onload="parentIframeResize()"> 
      // Tell the parent iframe what height the iframe needs to be
      function parentIframeResize()
         var height = getParam('height');
         // This works as our parent's parent is on our domain..

      // Helper function, parse param from request string
      function getParam( name )
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
          return results[1];

If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it's simple:

<script language="JavaScript">
function autoResize(id){
    var newheight;
    var newwidth;

        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";

<iframe src="usagelogs/default.aspx" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>


window.postMessage is a method for safely enabling cross-origin communication. Normally, scripts on different pages are only allowed to access each other if and only if the pages which executed them are at locations with the same protocol (usually both http), port number (80 being the default for http), and host (modulo document.domain being set by both pages to the same value). window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.


window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called. (Other standard properties of events are present with their expected values.)

The iFrame-Resizer library uses postMessage to keep an iFrame sized to it's content, along with MutationObserver to detect changes to the content and doesn't depend on jQuery.

jQuery: Cross-domain scripting goodness

Has demo of resizing iframe window...

This article shows how to remove the dependency on jQuery... Plus has a lot of useful info and links to other solutions.

Barebones example...

HTML 5 working draft on window.postMessage

John Resig on Cross-Window Messaging


The simplest way using jQuery:

.attr({"scrolling": "no", "src":""})
.load(function() {
    $(this).css("height", $(this).contents().height() + "px");

The solution on works great (uses jQuery):

<script type=”text/javascript”>
  $(document).ready(function() {
    var theFrame = $(”#iFrameToAdjust”, parent.document.body);
    theFrame.height($(document.body).height() + 30);

I don't know that you need to add 30 to the length... 1 worked for me.

FYI: If you already have a "height" attribute on your iFrame, this just adds style="height: xxx". This might not be what you want.


may be a bit late, as all the other answers are older :-) but... here´s my solution. Tested in actual FF, Chrome and Safari 5.0.


iframe {border:0; overflow:hidden;}


    $("iframe").load( function () {
        var c = (this.contentWindow || this.contentDocument);
        if (c.document) d = c.document;
        var ih = $(d).outerHeight();
        var iw = $(d).outerWidth();
            height: ih,
            width: iw

Hope this will help anybody.


Finally I found some other solution for sending data to parent website from iframe using window.postMessage(message, targetOrigin);. Here I explain How I did.

Site A = Site B =

SiteB is loading inside the siteA website

SiteB website have this line

window.parent.postMessage("Hello From IFrame", "*"); 


window.parent.postMessage("Hello From IFrame", "");

Then siteA have this following code

// Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];

var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child IFrame window
eventer(messageEvent, function (e) {
   // Do whatever you want to do with the data got from IFrame in Parent form.
}, false); 

If you want to add security connection you can use this if condition in eventer(messageEvent, function (e) {})

if (e.origin == '') {
    // Do whatever you want to do with the data got from IFrame in Parent form.

For IE

Inside IFrame:



 eventer(messageEvent, function (e) {
   var data = jQuery.parseJSON(;
 }, false);

Here is a simple solution using a dynamically generated style sheet served up by the same server as the iframe content. Quite simply the style sheet "knows" what is in the iframe, and knows the dimensions to use to style the iframe. This gets around the same origin policy restrictions.

So the supplied iframe code would have an accompanying style sheet like so...

<link href="" rel="stylesheet" type="text/css" />? <iframe id="iframe_widget" src="" frameborder="0" width="100%" scrolling="no"></iframe>

This does require the server side logic being able to calculate the dimensions of the rendered content of the iframe.


This answer is only applicable for websites which uses Bootstrap. The responsive embed feature of the Bootstrap does the job. It is based on the width (not height) of the content.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src=""></iframe>



I'm implementing ConroyP's frame-in-frame solution to replace a solution based on setting document.domain, but found it to be quite hard determining the height of the iframe's content correctly in different browsers (testing with FF11, Ch17 and IE9 right now).

ConroyP uses:

var height = document.body.scrollHeight;

But that only works on the initial page load. My iframe has dynamic content and I need to resize the iframe on certain events.

What I ended up doing was using different JS properties for the different browsers.

function getDim () {
    var body = document.body,
        html = document.documentElement;

    var bc = body.clientHeight;
    var bo = body.offsetHeight;
    var bs = body.scrollHeight;
    var hc = html.clientHeight;
    var ho = html.offsetHeight;
    var hs = html.scrollHeight;

    var h = Math.max(bc, bo, bs, hc, hs, ho);

    var bd = getBrowserData();

    // Select height property to use depending on browser
    if (bd.isGecko) {
        // FF 11
        h = hc;
    } else if (bd.isChrome) {
        // CH 17
        h = hc;
    } else if (bd.isIE) {
        // IE 9
        h = bs;

    return h;

getBrowserData() is browser detect function "inspired" by Ext Core's

That worked well for FF and IE but then there were issues with Chrome. One of the was a timing issue, apparently it takes Chrome a while to set/detect the hight of the iframe. And then Chrome also never returned the height of the content in the iframe correctly if the iframe was higher than the content. This wouldn't work with dynamic content when the height is reduced.

To solve this I always set the iframe to a low height before detecting the content's height and then setting the iframe height to it's correct value.

function resize () {
    // Reset the iframes height to a low value.
    // Otherwise Chrome won't detect the content height of the iframe.

    // Delay getting the dimensions because Chrome needs
    // a few moments to get the correct height.
    setTimeout("getDimAndResize()", 100);

The code is not optimized, it's from my devel testing :)

Hope someone finds this helpful!

function frameSize(id){
var frameHeight;

document.getElementById(id).height=0 + "px";

document.getElementById(id).height= (frameHeight) + "px";


<iframe id="frame"  src="startframe.html" frameborder="0" marginheight="0" hspace=20     width="100%" 


<p>This will work, but you need to host it on an http server, you can do it locally.    </p>

iGoogle gadgets have to actively implement resizing, so my guess is in a cross-domain model you can't do this without the remote content taking part in some way. If your content can send a message with the new size to the container page using typical cross-domain communication techniques, then the rest is simple.


When you want to zoom out a web page to fit it into the iframe size:

  1. You should resize the iframe to fit it with the content
  2. Then you should zoom out the whole iframe with the loaded web page content

Here is an example:

<div id="wrap">
   <IFRAME ID="frame" name="Main" src ="" />

<style type="text/css">
    #wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }
    #frame { width: 900px; height: 600px; border: 1px solid black; }
    #frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }

Here's a jQuery approach that adds the info in json via the src attribute of the iframe. Here's a demo, resize and scroll this window.. the resulting url with json looks like this...{docHeight:5124,windowHeight:1019,scrollHeight:571}#

Here's the source code fiddle

function updateLocation(){

    var loc = window.location.href;
    window.location.href = loc.replace(/#{.*}#/,"") 
        + "#{docHeight:"+$(document).height() 
        + ",windowHeight:"+$(window).height()
        + ",scrollHeight:"+$(window).scrollTop()




get iframe content height then give it to this iframe

 var iframes = document.getElementsByTagName("iframe");
 for(var i = 0, len = iframes.length; i<len; i++){
      window.frames[i].onload = function(_i){
           return function(){
                     iframes[_i].style.height = window.frames[_i].document.body.scrollHeight + "px";

Work with jquery on load (cross browser):

 <iframe src="your_url" marginwidth="0"  marginheight="0" scrolling="No" frameborder="0"  hspace="0" vspace="0" id="containiframe" onload="loaderIframe();" height="100%"  width="100%"></iframe>

function loaderIframe(){
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);

on resize in responsive page:

if($('#containiframe').length !== 0) {
var heightIframe = $('#containiframe').contents().find('body').height();
 $('#frame').css("height", heightFrame);

Using jQuery:


<script type="text/javascript" src=""></script>
iframe {
    width: 100%;
    border: 1px solid black;
function foo(w, h) {
    $("iframe").css({width: w, height: h});
    return true;  // for debug purposes
<iframe src="child.html"></iframe>


<script type="text/javascript" src=""></script>
$(function() {
    var w = $("#container").css("width");
    var h = $("#container").css("height");

    var req =, h);
    console.log(req); // for debug purposes
body, html {
    margin: 0;
#container {
    width: 500px;
    height: 500px;
    background-color: red;
<div id="container"></div>

This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.


Something on the lines of this i belive should work.


Load this with your body onload on the iframe content.


I have an easy solution and requires you to determine the width and height in the link, please try (It works with most browsers):

<a href='#' onClick=" document.getElementById('myform').src='t2.htm';document.getElementById('myform').width='500px'; document.getElementById('myform').height='400px'; return false">500x400</a>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.