萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

跨瀏覽器 iframe 自適應高度完美解決方案 (原生 JS、onload、postMessage、MutationObserver)

核心難點

  • 同源:父頁可直接讀取 iframe.contentDocument.body.scrollHeight。
  • 跨源:受同源策略限制,**無法直接存取** iframe 內容高度,必須用 postMessage 通訊。
  • 動態內容:iframe 內容高度可能因 AJAX 載入、圖片載入、使用者互動而變化,需持續監聽。

方案一:同源 - 簡單 onload 版 (適用靜態頁面)

function iframeAutoFit(iframe) {
    // 延遲執行確保內容渲染完成
    setTimeout(function() {
        if (!iframe) return;
        try {
            var doc = iframe.contentDocument || iframe.contentWindow.document;
            var height = doc.body.scrollHeight; // 或 doc.documentElement.scrollHeight
            iframe.style.height = height + 'px';
        } catch (e) {
            console.warn('iframe 高度獲取失敗 (跨域?):', e);
        }
    }, 100);
}

// 使用
<iframe id="myIframe" src="same-origin-page.html" onload="iframeAutoFit(this)" 
         frameborder="0" scrolling="no" style="width:100%; border:none;"></iframe>

方案二:同源 - 強健版 (處理動態內容、圖片載入)

function setupIframeAutoResize(iframe) {
    if (!iframe) return;
    
    var resizeTimer;
    
    function resize() {
        try {
            var doc = iframe.contentDocument || iframe.contentWindow.document;
            var height = Math.max(
                doc.body.scrollHeight, 
                doc.documentElement.scrollHeight,
                doc.body.offsetHeight,
                doc.documentElement.offsetHeight
            );
            iframe.style.height = height + 'px';
        } catch (e) { /* 跨域靜默失敗 */ }
    }
    
    // 初始載入
    iframe.onload = function() {
        resize();
        // 監聽 iframe 內圖片載入完成觸發 resize
        var doc = iframe.contentDocument || iframe.contentWindow.document;
        var images = doc.getElementsByTagName('img');
        for (var i = 0; i < images.length; i++) {
            if (!images[i].complete) {
                images[i].onload = resize;
            }
        }
        // 監聽 DOM 變動 (AJAX 新增內容等)
        if (window.MutationObserver) {
            var observer = new MutationObserver(function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(resize, 50); // 防抖
            });
            observer.observe(doc.body, { childList: true, subtree: true, attributes: true });
            // 儲存 observer 以便清理
            iframe._resizeObserver = observer;
        }
    };
    
    // 父視窗 resize 也觸發 (應對視窗寬度變化導致內容重排)
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(resize, 100);
    });
}

// 清理
function destroyIframeAutoResize(iframe) {
    if (iframe._resizeObserver) iframe._resizeObserver.disconnect();
    iframe.onload = null;
}

方案三:跨源 - postMessage 通訊 (標準、安全、雙向)

父頁面

<iframe id="crossIframe" src="https://other-domain.com/child.html" 
        frameborder="0" scrolling="no" style="width:100%; border:none; min-height:200px;"></iframe>

<script>
var iframe = document.getElementById('crossIframe');

// 監聽子頁面訊息
window.addEventListener('message', function(e) {
    // 安全性:驗證來源
    if (e.origin !== 'https://other-domain.com') return;
    
    // 期待格式: { type: 'iframeResize', height: 1234 }
    if (e.data && e.data.type === 'iframeResize' && typeof e.data.height === 'number') {
        iframe.style.height = e.data.height + 'px';
    }
});

// 可選:父頁面主動請求高度 (子頁面需監聽此訊息)
function requestIframeHeight() {
    iframe.contentWindow.postMessage({ type: 'requestHeight' }, 'https://other-domain.com');
}

// 定期請求 (備用)
setInterval(requestIframeHeight, 5000);
</script>

子頁面 (https://other-domain.com/child.html)

<script>
function sendHeight() {
    var height = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight,
        document.body.offsetHeight,
        document.documentElement.offsetHeight
    );
    // 發送給父頁面
    window.parent.postMessage({ type: 'iframeResize', height: height }, '*'); // * 為示範,生產環境請指定具體父域名
}

// 頁面載入完成
window.addEventListener('load', sendHeight);

// 監聽 DOM 變動
if (window.MutationObserver) {
    new MutationObserver(function() { sendHeight(); })
        .observe(document.body, { childList: true, subtree: true, attributes: true });
}

// 監聽圖片載入
document.querySelectorAll('img').forEach(function(img) {
    if (!img.complete) img.onload = sendHeight;
});

// 回應父頁面主動請求
window.addEventListener('message', function(e) {
    if (e.data && e.data.type === 'requestHeight') sendHeight();
});
</script>

方案四:成熟庫 - iframe-resizer (生產環境首選)

GitHub: davidjbradshaw/iframe-resizer

<!-- 父頁面 -->
<script src="iframeResizer.min.js"></script>
<iframe src="child.html" width="100%" scrolling="no"></iframe>
<script>
    iFrameResize({ log: false, checkOrigin: false }, '#myIframe');
</script>

<!-- 子頁面 -->
<script src="iframeResizer.contentWindow.min.js"></script>
<!-- 無需其他代碼,自動發送高度 -->

特色:支援跨域、多 iframe、巢狀 iframe、滾動同步、關閉回調、ID 衝突處理、極小體積 (4KB gzip)。

CSS 輔助技巧

iframe {
    display: block;        /* 消除底部間隙 */
    width: 100%;           /* 自適應寬度 */
    min-height: 200px;     *//* 載入前佔位,防止版面跳動 */
    border: none;
    background: #fafafa;   /* 載入中背景 */
}

/* 父頁面容器 */
.iframe-wrapper {
    position: relative;
    overflow: hidden;      /* 防止內容溢出 */
}

總結選型指南

場景推薦方案關鍵點
同源、靜態內容方案一 onload簡單、零依賴
同源、動態內容 (AJAX/圖片/互動)方案二 MutationObserver即時響應、無輪詢
跨源 (不同域名/協定/埠)方案三 postMessage標準、安全、雙向
生產環境、複雜需求、求穩方案四 iframe-resizer成熟、功能全、維護性佳

避坑提醒

  • scrolling="no" 避免雙滾動條,但需確保高度精確。
  • 子頁面 body { margin: 0; } 避免邊距干擾高度計算。
  • 跨域時 postMessage **務必驗證 e.origin**,防止 XSS。
  • 避免 document.domain 降級 (已棄用、不安全、Chrome 移除中)。
copyright © 萬盛學電腦網 all rights reserved