Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically resize an iFrame (crossbrowser solution)

I am trying to include an iframe on a Drupal page. So far I successfully included the frame but the height resize function that I wrote only works in Internet Explorer. My goal is to make resize work inFirefox and Chrome as well. I searched the Internet but I couldn't find what I was looking for. Long story short, I want my frame to automatically resize height itself.

This is what I did so far (this is the code of the HTML page included in Drupal):

<script type="text/javascript">
    function resize() {
        var iframe = document.all.icw;
        document.getElementById("icw").style.height = iframe.document.body.scrollHeight + "px";
    }
</script>
<iframe id="icw" src="XXXXX" width="100%" scrolling="no" onload="resize()">

I understand that if the iframe lives on another domain the solution may be more difficult due to permissions. Is that correct?

These are the errors I get in Chrome and Firefox:

Chrome: Cannot read property 'body' of undefined

Chrome: JavaScript attempt to access frame with URL XXX from frame with URL YYY. Domains, protocols and ports must match.

Firefox: document.all is undefined

EDIT: What if I want to change one of the iframe element? In my case I need to change a textbox value. I understand I must do that when the page is loaded but I can't find a solution. No matter where I put the code I always a get a

Cannot call method 'getElementById' of undefined

when I try to access the iFrame textbox.

EDIT2: Asked a new question since they weren't related.

like image 759
raz3r Avatar asked Oct 30 '12 08:10

raz3r


2 Answers

This solution works even cross-domain as long as you have access to both. There are a bunch of edge cases, but at least you can start with this. You can also add timer event to make sure iFrame is always a correct size so you never have scrollbar. Keep in mind this only works with browser supporting HTML5 due to the use of postMessage.

Inside iFrame

function resize(){
    var body = document.body,
    html = document.documentElement,
    height = body.offsetHeight;
    if(height === 0){
        height = html.offsetHeight;
    }
    parent.postMessage({'action':'RESIZE', 'height':height}, '*');
}

Parent

function handleMessage(e) {
    if (e.data.action == 'RESIZE') {
        var targetHeight = e.data.height;
        $('#iFrame').height(targetHeight);
    }
}

window.addEventListener("message", handleMessage, false);
like image 178
juminoz Avatar answered Oct 01 '22 19:10

juminoz


window.addEventListener("message", handleMessage, false);

This code do not work for IE.

For IE use

window.attachEvent("onmessage", handleMessage, false);
like image 35
Deepak Gangore Avatar answered Oct 01 '22 21:10

Deepak Gangore