Resize iframe by its content – cross-domain

Posted on 24. January 2014

We all had this problem once: Including an iFrame into a website and then – there were scroll bars which mess up everything. But have you ever heard of the JavaScript method Window.postMessage? We can use this method to communicate between the iframe and its parent and it is also widely supported.

At first, we need to register the message event to the listener on the parent:

// browser compatibility: get method for event // addEventListener(FF, Webkit, Opera, IE9+) and attachEvent(IE5-8) var myEventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; // create event listener var myEventListener = window[myEventMethod]; // browser compatibility: attach event uses onmessage var myEventMessage = myEventMethod == "attachEvent" ? "onmessage" : "message"; // register callback function on incoming message myEventListener(myEventMessage, function (e) { // we will get a string (better browser support) and validate // if it is an int - set the height of the iframe #my-iframe-id if (e.data === parseInt(e.data)) { document.getElementById('my-iframe-id').height = e.data + "px"; } }, false);

Note: You can limit the source of the message for security by asking the event for its origin (e.origin).

Now we need to post the message, the height of its content, by the iframe:

// all content including images has been loaded window.onload = function() { // post our message to the parent window.parent.postMessage( document.body.scrollHeight // get height of the content ,"*" // set target domain ) };

Thats it. Thats all.

Made with ♥️ and Gatsby © 2024