Monday, April 9, 2012

iframe resizing

Problem:

The problem is getting the iframe to automatically resize based on the content of the child iframe.

The majority of the solutions to this problem found on the web, expect that both the parent and the child iframe belong to the same domain, and thus avoid the "cross domain" security restriction when accessing the childIFrame.body.scrollHeight  property.



Solution:

When I found this post
he gave me the idea of posting event messages between the parent and child iframe.

I decided to use the jQuery plugin found here for posting messages

Basically, it works as follows. The child iframe posts a message to the parent with its scroll height upon loading the page. The parent listens for messages and when it is received, it adjusts the height of the iframe according to the scroll height it receives from the child iframe. See the example code below:

Parent:
<script type="text/javascript">

    $(document).ready(function() {

        $.receiveMessage( 
                function(e) {
                    alert(e.data);
                    var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );
                    //alert('h='+h);
                    if ( !isNaN( h ) && h > 0 ) {                        
                        $('#snvFrame').height(h);                        
                    }
                    
                },                
                /*
                function(e) {
                    //alert(e);
                    return true;
                }*/
            );
         
     });


</script>

<iframe id="snvFrame" src="<%= PhenomeConfig.getInstance().getIncidentalSNPsUrl() %>" width="100%" frameborder="0" height="100%" allowtransparency="true">


</iframe>


Child:
        <script type="text/javascript">

             $(document).ready(function() {                
                $.postMessage({ if_height: $(document).height() }, 'http://localhost:8989/phenbank/incidentalSNPs.html');                
             });

        </script>




References:

No comments:

Post a Comment