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 can't call a page on
  • a page at can call a page on or on a sub domain,

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
from frame with URL
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).


Download URL broken.

Thanks for the heads up. Seems is experiencing some troubles recently. I'll see what I can do.

To the top