萬盛學電腦網

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

跨域 iframe 高度自適應完整方案:代理頁面繞過同源策略

跨域 iframe 高度自適應是經典難題:受同源策略限制,父頁無法讀取子頁 document.body.scrollHeight。業界標準方案是「代理頁面 + hash 傳遞 + 同源訪問」。本文提供完整三頁面架構代碼、邊界處理、現代替代方案與安全加固。

一、架構圖解

┌─────────────────────────────────────────────────────────────┐
│ domainA: parent.html (主頁)                                    │
│  └─ iframe[name="child"] src="https://domainB/child.html"    │
│                                                               │
│  ┌─────────────────────────────────────────────────────┐     │
│  │ domainB: child.html (業務頁)                            │
│  │  └─ iframe[name="proxy"] src="https://domainA/proxy.html#height" │
│  │                                                     │     │
│  └─────────────────────────────────────────────────────┘     │
└─────────────────────────────────────────────────────────────┘

數據流向:
child.html 計算高度 → 設置 proxy iframe.src = "proxy.html#" + height
           ↓
proxy.html (同域 parent) 讀取 location.hash → 調用 parent.parent.resize(height)
           ↓
parent.html 執行 resize() → 設置 child iframe 高度

二、三頁面完整代碼 (生產就緒版)

1. parent.html (domainA 主頁)


<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>主頁 - 跨域 iframe 自適應</title>
  <style>
    .child-frame { width: 100%; border: none; min-height: 300px; }
  </style>
</head>
<body>
  <h1>主頁內容</h1>
  <iframe 
    name="childFrame" 
    class="child-frame" 
    src="https://domainB.example.com/child.html"
    scrolling="no"
    frameborder="0"
  ></iframe>

  <script>
  // 暴露給代理頁調用的全局函數
  window.resizeChildIframe = function(height) {
    const iframe = document.querySelector('iframe[name="childFrame"]');
    if (iframe) {
      // 安全限制:高度範圍
      const h = Math.max(200, Math.min(parseInt(height) || 200, 10000));
      iframe.style.height = h + 'px';
      console.log('[Parent] iframe 高度設置為:', h);
    }
  };
  
  // 可選:監聽子頁 postMessage 作為備用方案
  window.addEventListener('message', e => {
    if (e.origin !== 'https://domainB.example.com') return;
    if (e.data?.type === 'resize' && typeof e.data.height === 'number') {
      window.resizeChildIframe(e.data.height);
    }
  });
  </script>
</body>
</html>

2. child.html (domainB 業務頁)


<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>業務頁 - 域 B</title>
  <style>
    body { margin: 0; padding: 20px; font-family: sans-serif; }
    .toggle-btn { margin-bottom: 20px; padding: 8px 16px; cursor: pointer; }
    .content { transition: height 0.3s ease; }
  </style>
</head>
<body>
  <button class="toggle-btn" id="toggleBtn">切換內容高度</button>
  <div class="content" id="content">
    <p>這是跨域 iframe 內容。點擊按鈕切換高度測試自適應。</p>
    <div id="extra" style="display:none;">
      <p>額外內容區塊 1</p><p>額外內容區塊 2</p><p>額外內容區塊 3</p>
      <p>額外內容區塊 4</p><p>額外內容區塊 5</p>
    </div>
  </div>

  <!-- 代理 iframe:隱藏、同域 A -->
  <iframe 
    name="proxyFrame" 
    id="proxyFrame" 
    src="https://domainA.example.com/proxy.html" 
    style="display:none;" 
  ></iframe>

  <script>
  const proxyUrl = 'https://domainA.example.com/proxy.html';
  const proxyFrame = document.getElementById('proxyFrame');
  const content = document.getElementById('content');
  const extra = document.getElementById('extra');
  let expanded = false;

  // 計算並發送高度
  function notifyHeight() {
    // 關鍵:獲取文檔完整高度
    const height = Math.max(
      document.body.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.clientHeight,
      document.documentElement.scrollHeight,
      document.documentElement.offsetHeight
    );
    
    // 方案 A:hash 傳遞 (傳統、無需 postMessage 權限)
    // 利用 src 變化觸發 proxy.html 重新加載執行腳本
    proxyFrame.src = proxyUrl + '#' + height;
    
    // 方案 B:postMessage (現代、推薦,需 proxy.html 監聽 message)
    // proxyFrame.contentWindow.postMessage({type: 'resize', height}, 'https://domainA.example.com');
  }

  // 內容變化時通知
  document.getElementById('toggleBtn').addEventListener('click', () => {
    expanded = !expanded;
    extra.style.display = expanded ? 'block' : 'none';
    // 異步確保佈局完成
    requestAnimationFrame(() => notifyHeight());
  });

  // 初始化通知
  notifyHeight();
  
  // 監聽內部圖片加載/字體加載導致的高度變化
  new ResizeObserver(notifyHeight).observe(document.body);
  </script>
</body>
</html>

