所謂 iframe 自適應,就是基於版面與互動考量,隱藏 iframe 的邊框與捲軸,讓使用者看不出它是個 iframe。若 iframe 永遠載入同一個固定高度的頁面,直接把高度寫死即可;但只要頁面會切換、或內部有 DOM 動態操作,就必須讓程式同步 iframe 與被內嵌頁面的實際高度。
iframe 是網頁的一部分,其尺寸仍受網頁本身限制。若 iframe 的高度沒有明確設定,它就會使用預設高度(通常約 150px)。而 height="100%" 是相對於父容器,並非內容高度,所以內容超出時還是會出現捲軸。基本上,傳統解法都是「加捲軸」來因應溢出,這並不是真正的自適應。
$("#main").load(function () {
var mainheight = $(this).contents().find("body").height() + 30;
$(this).height(mainheight);
});
加 30px 是為了留餘裕,避免邊界誤差造成殘留捲軸。重點:這段程式碼必須放在 iframe 元素的後面,放在 <head> 裡實測無效,因為那時 iframe 節點還不存在。
// 這段放在 test.html(被內嵌的子頁面)裡
$(window.parent.document).find("#main").load(function () {
var main = $(window.parent.document).find("#main");
var thisheight = $(document).height() + 30;
main.height(thisheight);
});
早期實作時常遇到無效的狀況,原因是跨域權限不足;把 window.document.domain 設為相同的父網域後即可正常運作。
由於同源策略,父頁面的 JavaScript 無法讀取跨域 iframe 的高度。解法是引入一個「代理頁」。
假設 www.a.com/a.html 要內嵌 www.b.com/c.html,我們在 a 網域下準備一個 agent.html 作為中繼。
a.html:
<iframe src="https://www.b.com/c.html" id="Iframe"
frameborder="0" scrolling="no" style="border:0px;"></iframe>
c.html:把尺寸寫進另一個 iframe 的 src 上
<iframe id="c_iframe" height="0" width="0"
src="https://www.a.com/agent.html" style="display:none"></iframe>
<script type="text/javascript">
(function autoHeight() {
var b_width = Math.max(document.body.scrollWidth, document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight, document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;
})();
</script>
agent.html:讀出 hash 並回寫最上層 iframe 的高度
<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("Iframe");
var hash_url = window.location.hash;
if (hash_url.indexOf("#") >= 0) {
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>
因為 agent.html 屬於 a 網域,操作 a.html 時不受同源限制,尺寸就這樣被傳了過去。
代理頁的技巧能用,但步驟繁瑣。HTML5 之後,跨域溝通有了標準答案:
// 子頁面(b.com):把高度告訴父頁
function notifyHeight() {
var h = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
parent.postMessage({ type: 'resize', height: h }, 'https://www.a.com');
}
window.addEventListener('load', notifyHeight);
new ResizeObserver(notifyHeight).observe(document.body);
// 父頁面(a.com):接收並調整
window.addEventListener('message', function (e) {
if (e.origin !== 'https://www.b.com') return; // 務必驗證來源!
if (e.data && e.data.type === 'resize') {
document.getElementById('Iframe').style.height = e.data.height + 'px';
}
});
兩個關鍵點:ResizeObserver 取代固定排程的輪詢,內容一變就通知;e.origin 驗證不可省略,否則任何網站都能對你的頁面發訊息,等於開了一個後門。這也是為什麼代理頁那種「把數值塞進 hash」的土法煉鋼,在今天應該被 postMessage 取代——它天生有來源標識,安全性高得多。