18

Within an iFrame, we need to get the parent's window/document height.

Is there a way to get this using jQuery?

I know we can use $(document).height() to get a page's height. I just can't figure out how to get the parent's value from within the iFrame.

Alexander Farber
  • 19,827
  • 73
  • 224
  • 393
Fred Wilson
  • 2,147
  • 3
  • 17
  • 20

4 Answers4

21

jQuery is not needed.

parent.document.body.clientHeight

That works for me with IE7 and FF3.

Thinker
  • 13,722
  • 8
  • 39
  • 52
  • 7
    I don't think this would work with an iframe from another site - would it? Not sure if the question cares however. – Adam Nelson Apr 14 '09 at 18:41
  • 8
    Adam is correct. This code only works if [the domain is the same](http://stackoverflow.com/questions/13798540/how-to-get-window-size-from-cross-domain-iframe-in-ie). If it isn't, use postMessage to send the height from the parent to the iframe. – fregante Oct 17 '13 at 18:30
  • @bfred.it Could you perhaps elaborate with the syntax you could use in this scenario? I'm trying to do this with postMessage myself based on your suggestion. I'm trying to get the height and width of the window/browser that a 300x250 iframe is in. – JoeL May 13 '16 at 15:35
  • Request the height with `parent.postMessage(...)` in the iframe; listen to the `message` event in the main window; respond with `iframe.postMessage(document.body.clientHeight)`. Full request/respond code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Example – fregante May 14 '16 at 04:28
6

In jQuery you can do

$(parent.window).width();
Kld
  • 6,748
  • 3
  • 34
  • 49
3

I tried the clientHeight approach on a website where both Iframes where on the same domain and it didn't work. (return 0).

After a lot of testing the best way I have found (and I'll be happy to learn a better way) is to create a function on the parent which returns the document height, something like:

Parent:

function getDocumentHeight(){
   return $(document).height();
}

Iframe:

var parentDocHeight = parent.getDocumentHeight();
Shai Reznik - HiRez.io
  • 8,178
  • 2
  • 32
  • 33
3

Another possibility is :

$(window.parent.document).height()
Elo
  • 1,975
  • 19
  • 24