Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Automatic Iframe Height The Right Way

Unfortunately there still are times when you need to embed an iframe. Most of the time you would want to assign an automatic height to the iframe. It's not very easy, but it's definitely doable if you meet a couple of requirements.

Requirements needed for auto iframe height

The page calling the iframe and the iframed page should have the:

  • Same host
  • Same protocol
  • Same port

This means:

  • a page at www.domain1.com can't call a page on www.domain2.com
  • a page at domain1.com can call a page on domain1.com or on a sub domain, xx.domain1.com

For this to work, you also need to add this code snippet (in <script>) to both pages, preferably in the <head> section:

document.domain = /(\w+)(.\w+)?$/.exec(location.hostname)[0];

This code snippet tells the browser the default domain (host), which need to be the same according to the requirements above.

Common error code

This is the error you get in Chrome if you make an illegal iframe call:

Unsafe JavaScript attempt to access frame with URL http://domain1.com
from frame with URL http://otherdomain.com.
Domains, protocols and ports must match.

Now you know the solution.

Auto iframe script

Here's a working auto iframe height script you can use.

It's even non jQuery (even though it says it's jQuery).

Comments

Download URL broken.

Thanks for the heads up. Seems lost-in-code.com is experiencing some troubles recently. I'll see what I can do.

To the top