跨域 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 高度
<!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>
<!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>
<!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>
iframe.src 觸發代理頁重新加載,代理頁腳本執行時自動擁有訪問 parent.parent (主頁) 的權限,因為**代理頁與主頁同域**。無需雙方協作部署 postMessage 監聽器。原文利用 proxyFrame.src = proxyUrl + '#' + height 觸發代理頁**重新加載**,每次高度變化即一次加載,天然事件驅動,無需定時器。注意:需確保代理頁無緩存或添加時間戳參數 ?t=Date.now()。
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);
| 方案 | 原理 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| 代理頁 + hash | src 觸發重載 + 同域訪問 | 無需雙方協作部署、兼容極舊瀏覽器 | 代理頁重載開銷、URL 歷史污染 | 舊系統、無法修改主頁代碼 |
| postMessage | Cross-document messaging | 標準、雙向、無重載、性能優 | 需雙方部署代碼、IE8- 不支持 | 現代項目、可控雙方代碼 |
| document.domain 降級 | 設置相同 document.domain | 同主域下直接訪問 | 僅限同主域、瀏覽器正棄用、安全風險 | 同主域子域名場景 |
| CSS 單位 vh/vw | 視口單位佈局 | 無 JS、極簡 | 無法適配動態內容高度 | 固定比例佈局 |
document.referrer 或約定密鑰)Math.max(200, Math.min(height, 10000)) 防止惡意撐大/縮小frame-ancestors 限制可嵌入域SAMEORIGIN 或 ALLOW-FROM (舊)console.log
<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>
[Parent] [Child] [Proxy] 前綴,清晰追蹤調用鏈掌握這套方案,無論是嵌入第三方報表、支付頁面、還是微前端子應用,iframe 高度自適應都不再是阻礙。