內嵌 <iframe> 時最惱人的問題是高度:設定了固定值,內容少了會留白、內容多了會出現雙重捲軸。理想狀況是讓 iframe 高度自動貼合內部內容。本文示範一個手動判斷 User-Agent 分支處理的版本,並說明為何現在不該這樣寫。
function SetIFrameHeight(down) {
var Sys = {};
var ua = navigator.userAgent.toLowerCase();
var s;
// 逐一比對 User-Agent,判斷是哪個瀏覽器及其版本
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
var pTar = null;
if (document.getElementById) {
pTar = document.getElementById(down);
} else {
eval('pTar=' + down + ';'); // 極舊瀏覽器的降級
}
pTar.style.display = "block";
if (Sys.ie) {
if (Sys.ie == '9.0') {
pTar.height = pTar.contentWindow.document.body.offsetHeight + 15 + "px";
pTar.width = pTar.contentWindow.document.body.scrollWidth + "px";
} else if (Sys.ie == '8.0') {
pTar.height = pTar.Document.body.offsetHeight + 15 + "px";
pTar.width = pTar.Document.body.scrollWidth + "px";
} else {
pTar.height = pTar.Document.body.scrollHeight + 25 + "px";
pTar.width = pTar.Document.body.scrollWidth + "px";
}
}
if (Sys.firefox) {
pTar.height = pTar.contentDocument.body.offsetHeight + 15 + "px";
pTar.width = pTar.contentDocument.body.scrollWidth + "px";
}
if (Sys.chrome) {
pTar.height = pTar.contentDocument.body.offsetHeight;
pTar.width = pTar.contentDocument.body.scrollWidth;
}
if (Sys.opera) {
pTar.height = pTar.contentDocument.body.offsetHeight;
pTar.width = pTar.contentDocument.body.scrollWidth;
}
if (Sys.safari) {
if (pTar.contentDocument.body.offsetHeight <= '186') {
pTar.height = pTar.contentDocument.body.offsetHeight + 10;
} else {
pTar.height = pTar.contentDocument.body.offsetHeight;
}
pTar.width = pTar.contentDocument.body.scrollWidth;
}
}
核心是三種不同的 DOM 存取路徑:
contentWindow.document —— IE9 使用Document(大寫 D)—— 舊 IE 的非標準屬性contentDocument —— 標準寫法,Firefox、Chrome、Safari、Opera 皆適用至於那些 + 15、+ 25、+ 10 與 Safari 的 186 門檻,都是實測出來的「魔術數字」,用來補償各瀏覽器的邊界與捲軸計算差異。這正是 User-Agent 分支法最大的問題:數字綁死在特定版本上,任何瀏覽器更新都可能失效。
contentDocument 會因同源政策而拋出安全性例外。eval 不必要:那個降級分支毫無價值,且會阻礙 CSP 的啟用。
function fitIframe(iframe) {
try {
var doc = iframe.contentDocument || iframe.contentWindow.document;
var body = doc.body;
var html = doc.documentElement;
// 取最大值,避免 body 與 html 高度不一致時被裁切
var height = Math.max(
body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight
);
iframe.style.height = height + "px";
} catch (e) {
console.warn("無法調整高度(可能為跨來源)", e);
}
}
// 同源時,由 iframe 內部主動通知父頁最可靠
window.addEventListener("load", function () { fitIframe(myFrame); });
父頁面:
window.addEventListener("message", function (e) {
// 務必驗證來源,否則任何網站都能操控你的頁面
if (e.origin !== "https://trusted.example.com") return;
if (e.data && e.data.type === "iframe-height") {
document.getElementById("myFrame").style.height = e.data.height + "px";
}
});
iframe 內部(放在被嵌入的頁面中):
function notifyHeight() {
var h = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight
);
parent.postMessage({ type: "iframe-height", height: h }, "https://parent.example.com");
}
new ResizeObserver(notifyHeight).observe(document.body);
window.addEventListener("load", notifyHeight);
ResizeObserver 會在內容尺寸改變時自動觸發,解決了原寫法「只測一次」的根本問題。而 postMessage 的 origin 驗證是必要的安全措施,缺少它等於讓任何網站都能在你的頁面上注入任意高度甚至觸發其他訊息。
如果 iframe 的內容其實也是你自己的,那麼 iframe 帶來的都是純成本:多一次 HTTP 請求、樣式無法共用、SEO 不友善、鍵盤焦點與無障礙樹isolation 造成困擾、行動裝置上高度計算尤其麻煩。
直接用伺服器端組件載入內容片段(AJAX 抓 HTML 後插入),或用前端框架的元件系統,通常會得到更好的結果。iframe 真正值得使用的場合是:嵌入第三方內容、需要嚴格的樣式與腳本隔離、或需要沙箱化不受信任的內容。