contentDocument.body.scrollHeight。<!-- 父頁面 -->
<iframe id="myFrame" src="child.html" frameborder="0" scrolling="no" style="width:100%;"></iframe>
<script>
$('#myFrame').on('load', function() {
var $iframe = $(this);
// 延遲確保內部圖片/字體渲染完成
setTimeout(function() {
try {
var height = $iframe[0].contentWindow.document.body.scrollHeight;
$iframe.height(height + 20); // 留白緩衝
} catch (e) {
console.error('同域高度獲取失敗:', e);
}
}, 100);
});
</script>
<!-- 子頁面 child.html -->
<script>
function reportHeight() {
var height = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight
);
// 發送給父頁
parent.postMessage({type: 'iframeResize', height: height}, '*'); // 生產環境指定具體域
}
// 頁面載入
window.addEventListener('load', reportHeight);
// 窗口變化
window.addEventListener('resize', reportHeight);
// 業務動態更新後 (AJAX 完成、圖片 onload、元素展開/折疊)
function afterContentChange() {
// nextTick 確保佈局更新
requestAnimationFrame(reportHeight);
}
</script>
<!-- 父頁面 -->
<script>
window.addEventListener('message', function(e) {
// 安全驗證來源
if (e.origin !== 'https://trusted-child-domain.com') return;
if (e.data.type === 'iframeResize') {
document.getElementById('myFrame').style.height = e.data.height + 'px';
}
});
</script>
同方案二,但父子頁面域不同。關鍵點:
parent.postMessage(data, parentOrigin) 指定目標源。e.origin 驗證來源合法性。
架構:
parent.html (domain A)
└─ iframe → child.html (domain B)
└─ iframe → agent.html (domain A, 隱藏, src="agent.html#width|height")
流程:
1. child.html 計算高寬 → 設置 agent.html src = "agent.html#w|h" (觸發重載)
2. agent.html 解析 hash → parent.parent.document.getElementById('iframeId').style.height = h
3. 利用同源策略:agent.html 與 parent.html 同域,可操作父頁 DOM
<!-- child.html (domain B) -->
<iframe id="proxy" src="https://domain-a.com/agent.html" style="display:none"></iframe>
<script>
function syncSize() {
var w = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
var h = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
document.getElementById('proxy').src = 'https://domain-a.com/agent.html#' + w + '|' + h;
}
window.onload = syncSize;
window.onresize = syncSize;
// 動態內容更新後調用 syncSize()
</script>
<!-- agent.html (domain A) -->
<script>
window.onload = function() {
var hash = location.hash; // #1200|800
if (hash.indexOf('#') === 0) {
var parts = hash.substring(1).split('|');
var w = parts[0] + 'px', h = parts[1] + 'px';
// 操作頂層父頁的 iframe
var topFrame = window.parent.parent.document.getElementById('myFrame');
if (topFrame) {
topFrame.style.width = w;
topFrame.style.height = h;
}
}
};
</script>
// 父頁面寫法 (放在 iframe 後面)
$('#mainframe').on('load', function() {
var h = $(this).contents().find('body').height() + 30;
$(this).height(h);
});
// 子頁面寫法
$(window.parent.document).find('#mainframe').on('load', function() {
var h = $(document).height() + 30;
$(this).height(h);
});
// 子頁面
var observer = new MutationObserver(function(mutations) {
// 過濾屬性變化、字符數據變化,僅關注結構變化
var hasStructuralChange = mutations.some(function(m) {
return m.type === 'childList' || m.type === 'characterData';
});
if (hasStructuralChange) reportHeight();
});
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true
});
// 子頁面
var resizeObserver = new ResizeObserver(function(entries) {
for (var entry of entries) {
if (entry.target === document.body) {
reportHeight();
break;
}
}
});
resizeObserver.observe(document.body);
| 場景 | 推薦方案 | 關鍵點 |
|---|---|---|
| 同域、靜態內容 | 方案一 (load 事件) | 簡單、無需修改子頁 |
| 同域、動態內容 | 方案二 (postMessage) | 實時、雙向通信、擴展性強 |
| 跨域、現代瀏覽器 | 方案三 (postMessage) | 標準、安全、無代理頁 |
| 跨域、需支援 IE8- | 方案四 (代理頁) | 繞過同源限制、維護成本高 |
| 嵌入第三方無法修改 | 方案一 + 定時輪詢 | 最後手段、效能差 |
min-height: 200px 防止空頁塌陷。scrolling="no" overflow:hidden,子頁自行滾動。agent.html?t=xxx#w|h 強制重載。window.top 定位頂層,window.parent 定位直接父級。