DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
跨域 iframe 高度自適應:用同域代理頁打通限制
編輯:HTML和Xhtml     

情境設定

主頁面 a.html 位於 A 網域(www.taobao.com),它以 iframe 嵌入 B 網域的 b.html(https://www.alimama.com/b.html)。由於 b.html 的寬高無法預知、而且會隨內容變化,我們希望 a.html 中的 iframe 能自動伸縮到正好包住 b.html。

問題本質

這是一個 JavaScript 的跨域限制問題。要調整 a.html 裡 iframe 的寬高,就必須先讀到 b.html 的實際尺寸;但 A、B 屬於不同網域,瀏覽器基於安全性考量會阻擋跨域存取,於是尺寸讀不到。

解法:插入一個同域中間代理頁

思路是在 A 網域下放一個代理頁 c.html(www.taobao.com/c.html)。它與 a.html 同域,因此可以合法地改寫 a.html 中的 iframe。流程是:

  1. b.html 量出自己的寬高,寫進 c.html 的 location.hash。
  2. c.html 讀取 hash 中的數值。
  3. 因為 c.html 與 a.html 同域,它能直接取得 a.html 裡那個 iframe 並設定寬高。

程式碼

a.html:先用 iframe 引入 b.html

<iframe id="b_iframe" height="0" width="0" src="https://www.alimama.com/b.html"
        frameborder="no" border="0px" marginwidth="0" marginheight="0"
        scrolling="no" allowtransparency="yes"></iframe>

b.html:量出自己的尺寸,塞進 c.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");
  // 結果形如 https://www.taobao.com/c.html#width|height
  c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;
</script>
<!-- 這個隱藏的 iframe 指向同域的代理頁 c.html -->
<iframe id="c_iframe" height="0" width="0" src="https://www.taobao.com/c.html"
        style="display:none"></iframe>

c.html:解析 hash,回頭調整 a.html 中的 iframe

<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 跨域操作」問題,也都能沿著這個「同域代理頁 + hash 傳值」的思路解決。

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