Cross Domain Iframe Height Resize

If you try to set an iframe height which is hosted in another domain, the browser might throw security exception. So here is my solution to get it work in every browser based on the cross-domain jQuery postMessage Plugin.

Note that both parent and child need to include the jQuery postMessage javascript.

The parent frame code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script type="text/javascript" src="jquery.ba-postmessage.min.js"></script>
 
<div id="iframe"></div>
 
<script type="text/javascript">
(function ($) {
var if_height,
       src = 'http://childframeurl.com#' + encodeURIComponent( document.location.href ),
       iframe = $( '<iframe " src="' + src + '" width="700" height="1000" scrolling="no" frameborder="0"><\/iframe>' ).appendTo( '#iframe' );
 
       setInterval(function getHeight() {
             $.receiveMessage(function(e){
                    var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );
                    if ( !isNaN( h ) && h > 0 && h !== if_height ) {
                    // Height has changed, update the iframe.
                    iframe.height( if_height = h );
                    }
             } );
       }, 500);
})(jQuery);
</script>

The child frame code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type="text/javascript" src="jquery.ba-postmessage.min.js"></script>
<script type="text/javascript">
(function ($) {
       $(document).ready(function() {
             var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ),link;
 
             function setHeight() {
                    $.postMessage({ if_height: $('body').outerHeight( true ) }, parent_url, parent );
             };
             setHeight();
             setInterval(setHeight, 500);
       });
})(jQuery);
</script>

Share this

The Author

admin - Hello, my name is Simon, I’am 25 and I’m a software and web developer. My interests span all aspects of programming and development, including ASP, JavaScript, AJAX, PHP, .NET, Java, C#, C++, Objectv-C, Flash, Cocoa, SQL, XML and everything in between. www.simra.ch

Leave a Reply

*
 
© 2010 onYou GmbH. All Rights Reserved