domainA 頁面嵌入 domainB 頁面 (iframe),domainB 內容動態變化需自適應高度,同源策略阻斷父頁直接讀取子頁高度。
domainA/index.html (父頁)
└─ iframe → domainB/other.html (子頁)
└─ iframe → domainA/agent.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>
<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>
<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 高度 (同域允許)
→ 完成自適應
?t=Date.now() 確保每次代理頁都重新載入執行 onload。window.parent.parent 從代理頁 → 子頁 → 父頁。
// 子頁 (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 可被竄改) | 僅極舊環境 |
| postMessage | IE8+ 全現代 | 即時、事件驅動 | 低 (兩頁面通信) | 高 (origin 驗證) | ⭐⭐⭐⭐⭐ 首選 |
| document.domain 降級 | IE6+ (同主域) | 即時 | 低 | 中 (放寬同源) | 同主域場景 |
window.top 定位頂層,window.parent 定位直接父級,避免硬編碼層級。