Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross domain iframe resizer using postMessage

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

like image 860
Peter Avatar asked Sep 23 '11 16:09

Peter


2 Answers

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>
like image 74
Peter Avatar answered Sep 30 '22 11:09

Peter


Using Peter's code and some ideas from here, you could separate out the compatibility from the executable code, and add some cross-site validation.

<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (e.origin !== 'http://yourdomain.com' || isNaN(e.data)) return;
    document.getElementById('iframe_id_goes_here').style.height = e.data + 'px';
  }, false);
</script>

Also, for completeness, you could use the following code within the iframe whenever you want to trigger the resize.

parent.postMessage(document.body.offsetHeight, '*');
like image 43
deadbeef404 Avatar answered Sep 30 '22 13:09

deadbeef404