萬盛學電腦網

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

JavaScript 實作 iframe 高度自動適應(跨域相容方案)

核心挑戰

iframe 高度自適應受限於同源政策:父頁面無法直接讀取跨域 iframe 的 contentDocument.body.scrollHeight。本文提供三種方案,依專案環境選擇。

方案一:同源環境——直接讀取 DOM(最簡單)

<script>
function resizeIframe(iframeId) {
    const iframe = document.getElementById(iframeId);
    if (!iframe) return;

    iframe.onload = function() {
        try {
            // 同源才能存取
            const doc = iframe.contentDocument || iframe.contentWindow.document;
            const height = Math.max(
                doc.body.scrollHeight,
                doc.body.offsetHeight,
                doc.documentElement.scrollHeight,
                doc.documentElement.offsetHeight
            );
            iframe.style.height = height + 'px';
        } catch (e) {
            console.warn('跨域無法讀取高度,請改用 postMessage 方案', e);
        }
    };
}

// 使用
resizeIframe('myIframe');
</script>

方案二:跨域環境——postMessage 雙向通訊(標準做法)

父頁面

<iframe id="childFrame" src="https://other-domain.com/child.html" style="width:100%; border:none;"></iframe>

<script>
window.addEventListener('message', e => {
    // 安全性:驗證來源
    if (e.origin !== 'https://other-domain.com') return;
    if (e.data && e.data.type === 'iframeResize') {
        document.getElementById('childFrame').style.height = e.data.height + 'px';
    }
});
</script>

子頁面(需能修改)

<script>
function reportHeight() {
    const height = Math.max(
        document.body.scrollHeight,
        document.body.offsetHeight,
        document.documentElement.scrollHeight,
        document.documentElement.offsetHeight
    );
    // 發送給父頁面,* 表允許所有源,生產環境請指定具體父域名
    window.parent.postMessage({type: 'iframeResize', height}, '*');
}

// 頁面載入、DOM 變動、視窗調整時回報
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// 若有動態內容(AJAX、Vue/React 渲染),在渲染完成後手動呼叫 reportHeight()
</script>

方案三:無法修改子頁面——ResizeObserver + 同源 Proxy(進階)

若子頁面不可控且跨域,唯一辦法是在同源建立一個 Proxy 頁面去載入目標網站,再由 Proxy 向父頁面傳高度。架構較複雜,僅列概念:

父頁面 → iframe[Proxy頁面] → iframe[目標跨域頁面]
                ↑                   ↑
           接收 postMessage    同源可直接讀高度

原文舊版碼重構(修正舊寫法問題)

// 原始碼問題:變數宣告未用 var/let、迴圈變數汙染全域、Opera 判斷過時
// 重構後:
const iframeIds = ['top1']; // 可擴充多個
const hideUnsupported = 'yes';

function dynIframeSize() {
    iframeIds.forEach(id => {
        const iframe = document.getElementById(id);
        if (!iframe) return;

        // 同源嘗試
        try {
            const doc = iframe.contentDocument || iframe.contentWindow.document;
            const height = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
            iframe.style.height = height + 'px';
        } catch (e) {
            // 跨域失敗時的 fallback
            if (hideUnsupported === 'no') iframe.style.display = 'block';
        }
    });
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', dynIframeSize);
} else {
    dynIframeSize();
}

// 視窗大小改變時重新計算
window.addEventListener('resize', dynIframeSize);

方案選擇決策樹

  1. 同源? → 方案一
  2. 跨域但可控制子頁面? → 方案二
  3. 跨域且不可控制子頁面? → 方案三或放棄自適應(固定高度 + 滾動條)

注意事項

  • 子頁面若有 margin、padding、box-sizing 影響高度,建議在子頁面 body { margin: 0; }。
  • 動態內容(AJAX、圖片載入、虛擬清單)需在內容穩定後主動觸發 reportHeight()。
  • 父頁面 CSS 設定 iframe { display: block; } 避免底部縫隙。
copyright © 萬盛學電腦網 all rights reserved