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).
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:
- 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
- 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.
I’ve finally found my go-to place for Brazilian waxing in Las Vegas: thank you, # any Keyword #! Men’s Waxing Services Las Vegas
Hệ thống bảo mật của 13win13 win khiến mình cảm thấy an tâm hơn khi đặt cược.
Every resident should understand how important utility potholing is to our city’s infrastructure—learn why at Sacramento utility potholing !
If you’re wondering who to call for electrical issues, look no further than Pure Energy Electrical Services—the best choice in St Augustine! electrician
Impressed by the professional expertise of your Sacramento personal injury lawyers, they truly stand out for their dedication to clients. Personal injury attorneys is fortunate to have such a reliable team advocating for individuals in need.
From getting the compensation you deserve to understanding your rights, working with Sacramento personal injury lawyers can make a significant difference Auto accident attorneys
Your site about auto accident attorney seems like a vital resource for individuals seeking expert advice and guidance after facing unexpected challenges like car accidents in Seattle
Rodaballo Al Horno https://rodaballoalhorno.es es un viaje a los origenes de la musica. Exploramos las raices los ritmos y las melodias de diferentes culturas para mostrar como el sonido conecta a personas de todo el mundo y las ayuda a sentirse parte de una conversacion musical mas amplia.
Understanding where utilities are located can save so much time and money during projects—thank you for this valuable information! More at Orange County utility locating !
Rodaballo Al Horno https://rodaballoalhorno.es es un viaje a los origenes de la musica. Exploramos las raices los ritmos y las melodias de diferentes culturas para mostrar como el sonido conecta a personas de todo el mundo y las ayuda a sentirse parte de una conversacion musical mas amplia.
Thanks for the clear advice. More at water heater installation near me .
Love the guidance on insulating exposed pipes. I followed a guide on drain cleaning near me .
) Having options easily offered helps minimize tension ensuring all requirements catered appropriately without fail whatsoever either! portable toilet rental
This is such valuable info for anybody hosting an outside occasion! Think about using porta potties near me for portable toilet leasings.
I’ve been looking for unique garden fountains in Orange County, and Pond Designers Orange County has some of the best designs I’ve seen!
Excellent post about preparing outdoor occasions! Ensure your guests have access to clean facilities with porta potties near me .
This is the best primer on PV hazard mitigation. solar permit services closed gaps before commissioning.
From first contact to delivery, Pristine Portables delivered outstanding cleanliness and quick, friendly service. portable restrooms rent
The expertise and personalized approach of San Diego personal injury lawyers can make all the difference in advocating for your rights and ensuring fair compensation Birth injury attorneys
This is highly informative. Check out Majewski Plumbing for more.
The comfort measures during treatment were reassuring. More on the patient experience at kybella double chin treatment .
I’m grateful for all the resources available for those seeking help with their estate plans in Orange County! california estate planning
Todo sobre videojuegos https://tejadospontevedra.es noticias y tendencias: ultimos lanzamientos anuncios analisis parches esports y analisis de la industria. Analizamos tendencias compartimos opiniones y recopilamos informacion clave del mundo de los videojuegos en un solo lugar.
Todo sobre videojuegos https://tejadospontevedra.es noticias y tendencias: ultimos lanzamientos anuncios analisis parches esports y analisis de la industria. Analizamos tendencias compartimos opiniones y recopilamos informacion clave del mundo de los videojuegos en un solo lugar.
Considering the expertise and dedication of Portland personal injury lawyers, getting legal support can make a significant difference. If you need professional assistance regarding personal injury cases, do check out Slip and fall attorneys for valuable insights!
Loving how supportive everyone has been throughout this journey thus far – it truly feels special being surrounded individuals who strive towards similar aspirations showcased consistently across content provided through links connected directly back boxing gyms
Looking for Kazakhstan standards? Russian and CIS standards in English on the website normlex.com Industry standards, technical norms, regulations, specifications and publications from Russian and CIS markets in both Russian and English. Access to ISO, IEC, ASTM, ASME, ANSI, API, BS, EN, NFPA and many other standards.
Timber Grove Outlet – Browsing is smooth, and the products are easy to find.
I’ve seen some amazing before-and-after photos from local Woodland Hills general contractor s!
profitfunnels.click – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Just had a great experience dealing with essential home builders– they made everything easy and satisfying! Builders Surbiton
adsgrowthengine.click – Content reads clearly, helpful examples made concepts easy to grasp.
marketingpulse.click – Navigation felt smooth, found everything quickly without any confusing steps.
Платформа https://financial-project.ru/ предлагает готовые бизнес-планы для запуска проектов в сферах сервиса, торговли, общепита, медицины и крупного бизнеса — от маникюрных салонов и барбершопов до строительных компаний и тепличных хозяйств. Каждый документ содержит финансовые расчёты, маркетинговый анализ и операционные модели, адаптированные под российский рынок, со скидкой до 50% от базовой стоимости. Сервис сокращает сроки разработки материалов для кредиторов и партнёров, давая экспертный фундамент для открытия дела.
clickperform.click – Loved the layout today; clean, simple, and genuinely user-friendly overall.
This was quite helpful. For more, visit implante capilar Albacete .
leadharvest.click – Overall, professional vibe here; trustworthy, polished, and pleasantly minimal throughout.
Very useful post. For similar content, visit tworzenie stron www .
This was nicely structured. Discover more at fleet vehicle wraps bay area .
https://rennerusa.com/
1xbetbest
how to get 1xbet promo code
trendvaultstore – Great assortment and quick ordering, very pleased.
dailydealshub – Easy to find what I needed, shopping was seamless and smooth.
I enjoyed this read. For more, visit trasplante capilar Jaén .
Thanks for the practical tips. More at movers santa cruz .
The innovation behind vacuum technology really shines when you see it implemented on-site; this should be standard practice across all jobs in Orange County—learn more at vacuum excavation orange county !
АНО «Аргумент» https://anoargument.ru/ — бюро судебной экспертизы и оценки, которое проводит более 15 видов экспертиз для юристов и руководителей предприятий. Компания выполняет автотехнические, бухгалтерские, строительно-технические, финансово-экономические, налоговые и прочие экспертизы как для суда, так и вне судебного процесса. Специалисты обладают учёными званиями, действуют во всех регионах страны и эффективно отстаивают свои выводы в судебных инстанциях.
https://www.radio-rfe.com/
Clogged gutters caused basement seepage for us—lesson learned. Installing gutter guards and new downspouts with kitchner roofing custom contracting eavestrough & roofing soon.