Cross Domain IFRAME resize

2.7k views Asked by At

I know this get's asked a lot, but how do I set the dynamic height of a cross domain iframe, when I don't have access to the actual page the IFRAME is showing?

4

There are 4 answers

3
Quentin On BEST ANSWER

You can't. There is no way to know what the height of the document in the frame is from outside the frame because all information about the document is protected from third party sites.

0
brians69 On

I was having this issue too but I finally got a solution:

Put this code inside the <head>:

    <script type="text/javascript">
  function resizeCrossDomainIframe(id, other_domain) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', function(event) {
      if (event.origin !== other_domain) return; // only accept messages from the specified domain
      if (isNaN(event.data)) return; // only accept something which can be parsed as a number
      var height = parseInt(event.data) + 0; // add some extra height to avoid scrollbar
      iframe.height = height + "px";
    }, false);
  };
</script>

Then, use this code for the iframe:

<iframe src='http://www.example.com/my-iframe/' frameborder="0" id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://www.example.com');">
4
Steen On

If you have access to add javascript on both parent and iframe page you can add this to both:

document.domain = 'mydomain.com';

This way you avoid the cross-domain restrictions, and can sniff the hight to change iframe height in parent page

0
gaby de wilde On

have to proxy the page though your own server (at least one time)

<?php
$homepage = file_get_contents('http://www.megaupload.com'); 
echo $homepage;
?>
<script>etc</script>