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
<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>
agent.html
//alert("realHeight:"+realHeight);
//alert(document.parentWindow.name);//獲取容器所在窗口的名稱 domainA
//error://alert(document.parentWindow.parent.name); //訪問失敗 :不能訪問domainB
//alert(document.parentWindow.parent.parent.name);//最頂層window屬于domainA,因此可以訪問
}
//使用不同的時間戳設置iframe的src屬性后,就不用使用setInterval()
//setInterval("invokeMethodInTopWindow()",100);
</script>
</body>
</html>
domainB中的other.html
新聞熱點
疑難解答