我们有一个可嵌入的徽章,可以创建 iframe。它需要是动态大小;它根据从第 3 方 API 或我们的数据库加载的数据来更改大小。所以不知道加载前它的高度是多少。
它是通过一个标签来调用的,该标签从我们的服务器加载脚本,该脚本创建一个设置为特定 src 的 iframe。
在我自己的机器上,在 iframe 中我可以这样做,
window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';
但是当然,当它嵌入到与 iframe src 不同的页面中时,由于跨域限制(FF 中的“不安全访问尝试”错误等),该操作会失败。
由于我们已经将脚本加载到具有完全访问权限的主机页面中,因此这有点愚蠢。
基本上,我需要从 iframe 到主机页面获取一个变量,即新高度。
我可以反过来做吗?主页上有一个函数询问 iframe 它是一个元素的 offsetHeight 吗?
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?
发布评论
评论(3)
对于跨浏览器工作来说,这可能是一个真正的痛苦。
我强烈建议您使用 easyXDM (http://easyxdm.net/)。它是一个 JavaScript 库,在现代浏览器上使用 PostMessage 传输,并在旧浏览器上使用一些 JavaScript 忍者。
该库允许您在 Iframe 与其父级之间进行通信,即使它们不在同一域中也是如此。
该库支持一直到 IE6!
编辑:实际上有一个示例可以在加载内容后动态调整 Iframe 的高度: http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/
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/
虽然我对这种情况没有特别的经验,但引用以下内容不会有什么坏处: 跨域 Iframe 调整大小
Although i have no particular experience with this situation referencing the following wouldn't hurt: Cross Domain Iframe Resize
根据您尝试加载的页面的简单性,您可以尝试使用 PHP 加载它并在构建 HTML 时公开一些变量(当然,如果这是一个选项的话)。
例如,您可以使用 file_get_contents 加载它,使用一些正则表达式来查找 img 宽度和高度,然后在 echo'ing iframe 时使用这些值。
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.