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.

18,908 thoughts on “iframe automatic height adjustment using HTML5 cross domain web messaging

  1. Посетите https://accs-shop.com/ – это Магазин аккаунтов №1 с многолетним опытом работы, в котором вы сможете купить аккаунты в широком ассортименте. Посмотрите категории – там вы обязательно найдете для себя необходимый товар. Каждый аккаунт проходит тщательную проверку перед продажей, вы можете быть уверены в качестве, а поддержка работает быстро!

  2. Game-Lands https://game-lands.ru/ – это сайт с подробными гайдами и прохождениями для новичков и опытных игроков. Здесь вы найдете лучшие советы, топовые билды и сборки, точное расположение предметов, секретов, пасхалок, и исправление багов на релизах. Узнаете, как получить редкие достижения, что делать в сложных моментах и с чего начать в новых играх. Всё, чтобы повысить скилл и раскрыть все возможности игровых механик.

  3. Ищете просмотры вк накрутка на видео? Сервис seoprofi.org специализируется на безопасной накрутке просмотров для Rutube и VK Видео, а также увеличении посещаемости сайтов с помощью живого трафика. Система гарантирует равномерное увеличение метрик с органичным удержанием в диапазоне 40-80%, способствуя продвижению материалов в рекомендательные ленты и повышению ранжирования без угрозы санкций. Ценовая политика начинается с 1200 рублей за тысячу единиц посещений, старт проектов осуществляется за 1-3 часа при наличии поддержки 24/7.

  4. Ищете тибетская музыкальная чаша купить? Terapiazvu.com предлагает обучение вибро-акустическому массажу тибетскими поющими чашами ручной работы с применением методов резонансно-акустической терапии. Опытные преподаватели организуют двухуровневые курсы по освоению звукотерапии, консультируют при выборе персональной чаши в онлайн-режиме и гарантируют бесплатную пересылку товара по стране. Звуковые практики с тибетскими чашами эффективно снимают стресс, восстанавливают энергетический баланс организма и помогают в решении психосоматических проблем.

  5. Thanks for covering maintenance! Shade structures live or die by fabric quality and hardware. If you’re looking for a quick selector tool by climate, snow load, and sun angle, you might find this useful: pergola builder .

  6. Языковой образовательный центр в Алматы и Атырау предлагает современное обучение английскому и другим языкам по доступным ценам для взрослых и детей любого уровня подготовки. Эффективные методики развития устной речи, грамматики и лексики реализуют дипломированные преподаватели с богатым опытом работы. Подробная информация о программах представлена на сайте https://www.ctgroup.kz/ Учебное заведение организует коллективные курсы численностью до 6 учащихся и персональные занятия в технологичных классах с обеспечением сопровождения до получения целевого балла.

  7. Mi arıyorsunuz guvenilir casino siteleri? Sekabet Casino’ya Türkiye’den güvenle ulaşmak, üyelik ve finans işlemleri rehberini görmek ve en iyi geliştiricilerin oyunları ile spor bahislerini incelemek için villaperret26.com adresine göz atın. Promosyonlarımız ile bonuslarımız, kullanıcılar için yüksek değerli ödül sistemi sunar. Uygulamamız mobilde her an erişilebilir; kullanımı pratik ve tüm cihazlarla uyumlu.

  8. VIP ESCORT SERVICE Escort agency – VIP escorts elite escort

  9. Anyone here completed a solar panel installation near me in La Mesa recently? Curious about timelines, permitting experience, and inverter brands used. I’m also exploring long-term maintenance options. I’m reviewing details on solar panel warranty repair .

  10. Embracing nature’s beauty creates spaces where families gather comfortably across seasons alike ; take steps forward now ! Seek guidance shared amongst talented professionals facilitating growth through connection established using # local landscaping services

  11. ETNA https://www.etnasoft.com/ is a white-label fintech platform for broker-dealers and RIAs offering integrated trading, wealth management, and back-office solutions. Features include multi-asset trading, automated portfolio rebalancing, compliance automation, mobile apps, and 20+ custodian integrations. The platform deploys in two weeks, supports complete brand customization, and scales from startups to established firms managing billions in assets.

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>