iframe窗口高度自适应的实现方法

前端技术 2023/09/07 JavaScript

domainA 中有一个页面index.html,通过iframe嵌套了domainB中的一个页面other.html
由于other.html页面在iframe中显示,而且其页面内容会动态的增加或减少,现在需要去掉iframe的滚动条
由于javascript同源策略的限制,无法进行跨域操作,使得问题比较棘手
参考了一下网上的做法,引入了一个代理页面,或者叫做中介 agent.html,属于domainA
然后,在domainB 中的other.html中,再使用iframe将agent.html进行嵌套

好了,现在情况是这样的:
index.html 使用iframe 嵌套 other.html
other.html 使用iframe 嵌套 agent.html
之所以要引入第3个页面agent.html,就是为了遵守“同源策略”的规则,完成不同domain下参数的传递!

我们最终的目的是要去掉滚动条,又要保证被嵌入的页面内容全部得到显示
1.取得other.html页面的实际高度height
2.将height设置到其嵌入的iframe的src属性上
3.在agent.html中截取出所属iframe的src属性中的height值

下面的例子中,使用了一个技巧,避免了使用setInterval()不断去设置iframe的高度
做法是在iframe的src上,附加一个时间戳,让浏览器每次都重新加载agent.html
进而让agent.hml中的js函数invokeMethodInTopWindow()得到执行
domainA 中的2个html
index.html

复制代码 代码如下:

#{extends \'main.html\' /}
#{set title:\'Home\' /}

<hr>

<div style=\"color:red;font-weight:bold\">窗口自适应---绕开同源策略的限制,同时又利用同源策略,去掉iframe的滚动条,动态调整窗口的高度,让其能够显示被嵌套页面的所有内容</div>
<!-- 需要动态调整高度的iframe -->
<div style=\"text-align:center;\">
    <iframe name=\"domainB\" src=\"http://127.0.0.1:8088/other\" width=\"80%\" scrolling=\"no\" frameborder=\"0\"></iframe>
</div>

<script type=\"text/javascript\">
    function resize(height) {
        //alert(\"resize\");
        document.getElementsByName(\"domainB\")[0].height=height;
    }
</script>

本文地址:https://www.stayed.cn/item/19311

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。