Cross domain iframe resizer using postMessage

Peter picture Peter · Sep 23, 2011 · Viewed 14.1k times · Source

I've read all the cross domain iframe posts here (my thanks to all of you!) and elsewhere.

The postMessage script at cross-domain iframe resizer? works beautifully in Firefox 5 and up. It resizes the iframe every time a page is clicked within the iframe perfectly.

But it doesn't resize at all in IE (7 8 or 9) on my computer. I checked the security settings and the one in IE for access across domains was checked to enable.

Does postMessage not work in IE? - Or is there something else that needs to be added? thanks

Answer

Peter picture Peter · May 25, 2012

It's a great script from thomax - it also works on so you can use iframes on mobile - iphones and android

For IE7 and IE8, you have to use window.attachEvent instead of window.addEventListener It should also be onmessage instead of message (see below) ps you also need to do the same on the server with the content posting its size

<script type="text/javascript">
if (window.addEventListener)
{
  function resizeCrossDomainIframe(id) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', function(event) {
      var height = parseInt(event.data) + 32; 
      iframe.height = height + "px";
    }, false);
  }
}
else if (window.attachEvent)
{
  function resizeCrossDomainIframe(id) {
    var iframe = document.getElementById(id);
    window.attachEvent('onmessage', function(event) {
      var height = parseInt(event.data) + 32; 
      iframe.height = height + "px";
    }, false);
  }
}
</script>