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.
This one’s worth your attention—check out this article http://fremontrp.listbb.ru/viewtopic.php?f=18&t=2456
new 2021 casino uk, olg thousand islands casino and online gambling uk
legal, or united kingdom civil war poker tables
My webpage; What Is Outside Bet In Roulette
ryla6760 – Excellent resource for both students and Rotary clubs involved in RYLA.
2021nikemenshoes.top – Delivery info seems clear, I’m tempted to place an order.
warmm1.cc – I’ll revisit often — there’s promise in what I saw.
zukdfj.shop – I enjoy the tone: casual yet professional — good combo.
80hg88.cc – Great find, will share with friends who like similar topics.
qyrhjd.top – The tone is casual but still informative, good balance.
20b7f9xg.xyz – The writing is direct and helpful—no fluff, which I appreciate.
nav6.xyz – Crisp design and helpful articles, wish there were more updates.
A vibrant platformer guiding a panda through exciting puzzles and treasures. Fun and family-friendly: Panda game walkthrough
Refcom INFO — авторы с опытом более 25 лет: консультируют по ВКР и диссертациям, готовят научные статьи, проверяют и сопровождают по Антиплагиату. Работают напрямую, без посредников, с клиентами из KZ, RU, BY, UA, а также Европы; подскажут структуру, оформят таблицы и презентации, помогут повысить уникальность и подготовиться к защите. Ищете курсовые на заказ в ЯНАО? Подробности на refcom.info — пишут аккуратно, проверяют тщательно, соблюдают сроки и конфиденциальность. С публикациями в РИНЦ/Elibrary помогают — готовят и размещают, а про ВАК/Scopus/WoS сразу уведомляют, что не берут.
seostream – The content is diverse and engaging.
elipso.site – Wow, stumbled on this site today and really like its layout.
rinatmat – Very user friendly, and I like the topic variety here.
comprafacilrd – I checked the product selection and pricing feels very competitive.
wzoo – The layout is clean and browsing feels effortless here.
hpwt02n0me – Good use of white space, makes reading less tiring.
u888vn – Posts are well detailed, very good for learning new things.
pacerproes – Really like this site, layout feels modern and clean.
htechwebservice – Great site overall, design feels professional and modern.
ifyss – I enjoy the fresh perspective this site offers.
caneguida – The layout is clean and easy to navigate.
683tz084 – Great resource for those interested in niche subjects.
В сердце Новосибирска расположен настоящий оазис для владельцев техники Apple — сервисный центр iClub, где профессионалы с более чем 11-летним опытом берутся за ремонт iPhone, MacBook, iPad и даже устройств других брендов, таких как Samsung и Xiaomi. Здесь вас ждет срочный ремонт в присутствии клиента, использование только оригинальных запчастей и гарантия до 12 месяцев, что подтверждают тысячи положительных отзывов от довольных пользователей, хвалящих быстроту и качество работы. Ищете ремонт iphone xs max? — обратитесь на iclub.pro, где команда квалифицированных мастеров вернет ему жизнь без лишних наценок и обмана. Центр предлагает удобное расположение недалеко от метро, бесплатную парковку, оплату в рассрочку и даже услугу проверки устройств при покупке с рук, чтобы вы избежали подделок. С акциями вроде скидок до 30% на установку ОС и подарочными защитными стеклами, iClub становится идеальным выбором для тех, кто ценит честность, профессионализм и заботу о клиенте — доверьте свою технику экспертам и наслаждайтесь ее безупречной работой.
seoelitepro – The content is diverse and engaging.
LDV-Case — дизайн-ателье премиальных чехлов из натуральной кожи для популярных моделей смартфонов. Ручная работа, редкие фактуры (страус, змея, крокодил, нога страуса), плотная посадка без зазоров и долговечность, подтверждённая отзывами. Возможен индивидуальный заказ, быстрая доставка и консультации: цены честные, выбор — широкий. Загляните в каталог готовых изделий на https://ldv-case.shop/ и создайте аксессуар, который подчеркнёт ваш стиль каждый день.
fcalegacy – Very informative pages, lots of value in each section.
Looking for merge game? play.google.com/store/apps/details?id=games.ugo.merge.secrets It’s an adventure puzzle merge game featuring quests, diverse locations, and a narrative-driven journey. It’s fully free to play: all downloads and participation in in-game activities are at no cost. Join us on this journey and start uncovering island secrets today!
iyimu – The content is diverse and engaging.
h7721 – The site’s structure is intuitive, good job on navigation.
bslthemes – The design is minimalist yet effective.
Планируете вечер у моря или камерную встречу дома? Dubaialco.ru превращает задумку в праздник: внушительный выбор — от шампанского и просекко до виски, текилы и бризеров — с удобной навигацией по категориям и понятными ценами. В витрине — бестселлеры вроде Hennessy, Red Label, Patron, а также Heineken и Smirnoff Ice. Заказ оформляется в пару кликов, а доставка по Дубаю быстрая и точная. Откройте коллекцию на https://dubaialco.ru/ и найдите идеальный напиток под настроение, будь то легкий аперитив, коллекционный коньяк или сет для вечеринки.
bongda247 – A hidden gem for those seeking unique insights.
basingstoketransition – A meaningful cause, the content really educates on local sustainability.
Прочные велосипеды для экстремального катания kra 40 cc kraken рабочая ссылка onion сайт kraken onion kraken darknet
roulette online canada, uptown pokies no deposit bonus
2021 united states and roulette wheels for sale usa,
or roxy casino legal age denmark [Chance] united states
https://wildercasino.fun
newstoday – Layout is clean, images and text balanced nicely throughout.
Мен ар дайым Лука Модричти көргөндө чыныгы лидерликти байкайм.Эгер Лука Модрич кетсе Реалдын орто талаасы өзгөрөт. Модричтин пас тактыгы укмуштуудай. Жаш өткөн сайын Модричтин тажрыйбасы баалуу болуп жатат. Колдон бетер esli kerek болсо бул форматты да эстеп кал: luka-modric-kg com. Хорватиянын эң атактуу оюнчусу дал ушул Модрич. Футбол сүйүүчүлөрү үчүн Модрич — Реалдын жүрөгү. Модрич согуш жылдарында чоңойгон бирок футбол аны сактап калды. Анын баасы трансфермаркетте дагы жогору. Анын тажрыйбасы каалаган клубга керектүү.
cyrusmining – Possibly a scam or low credibility site due to lack of visible information.
wraoys – The domain name is unique, but content direction is unclear so far.
antsmarket – Could be a startup or placeholder—hard to tell real intent yet.
axin2 – I like the font choices here, very readable and neat.
live-sex-cam – Been spending time here lately, always something exciting to explore.
https://mellstroy2025.com
artvoyage – The blog posts about art travel are wonderfully written and engaging.
saltburn – Interesting name, but not much to see here beyond a basic landing page.
dhpb-smile – I visited briefly, the design feels basic but functional so far.
Сео аудит бесплатно онлайн https://seo-audit-sajta.ru