Dynamic height for cross domain iframes

An iframe usually has a fixed height. If you want the iframe to dynamically fit it's content, you'd have to use JavaScript:

var contentFrame = docment.getElementById('my-iframe')
var contentHeight = contentFrame.contentWindow.body.scrollHeight();
contentFrame.style.height = contentHeight + 'px';

Of course this doesn't work for if the source of "my-iframe" has a different hostname or port, since only frames from the exact same domain are allowed to communicate with each other for security reasons (→ cross domain scripting).

However, the iframe that needs to be resized could contain another iframe, which points to the same host as the very parent. When we render the helper-iframe via JavaScript, we can pass information (→ our page height) via a dynamically generated url into it. The helper iframe can then call it's parent's parent back with the information it received via url, since it has the same origin.


<h1>I'm externalwebsite.com</h1>  
<script type=&quot;text/javascript&quot;>
  function resizeWhiteLabelApp(height){
    docment.getElementById('my-iframe').style.height = height + 'px'; 
<iframe id=my-iframe" src="http://whitelabelapps.com/"></iframe>


<script type=&quot;text/javascript&quot;>
  parent.parent.resizeWhiteLabelApp("<?php $_GET['height'] ?>");


<h1>my fancy white-label application</h1>
<script type="text/javascript">
  var str = '<iframe src="http://externalwebsite.com'+ 
    'helper_frame.php?height=' + 
    document.body.scrollHeight + 
    '" style="display:none;"></iframe>';

This can also be done without PHP (completely in JavaScript):

<script type=&quot;text/javascript&quot;>
  var x = "[\\?&]height=([^&#]*)"; 
  x = new RegExp(x);
  x = x.exec(window.location.href);        
  x = ((x==null) ? 0 : x[1]);