3. proxy.html (domainA 代理頁,與 parent 同域)


<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>代理頁</title>
</head>
<body>
  <script>
  // 核心邏輯:讀取 hash → 調用父頁面的 resize 函數
  (function() {
    // 從 hash 獲取高度 (格式: #1234)
    const hash = window.location.hash.slice(1);
    const height = parseInt(hash, 10);
    
    if (!isNaN(height) && height > 0) {
      try {
        // 穿透兩層 iframe: parent(代理) → parent(主頁)
        window.parent.parent.resizeChildIframe(height);
        console.log('[Proxy] 已通知主頁調整高度:', height);
      } catch (e) {
        console.error('[Proxy] 調用失敗 (跨域?):', e);
        // 兜底:postMessage 給主頁
        window.parent.parent.postMessage({type: 'resize', height}, '*');
      }
    }
  })();
  </script>
</body>
</html>

三、關鍵技術點深度解析

1. 為什麼用 hash 傳遞而非 postMessage?

  • hash 方案:修改 iframe.src 觸發代理頁重新加載,代理頁腳本執行時自動擁有訪問 parent.parent (主頁) 的權限,因為**代理頁與主頁同域**。無需雙方協作部署 postMessage 監聽器。
  • postMessage 方案:現代標準,雙向通信,需雙方部署監聽代碼。推薦雙方案並存:hash 為主,postMessage 為備用。

2. 避免 setInterval 輪詢的技巧

原文利用 proxyFrame.src = proxyUrl + '#' + height 觸發代理頁**重新加載**,每次高度變化即一次加載,天然事件驅動,無需定時器。注意:需確保代理頁無緩存或添加時間戳參數 ?t=Date.now()。

3. 高度計算最佳實踐


function getDocumentHeight() {
    const body = document.body;
    const html = document.documentElement;
    return Math.max(
        body.scrollHeight, body.offsetHeight,
        html.clientHeight, html.scrollHeight, html.offsetHeight
    );
}

// 現代:ResizeObserver 自動監聽
new ResizeObserver(entries => {
    for (const entry of entries) {
        if (entry.target === document.body) notifyHeight();
    }
}).observe(document.body);

四、現代替代方案對比

方案原理優點缺點適用場景
代理頁 + hashsrc 觸發重載 + 同域訪問無需雙方協作部署、兼容極舊瀏覽器代理頁重載開銷、URL 歷史污染舊系統、無法修改主頁代碼
postMessageCross-document messaging標準、雙向、無重載、性能優需雙方部署代碼、IE8- 不支持現代項目、可控雙方代碼
document.domain 降級設置相同 document.domain同主域下直接訪問僅限同主域、瀏覽器正棄用、安全風險同主域子域名場景
CSS 單位 vh/vw視口單位佈局無 JS、極簡無法適配動態內容高度固定比例佈局

五、安全加固清單

  • 域名白名單:proxy.html 僅接受特定 domainB 的請求 (檢查 document.referrer 或約定密鑰)
  • 高度範圍限制:Math.max(200, Math.min(height, 10000)) 防止惡意撐大/縮小
  • CSP 政策:主頁設置 frame-ancestors 限制可嵌入域
  • X-Frame-Options:子頁設置 SAMEORIGIN 或 ALLOW-FROM (舊)
  • 移除調試日誌:生產環境關閉 console.log

六、React/Vue 組件化封裝

Vue 3 組件示例


<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
    src: String,
    allowedDomains: { type: Array, default: () => [] }
});

const iframeRef = ref();
let resizeHandler = (e: MessageEvent) => {
    if (!props.allowedDomains.includes(e.origin)) return;
    if (e.data?.type === 'resize') {
        iframeRef.value.style.height = Math.max(200, e.data.height) + 'px';
    }
};

onMounted(() => {
    window.addEventListener('message', resizeHandler);
});
onUnmounted(() => window.removeEventListener('message', resizeHandler));
</script>

<template>
  <iframe 
    ref="iframeRef" 
    :src="src" 
    class="cross-domain-iframe" 
    scrolling="no" 
    frameborder="0"
    @load="() => { /* 可選:加載完成邏輯 */ }"
  ></iframe>
</template>

七、總結

  1. 跨域 iframe 高度自適應核心矛盾:**需讀取子頁高度** vs **同源策略禁止跨域訪問**
  2. 經典解法:**同域代理頁 + hash 傳遞 + 父頁暴露 resize 函數**
  3. 現代首選:**postMessage 雙向通信**,代碼更簡潔、性能更優、無重載
  4. 工程化:封裝為通用組件,內建 ResizeObserver、安全白名單、高度範圍限制
  5. 調試技巧:Console 過濾 [Parent] [Child] [Proxy] 前綴,清晰追蹤調用鏈

掌握這套方案,無論是嵌入第三方報表、支付頁面、還是微前端子應用,iframe 高度自適應都不再是阻礙。

copyright © 萬盛學電腦網 all rights reserved