iframe 自適應高度面臨兩大挑戰:
document.body.scrollHeight。// iframe 內頁面 (child.html)
window.onload = function() {
// 確保圖片等資源載入完成
var height = document.body.scrollHeight;
parent.postMessage({type: 'resize', height: height}, '*');
};
// 父頁面 (parent.html)
window.addEventListener('message', function(e) {
if (e.data.type === 'resize') {
document.getElementById('myIframe').style.height = e.data.height + 'px';
}
});
// 父頁面
$('#myIframe').on('load', function() {
var iframe = this;
function checkHeight() {
try {
var h = iframe.contentWindow.document.body.scrollHeight;
iframe.style.height = h + 'px';
} catch (e) {
// 跨域會拋錯
}
}
checkHeight();
setInterval(checkHeight, 500); // 定期檢測動態內容變化
});
parent.html (domain A)
└─ iframe → child.html (domain B)
└─ iframe → agent.html (domain A, 隱藏)
agent.html#height。parent.parent.postMessage 或直接操作頂層 iframe 高度。// 父頁面
<iframe id="childFrame" src="https://domain-b.com/child.html" frameborder="0" scrolling="no"></iframe>
<script>
window.addEventListener('message', function(e) {
// 安全驗證來源
if (e.origin !== 'https://domain-b.com') return;
if (e.data.type === 'iframeResize') {
document.getElementById('childFrame').style.height = e.data.height + 'px';
}
});
</script>
// 子頁面 (domain B)
function reportHeight() {
var height = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight
);
parent.postMessage({type: 'iframeResize', height: height}, 'https://domain-a.com');
}
// 頁面載入、窗口變化、異步數據更新後均調用
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// 業務邏輯:數據渲染完成後
fetchData().then(render).then(reportHeight);
min-height 防止內容為空時塌陷。scrolling="no",子頁內容超出自動滾動。