DIV CSS 佈局教程網

用 location.hash 打通跨域 iframe 自適應
編輯:關於JavaScript     

場景設定:

主頁面 a.html 屬於域 A(www.jb51.net),被 iframe 嵌入的 b.html 屬於域 B(www.baidu.com)。

想達到的效果:a.html 裡嵌入了 b.html,但 b.html 的寬高不可預知且會變化,所以 a.html 中的 iframe 需要自適應其內容尺寸。

問題本質:要控制 iframe 的寬高,就必須先讀到 b.html 的實際尺寸。可 A、B 不同域,瀏覽器出於安全考慮限制了跨域訪問,父頁面根本拿不到子頁面的高度和寬度。

解法:借一個同域代理頁

引入一個與 a.html 同屬域 A 的中間代理頁 c.html(www.jb51.net/c.html)。它負責讀取 location.hash 裡的 width 與 height,然後去設置同域下 a.html 中 iframe 的尺寸。而 b.html 這邊,則把自己的寬高寫進 c.html 的 hash 裡。

hash 之所以能承擔這個任務,是因為它隨 URL 傳遞但不會被發送到服務器,同時修改 iframe 的 hash 也不會觸發跨域限制——這正是整個方案的支點。

三段代碼

a.html 中通過 iframe 引入 b.html:


復制代碼 代碼如下:
<iframe id=”b_iframe” height=”0″ width=”0″ src=”https://www.baidu.com/b.html” frameborder=”no” border=”0px” marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes” ></iframe>

b.html 負責測量並寫入 hash:


復制代碼 代碼如下:
<script type=”text/javascript”>
var b_width = Math.max(document.documentElement.clientWidth,document.body.clientWidth);
var b_height = Math.max(document.documentElement.clientHeight,document.body.clientHeight);
var c_iframe = document.getElementById(”c_iframe”);
c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //https://www.jb51.net/c.html#width|height”
}
</script>

<!–js讀取b.html的寬和高,把讀取到的寬和高設置到和a.html在同一個域的中間代理頁面車c.html的src的hash裡面–>
<iframe id=”c_iframe” height=”0″ width=”0″ src=”https://www.jb51.net/c.html” style=”display:none” ></iframe>

c.html 解析 hash 並回寫尺寸:


復制代碼 代碼如下:
<script type=”text/javascript”>
var b_iframe = parent.parent.document.getElementById(”b_iframe”);
var hash_url = window.location.hash;
var hash_width = hash_url.split(”#”)[1].split(”|”)[0]+”px”;
var hash_height = hash_url.split(”#”)[1].split(”|”)[1]+”px”;
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
</script>

這樣一來,a.html 中的 iframe 就能自適應 b.html 的寬高了。

延伸思考

其他同類的 JS 跨域操作問題,也可以沿著這個思路去解——本質上都是「找一個雙方都能信任的中間人」。如果並非跨域訪問,那事情簡單得多,可以直接參考 iframe 自適應高度的多種方法小結。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved