开发者

How can I dynamically resize my iframe, avoiding the browser security crossdomain restrictions?

开发者 https://www.devze.com 2023-01-31 08:03 出处:网络
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it\'s not known what height it will be

We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the开发者_开发技巧 host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?


This can be a real pain in the butt to get working cross browser.

I strongly suggest you use easyXDM (http://easyxdm.net/). It's a JavaScript library that uses the PostMessage transport on modern browsers and uses some JavaScript ninja on old browsers.

The library allows you to communicate between an Iframe and it's parent even if they aren't on the same domain.

The library supports all the way down to IE6!

Edit: There's actually an example to resize the height of an Iframe dynamically once content is loaded: http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/

  • Christian


Although i have no particular experience with this situation referencing the following wouldn't hurt: Cross Domain Iframe Resize


Depending on the simplicity of the page you're trying to load, you could try loading it with PHP and exposing some variables while building the HTML (if this is even an option, of course).

For example, you could load it with file_get_contents, use some regular expressions to find the img width and height, and then use those values when echo'ing the iframe.

0

精彩评论

暂无评论...
验证码 换一张
取 消