萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

iframe 自適應高度完整解決方案:跨域、同域、現代 ResizeObserver 最佳實踐

iframe 高度自適應是嵌入第三方內容、微前端子應用、舊系統整合的常見痛點。核心難點在於父頁面無法直接讀取跨域 iframe 內容高度 (同源策略限制)。本文提供從傳統 Hack 到現代標準 API 的完整演進方案。

問題本質

  • iframe 預設高度固定 (預設 150px),內容變化不會自動撐開
  • 同域:父頁可直接讀取 iframe.contentDocument.body.scrollHeight
  • 跨域:瀏覽器阻擋跨域 DOM 存取,需通訊機制傳遞高度資訊

方案演進路線圖

傳統同域 → 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>

方案二:跨域 —— postMessage 雙向通訊 (IE8+、全現代瀏覽器)

子頁面 (iframe 內) 發送高度

<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>

方案三:現代最佳 —— ResizeObserver 觀察 iframe (父頁單向監控,無需子頁配合)

前提: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>

優勢:無需子頁插入代碼、效能極佳 (瀏覽器原生)、自動處理動態內容變化、無輪詢開銷。

方案四:CSS 偽自適應 (固定寬度、內容可捲動)

若不需完全自適應,只想避免雙重捲軸:

.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、margindisplay:block; border:none; margin:0; padding:0; vertical-align:top;

安全性檢查清單 (跨域場景)

  • [ ] 父頁驗證 event.origin 為白名單域名
  • [ ] 子頁 postMessage 指定 targetOrigin 而非 '*'
  • [ ] 子頁設置 Content-Security-Policy: frame-ancestors 'self' https://parent.example.com;
  • [ ] 父頁 iframe 加上 sandbox="allow-scripts allow-same-origin allow-forms" 最小權限
  • [ ] 敏感操作 (支付、登入) 禁用 iframe 嵌入,改用重導向

總結建議

決策指南:
✅ 同域微前端/子應用 → ResizeObserver (零侵入、高效能、自動響應)
✅ 跨域第三方嵌入 → postMessage (標準、安全、需雙方配合)
✅ 簡單靜態內容嵌入 → 固定高度 + overflow:auto 或 CSS 偽自適應
❌ 避免:定時輪詢、URL Hash Hack、document.domain 降級 (已棄用/不安全)

參考資源

copyright © 萬盛學電腦網 all rights reserved