Javascript iframe style height

Change Iframe Size Automatically to Fit Content & Prevent Scrollbars

There are 2 ways to automatically change the size of an 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 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 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.
   

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, "*"); >); 
  

Demo

The demo uses a same-origin iframe. It uses setInterval() to keep checking the iframe size at intervals of 500ms.

   

Download Codes
(Note that even though the files contain only HTML, you must run them from a server)

Читайте также:  Php filter file path

Источник

Оцените статью