iframe 高度自適應是嵌入第三方內容、微前端子應用、舊系統整合的常見痛點。核心難點在於父頁面無法直接讀取跨域 iframe 內容高度 (同源策略限制)。本文提供從傳統 Hack 到現代標準 API 的完整演進方案。
iframe.contentDocument.body.scrollHeight傳統同域 → document.body.scrollHeight 定時輪詢 傳統跨域 → URL Hash 傳遞 / window.name 跨域 / postMessage (IE8+) 現代標準 → ResizeObserver (父頁觀察 iframe) / postMessage 雙向通訊 未來趨勢 → CSS container queries / iframe 自適應原生屬性 (提案中)
<iframe id="myFrame" src="same-origin-page.html" onload="resizeIframe(this)"></iframe>
<script>
function resizeIframe(iframe) {
try {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
// 或 document.documentElement.scrollHeight 取較大值
} catch (e) {
console.error('跨域或文檔未就緒:', e);
}
}
// 內容動態變化時需手動觸發或設定 interval
</script>
<script>
function sendHeight() {
const height = document.body.scrollHeight;
// 僅發送給信任的父域,生產環境請指定具體 origin
window.parent.postMessage({ type: 'iframeResize', height }, 'https://parent.example.com');
}
// 內容載入後、DOM 變動後、圖片載入後、視窗 resize 時觸發
window.addEventListener('load', sendHeight);
window.addEventListener('resize', sendHeight);
// MutationObserver 監聽 DOM 變化
new MutationObserver(sendHeight).observe(document.body, { childList: true, subtree: true });
// 圖片載入觸發
document.querySelectorAll('img').forEach(img => img.addEventListener('load', sendHeight));
</script>
<iframe id="childFrame" src="https://child.example.com/page.html" style="width:100%; border:none;"></iframe>
<script>
const iframe = document.getElementById('childFrame');
const ALLOWED_ORIGIN = 'https://child.example.com';
window.addEventListener('message', (event) => {
// 安全驗證:來源檢查 + 資料結構驗證
if (event.origin !== ALLOWED_ORIGIN) return;
if (!event.data || event.data.type !== 'iframeResize') return;
const height = Number(event.data.height);
if (!isNaN(height) && height > 0) {
iframe.style.height = height + 'px';
}
});
</script>
前提:iframe 與父頁**同域**,或 iframe 設定 allow="resize-observer" (實驗性)。適用於同域微前端子應用。
<iframe id="appFrame" src="/micro-frontend/app.html" style="width:100%; border:none; min-height:200px;"></iframe>
<script>
const iframe = document.getElementById('appFrame');
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
if (entry.target === iframe) {
// entry.contentRect.height 為 iframe 實際渲染高度
// 注意:需 iframe 內容不設定固定高度、且無 overflow:hidden 截斷
iframe.style.height = entry.contentRect.height + 'px';
}
}
});
observer.observe(iframe);
</script>
優勢:無需子頁插入代碼、效能極佳 (瀏覽器原生)、自動處理動態內容變化、無輪詢開銷。
若不需完全自適應,只想避免雙重捲軸:
.iframe-wrapper {
position: relative;
width: 100%;
height: 600px; /* 最大高度 */
overflow: hidden;
}
.iframe-wrapper iframe {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
border: none;
/* 內容超出時在 iframe 內部捲動,外層無捲軸 */
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 高度為 0 或異常小 | iframe 內容未載入完成、CSS float/absolute 導致父級高度塌陷 | onload 觸發、內容容器 clearfix、body { margin:0 } |
| 高度忽大忽小、跳動 | 圖片載入、字體載入、動畫、動態插入內容觸發多次 resize | 防抖動、imagesLoaded 庫、MutationObserver 批次處理 |
| 跨域 postMessage 不生效 | origin 不匹配、HTTP/HTTPS 不一致、端口不同、子頁未發送 | 嚴格核對 origin、子頁確實調用 postMessage、開發環境配置 hosts 對應 |
| ResizeObserver 不觸發 | iframe 為跨域、iframe 設定固定高度、內容區 overflow:hidden | 同域才生效、移除 iframe 固定高度、內容區避免 overflow:hidden |
| 白邊/縫隙 | iframe inline 元素基線對齊、border、margin | display:block; border:none; margin:0; padding:0; vertical-align:top; |
event.origin 為白名單域名postMessage 指定 targetOrigin 而非 '*'Content-Security-Policy: frame-ancestors 'self' https://parent.example.com;sandbox="allow-scripts allow-same-origin allow-forms" 最小權限overflow:auto 或 CSS 偽自適應