23

I'm trying to resize (make bigger or smaller) an iframe based on it's contents. After a click on each page a method is called which does the resizing.

In Chrome I can make the iframe bigger, but not smaller. document.body.scrollHeight is always the biggest value.

So if one big page sets #iframe.height = '620px', and someone clicks on a link to page with less content scrollHeight will remain at 620px instead of decreasing.

What's the proper way of handling this in Chrome/Safari?

Shai Mishali
  • 9,224
  • 4
  • 56
  • 83
MB.
  • 4,167
  • 8
  • 52
  • 79

3 Answers3

27

Before you ask for the height of the document inside the iframe you should set the height of the iframe object to "auto". Something like this:

objIframe = document.getElementById('theIframeId');    
objIframe.style.height = 'auto';

And now:

document.body.scrollHeight

returns the actual height of the document.

xpereta
  • 692
  • 9
  • 21
  • Brilliant! Have been fighting with this for days! – Mark Parnell Mar 06 '13 at 23:22
  • 2
    If anyone else comes across this, what fixed it for me is setting 'document.body.scrollHeight' for Firefox, and 'document.documentElement.scrollHeight' for Chrome and anything else... My example uses postMessage for cross domain `if(isFirefox) { e.source.postMessage('height:' + document.body.scrollHeight, e.origin); } else { e.source.postMessage('height:' + document.documentElement.scrollHeight, e.origin); }` – nitsuj Feb 19 '14 at 21:35
  • 1
    Thank you for this answer, I've included it in my iFrame library https://github.com/davidjbradshaw/iframe-resizer – David Bradshaw Jun 09 '14 at 23:26
  • @nitsuj just curious, how did you go about deciding which message to listen to or to send (body.scrollHeight vs. documentElement.scrollHeight) in a given browser? – user1422348 Nov 11 '14 at 23:10
  • in my case not iframe but the inner `div` needed to be `height:auto` – Amit Shah Jun 22 '17 at 09:20
11

Did you try using document.documentElement.scrollHeight instead?

Knu
  • 14,806
  • 5
  • 56
  • 89
0

According to spec, Element.scrollHeight will round the value to an integer. If you need an accurate fractional value, use Element.getBoundingClientRect() instead.

Weihang Jian
  • 7,826
  • 4
  • 44
  • 55