iframe automatic height adjustment using HTML5 cross domain web messaging

Yesterday I was working on a site that needed an iframe embedded in the page whose content came from a completely different domain. I try to steer clear of iframes at all costs normally so forgive me if what I’m about to say is pretty obvious.

I didn’t want the content in the iframe to appear as though it was in an iframe, so obviously I stripped off all the default browser styles…well, the border. I wanted the iframe to be as high as the content it was containing so that no scroll bars would appear.

So what I did was just give the iframe a height, however when the user navigated to a different page within the iframe, the height I had previously set was too big or too small.

I instantly thought “right, JavaScript will sort this out for me!” and proceeded to quickly code up a function that would inspect the scrollHeight of the content in the iframe and adjust the iframe height accordingly.

No! Said cross domain policy. I had momentarily forgotten all about that. Since the iframe content came from a different domain, I wasn’t allowed to access the document object of the iframe (or vice versa).

Here is how not to do it

Firefox says “Error: Permission denied to access property ‘document’” and other browsers similar.

I started searching for some kind of workaround.  Of course there isn’t really one…except I did find an interesting hack for Firefox. Which is – an iframe document can alter the url fragment of the parent window’s location object! ha madness.

The idea is that the document in the iframe alters the url fragment to read:

http://freestyle-developments.co.uk/blog/?p=150#138

