萬盛學電腦網

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

iframe 跨域自適應高度:代理頁面巧妙繞過同源策略實戰

問題場景

domainA 頁面嵌入 domainB 頁面 (iframe),domainB 內容動態變化需自適應高度,同源策略阻斷父頁直接讀取子頁高度。

代理頁面架構 (三層嵌套)

domainA/index.html (父頁)
    └─ iframe → domainB/other.html (子頁)
                  └─ iframe → domainA/agent.html (代理頁, 隱藏, 同域父頁)

完整代碼實現

1. domainA/index.html (父頁)


<iframe name="domainB" src="https://domain-b.com/other.html" 
        width="80%" scrolling="no" frameborder="0"></iframe>

<script>
function resizeIframe(height) {
    document.getElementsByName('domainB')[0].height = height;
}
</script>

2. domainB/other.html (子頁)


<body onclick="proxy()">
<button onclick="toggleContent()">切換顯示</button>
<div id="dynamicContent" style="display:none">大量動態內容...</div>

<!-- 隱藏代理 iframe,指向 domainA -->
<iframe id="proxyFrame" src="https://domain-a.com/agent.html" 
        style="display:none" width="0" height="0"></iframe>

<script>
function proxy() {
    // 1. 計算實際高度
    var h = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight
    );
    
    // 2. 設置代理 iframe src 帶上高度參數
    // 加時間戳強制重載 (繞過瀏覽器緩存)
    var proxy = document.getElementById('proxyFrame');
    proxy.src = 'https://domain-a.com/agent.html#' + h + '&t=' + Date.now();
}

function toggleContent() {
    var div = document.getElementById('dynamicContent');
    div.style.display = div.style.display === 'none' ? 'block' : 'none';
    proxy(); // 內容變化後同步高度
}
</script>

3. domainA/agent.html (代理頁)


<script>
window.onload = function() {
    // 1. 解析 hash 參數
    var hash = location.hash; // #800&t=123456789
    if (hash.indexOf('#') === 0) {
        var height = hash.split('#')[1].split('&')[0]; // 取高度值
        
        // 2. 操作頂層父頁的 iframe (同域,無跨域限制)
        var topFrame = window.parent.parent.document.getElementsByName('domainB')[0];
        if (topFrame) {
            topFrame.height = height;
            // 或 topFrame.style.height = height + 'px';
        }
    }
};
</script>

核心原理圖解

子頁計算高度 
    → 修改代理頁 src (觸發代理頁重載) 
    → 代理頁 onload 解析 hash 
    → 代理頁操作父頁 iframe 高度 (同域允許)
    → 完成自適應

關鍵技術點

  • hash 傳值:URL hash 部分不發送到服務器,純客戶端傳值,跨域安全。
  • 時間戳防緩存:?t=Date.now() 確保每次代理頁都重新載入執行 onload。
  • 三層訪問鏈:window.parent.parent 從代理頁 → 子頁 → 父頁。
  • 同域前提:代理頁必須與父頁同域 (domainA),才能操作父頁 DOM。

現代標準替代方案:postMessage (強烈推薦)


// 子頁 (domain B)
function reportHeight() {
    var h = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    parent.postMessage({type: 'iframeResize', height: h}, 'https://domain-a.com');
}
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);

// 父頁 (domain A)
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://domain-b.com') return; // 安全驗證
    if (e.data.type === 'iframeResize') {
        document.getElementsByName('domainB')[0].style.height = e.data.height + 'px';
    }
});

方案對比

方案瀏覽器支援實時性實現複雜度安全性推薦
代理頁面 (hash)IE6+ 全支援需觸發重載高 (三頁面協作)中 (hash 可被竄改)僅極舊環境
postMessageIE8+ 全現代即時、事件驅動低 (兩頁面通信)高 (origin 驗證)⭐⭐⭐⭐⭐ 首選
document.domain 降級IE6+ (同主域)即時低中 (放寬同源)同主域場景

避坑指南

  1. 代理頁緩存:必須加隨機參數強制重載,否則 onload 不再觸發。
  2. 多層 iframe 索引:用 window.top 定位頂層,window.parent 定位直接父級,避免硬編碼層級。
  3. 動態內容監聽:子頁內容變化 (AJAX、用戶展開、圖片載入) 後必須主動調用上報。
  4. 性能:postMessage 異步非阻塞,代理頁重載有開銷,高頻場景優先 postMessage。
copyright © 萬盛學電腦網 all rights reserved