讓 iframe 的高度自動貼合內容,看起來只是小事,一旦牽涉跨域就會變成經典難題。以下用一個具體情境說明成因與解法。
主頁面 a.html 位於 A 網域(www.jb51.net),被嵌入的 b.html 位於 B 網域(https://www.jb51.cn/b.html)。我們希望 a.html 中的 iframe 能自動符合 b.html 的寬高,因為 b.html 的內容尺寸無法預知,而且會動態變化。
這其實是 JavaScript 的跨域限制問題。要調整 a.html 中 iframe 的寬高,就必須先讀取 b.html 的尺寸;但 A、B 不屬於同一個網域,瀏覽器基於安全性考量會阻擋跨域存取,於是讀不到 b.html 的寬與高。
做法是引入一個與 a.html 同屬 A 網域的中間代理頁 c.html(例如 www.jb51.net/c.html)。它負責讀取 location.hash 裡的寬高數值,再回頭設定同域下 a.html 中 iframe 的尺寸。hash 是唯一能跨域傳值又不觸發請求的通道,這正是整個方案的關鍵。
<iframe id="b_iframe" height="0" width="0" src="https://www.jb51.cn/b.html"
frameborder="no" border="0px" marginwidth="0" marginheight="0"
scrolling="no" allowtransparency="yes"></iframe>
先量出自己的尺寸,再把數值塞進同域代理頁 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");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;
// 結果即 https://www.jb51.net/c.html#width|height
</script>
<iframe id="c_iframe" height="0" width="0" src="https://www.jb51.net/c.html"
style="display:none"></iframe>
代理頁解析 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 的寬高。
這個「同域代理 + hash 傳值」的思路,同樣可以用來解決其他類型的跨域 JavaScript 操作問題。若內容高度會持續變化,只要讓 b.html 在 resize 時重複更新 hash 即可。