Where 138 is the height of the iframe document (obviously you could be a bit more fancy and send other parameters and name them e.g #height:138 but for simplicity I’ve just set the value). The parent then reads this value and sets the iframe height accordingly:

var iFrameHeight = parseInt(location.hash.replace('#', ''));

So…yeah, that’s pretty interesting, but not really a solution. Check out the example implementation here.

Anyway, what to do? HTML5 web messaging to the rescue! Sweet! HTML5 web messaging is cross domain messaging done right. Not only does the messenger choose who should receive messages, but the recipient also chooses who to receive messages from.

The idea is that after the iframe document has loaded, it sends a message to the parent window telling it what it’s scrollHeight is. The parent listens for messages, and sets the height of the iframe when it receives a message.

A couple of things to note:

  1. There has to be communication between the two documents. i.e. the document on the external domain needs to actively send this message. Which can be a complete show stopper if you have no control over the document on the external domain
  2. This isn’t going to work on IE < 9. I tested the implementation linked below is working on FireFox 4 (Beta 7), Safari 5.0.2, Chrome 8, Opera 10.63 and Internet Explorer 9 Platform Preview 7. Which is a pretty good spread to be honest

Check out the example HTML5 web messaging implementation here.

325 thoughts on “iframe automatic height adjustment using HTML5 cross domain web messaging

  1. Nice blog here! Also your site loads up fast! What host are you using?

    Can I get your affiliate link to your host? I wish my web site
    loaded up as fast as yours lol

  2. I am not certain where you’re getting your information, but good topic.
    I must spend a while studying much more or understanding more.

    Thank you for excellent information I used to be on the lookout
    for this information for my mission.

  3. Helpful information. Fortunate me I found your site unintentionally,
    and I’m surprised why this coincidence didn’t happened earlier!

    I bookmarked it.

  4. Way cool! Some very valid points! I appreciate you penning this write-up and the rest of the website is also very good.

  5. You made some good points there. I checked on the web to find out more
    about the issue and found most people will go along with your views on this web
    site.

  6. Heya i am for the first time here. I found this board and I
    to find It really helpful & it helped me out a lot. I am hoping to provide something back and
    help others such as you aided me.

  7. hey there and thank you for your information – I’ve definitely picked
    up anything new from right here. I did however expertise a few technical points using
    this site, since I experienced to reload the site lots of times previous to
    I could get it to load properly. I had been wondering if your web hosting is OK?
    Not that I am complaining, but sluggish loading instances
    times will very frequently affect your placement in google and can damage your high quality score if advertising and marketing with Adwords.

    Well I am adding this RSS to my e-mail and can look out
    for a lot more of your respective intriguing content.

    Make sure you update this again very soon.

  8. Greetings from California! I’m bored at work so I decided to check out your blog on my iphone during lunch break.
    I enjoy the knowledge you provide here and can’t
    wait to take a look when I get home. I’m shocked at
    how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G ..

    Anyhow, fantastic site!

  9. Hi there! This post couldn’t be written much better!

    Reading through this article reminds me of my previous roommate!
    He constantly kept preaching about this. I’ll send this article to him.
    Pretty sure he’s going to have a good read. I appreciate you for sharing!

  10. Every weekend i used to pay a visit this site, as i wish for enjoyment, for the reason that this this web page conations genuinely
    nice funny material too.

  11. Hi there all, here every person is sharing these kinds of knowledge, thus it’s pleasant to read this website, and I used to visit this web site all the time.

  12. I was suggested this web site by my cousin. I am not sure whether this post
    is written by him as no one else know such detailed about my problem.
    You’re amazing! Thanks!

  13. Currently it sounds like Expression Engine is the
    preferred blogging platform out there right now. (from what I’ve read)
    Is that what you’re using on your blog?

  14. Hello, i read your blog from time to time and i own a similar
    one and i was just curious if you get a lot of spam responses?
    If so how do you reduce it, any plugin or anything you can suggest?

    I get so much lately it’s driving me insane so any assistance is very much appreciated.

  15. I have learn a few just right stuff here. Certainly value bookmarking for
    revisiting. I surprise how a lot attempt you place to make any such wonderful
    informative web site.

  16. I’m not that much of a online reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your website to come back later.
    Cheers

  17. Hey I know this is off topic but I was wondering if you knew
    of any widgets I could add to my blog that automatically tweet my newest
    twitter updates. I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with
    something like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  18. Hi there! This is kind of off topic but I need some help from an established blog.

    Is it tough to set up your own blog? I’m not very techincal but
    I can figure things out pretty quick. I’m thinking about creating my own but
    I’m not sure where to start. Do you have any points or suggestions?
    Thank you

  19. Hi it’s me, I am also visiting this web page regularly, this web site is truly fastidious and the visitors
    are genuinely sharing nice thoughts.

  20. Hi everybody, here every one is sharing these experience, thus it’s pleasant to read this website, and
    I used to visit this website every day.

  21. I am really loving the theme/design of your website.
    Do you ever run into any web browser compatibility
    issues? A couple of my blog visitors have complained about my website not
    working correctly in Explorer but looks great in Firefox.

    Do you have any suggestions to help fix this issue?

  22. I was curious if you ever considered changing the page layout of your blog?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people
    could connect with it better. Youve got an awful lot
    of text for only having one or 2 images. Maybe you could space it out better?

  23. Greetings I am so thrilled I found your site, I really found you by error, while I was researching on Bing for something
    else, Nonetheless I am here now and would just like to say thanks a lot for a marvelous post and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to go through it all at the minute but I have bookmarked it and also added
    your RSS feeds, so when I have time I will be back to read a great deal more,
    Please do keep up the excellent b.

  24. дизайн человека онлайн бесплатно с расшифровкой дизайн для людей дизайн человека расчет рейв карты

  25. расчет бодиграф дизайн человека расчет рейв карты бесплатно пустой бодиграф

  26. Ремонт кофемашин https://coffee-craft.kz с выездом на дом или в офис. Диагностика замена деталей настройка. Работаем с бытовыми и профессиональными моделями. Гарантия качества и доступные цены.

  27. карта по дизайну человека хьюман дизайн это путин по дизайну человека

  28. Круглосуточный вывод из запоя на дому нижний — помощь на дому и в стационаре. Капельницы очищение организма поддержка сердца и нервной системы. Анонимно и конфиденциально.

  29. Купить мебель кухонные уголки для дома и офиса по выгодным ценам. Широкий выбор стильный дизайн высокое качество. Доставка и сборка по всей России. Создайте комфорт и уют с нашей мебелью.

  30. любомудр дизайн человека бодиграф хьюман дизайн рассчитать онлайн

  31. карта дизайна человека дизайн человека посчитать дизайн в жизни человека

  32. генератор проектор манифестор рефлектор дизайн человека рейвы нумерология дизайн человека

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>