Wednesday, September 19, 2012

Resizing Cross-Domain IFrame with Javascript

I tried to find a way to pass height of page loaded in an IFRAME to parent document in order to reset the height of the IFRAME with javascript.
It's a simple coding, but .. if you use IFRAME with a page in a different domain, you cannot access to properties of page opened in IFRAME and from page to opener.

The idea is to be able to pass the value of the height of the content at regular intervals, using a javascript function, and try to read it by the parent.

This applies to the height value, but works for any data, of small size, to be passed client side from content of the iframe to container in a cross domain situation.
Obviously, if we can access page open iframe in edit.

NOTE: Both domains must be added to Trusted Sites.

Let's see how.
I put the following function in the page that I want to load iframe:

setInterval (function () {this.frames.status = getHeight();}, 400);

getHeight function () {

     var height;
    [we calculate body height, or div container height, if it changes with js, i.e.]
     return height;
}

At intervals of 400 ms, the function calculates the height of the loaded page (or element) and sets the object this.frames.status (this object can be write and read in cross domain situation!).

In the page containing the IFRAME, we set code like this:

<!-- this is for write value -->
<div id="div_height"></div>
<script type="text/javascript">

setInterval(function(){

   var iframe = document.getElementsByTagName("iframe")[0];

   if(iframe && iframe.document.frames.status != ""){


      document.getElementById("div_height").innerText = "now iframe has height of " + iframe.document.frames.status + " pixels";

      var h_iframe = parseInt(iframe.document.frames.status) + 150;
      iframe.style.height = h_iframe;
   }
}, 500);
</script>

At intervals of 500 ms, the function reads the value of the iframe.document.frames.status object, converts it to an integer and sets it as the height of the IFRAME (or other objects).

It works!