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
  • 21,519
  • 75
  • 241
  • 416
Fred Wilson
  • 2,177
  • 3
  • 17
  • 21

5 Answers5

21

jQuery is not needed.

parent.document.body.clientHeight

That works for me with IE7 and FF3.

Thinker
  • 14,234
  • 9
  • 40
  • 55
  • 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
7

In jQuery you can do

$(parent.window).width();
Kld
  • 6,970
  • 3
  • 37
  • 50
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,748
  • 2
  • 33
  • 33
3

Another possibility is :

$(window.parent.document).height()
Elo
  • 2,234
  • 22
  • 28
0

Google sent me here while trying to get the width of the parent window in a cross-domain iframe. Posting here to save someone else the time I spent on it.

As mentioned above, browser security won't let you access the parent window or document, if the iframe is on a different domain. You can either pass the width to the iFrame using the postMessage API. Or in my case, I didn't really need the width of the window or document, the width of the user's whole screen was fine. This is available even in a cross domain iframe via window.screen.width. You can also do window.screen.height.

Collin Krawll
  • 2,210
  • 17
  • 15