Change Iframe Size Automatically To Fit Content & Prevent Scrollbars

post imageChange Iframe Size Automatically to Fit Content & Prevent ScrollbarsJavascriptUpdated on 23 January 2021

There are 2 ways to automatically change the size of an <iframe> so as to fit its content and prevent scrollbars :

  • For same-domain iframes : From the parent page, the complete height & width of the iframe can be found through its contentDocument.body.scrollHeight & contentDocument.body.scrollWidth properties. These values can then be set as the CSS height & width of the <iframe> element.
  • For cross-domain iframes : The iframe page can send a message to the parent page using postMessage(), informing about its size. On receiving the message, the parent page can change CSS height & width of the <iframe> element.

Same-Domain Iframes

For same-domain iframes, code changes are required only in the parent page. The iframe page needs no code changes.

  • First we need to wait for the iframe to be loaded so that its correct dimensions are available.
  • After iframe has been loaded, contentDocument.body.scrollHeight property gets its full height.
  • contentDocument.body.scrollWidth property gets its full width.
<iframe src="child.html" id="child-iframe"></iframe> <script> let iframe = document.querySelector("#child-iframe"); iframe.addEventListener('load', function() { iframe.style.height = iframe.contentDocument.body.scrollHeight + 'px'; iframe.style.width = iframe.contentDocument.body.scrollWidth + 'px'; }); </script>

Cross-Domain Iframes

For cross-domain iframes, code changes are needed in both the iframe & the parent page.

  • The iframe page needs to be loaded first to get correct dimensions. After loading, its dimensions are passed to the parent page using postMessage().

    window.addEventListener('load', function() { let message = { height: document.body.scrollHeight, width: document.body.scrollWidth }; // window.top refers to parent window window.top.postMessage(message, "*"); });
  • In the parent page, the message is recieved, and the <iframe> CSS dimensions are updated.

    <iframe src="https://cross-domain.com/child.html" id="child-iframe"></iframe> <script> let iframe = document.querySelector("#child-iframe"); window.addEventListener('message', function(e) { // message that was passed from iframe page let message = e.data; iframe.style.height = message.height + 'px'; iframe.style.width = message.width + 'px'; } , false); </script>
Related PostsHow to Communicate Between Parent and Child Windows in Javascript

Từ khóa » Html Iframe Size Auto