主頁面 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。流程是:
location.hash。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 傳值」的思路解決。