iframe 高度自適應受限於同源政策:父頁面無法直接讀取跨域 iframe 的 contentDocument.body.scrollHeight。本文提供三種方案,依專案環境選擇。
<script>
function resizeIframe(iframeId) {
const iframe = document.getElementById(iframeId);
if (!iframe) return;
iframe.onload = function() {
try {
// 同源才能存取
const doc = iframe.contentDocument || iframe.contentWindow.document;
const height = Math.max(
doc.body.scrollHeight,
doc.body.offsetHeight,
doc.documentElement.scrollHeight,
doc.documentElement.offsetHeight
);
iframe.style.height = height + 'px';
} catch (e) {
console.warn('跨域無法讀取高度,請改用 postMessage 方案', e);
}
};
}
// 使用
resizeIframe('myIframe');
</script>
postMessage 雙向通訊(標準做法)<iframe id="childFrame" src="https://other-domain.com/child.html" style="width:100%; border:none;"></iframe>
<script>
window.addEventListener('message', e => {
// 安全性:驗證來源
if (e.origin !== 'https://other-domain.com') return;
if (e.data && e.data.type === 'iframeResize') {
document.getElementById('childFrame').style.height = e.data.height + 'px';
}
});
</script>
<script>
function reportHeight() {
const height = Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
// 發送給父頁面,* 表允許所有源,生產環境請指定具體父域名
window.parent.postMessage({type: 'iframeResize', height}, '*');
}
// 頁面載入、DOM 變動、視窗調整時回報
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// 若有動態內容(AJAX、Vue/React 渲染),在渲染完成後手動呼叫 reportHeight()
</script>
ResizeObserver + 同源 Proxy(進階)若子頁面不可控且跨域,唯一辦法是在同源建立一個 Proxy 頁面去載入目標網站,再由 Proxy 向父頁面傳高度。架構較複雜,僅列概念:
父頁面 → iframe[Proxy頁面] → iframe[目標跨域頁面]
↑ ↑
接收 postMessage 同源可直接讀高度
// 原始碼問題:變數宣告未用 var/let、迴圈變數汙染全域、Opera 判斷過時
// 重構後:
const iframeIds = ['top1']; // 可擴充多個
const hideUnsupported = 'yes';
function dynIframeSize() {
iframeIds.forEach(id => {
const iframe = document.getElementById(id);
if (!iframe) return;
// 同源嘗試
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const height = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight);
iframe.style.height = height + 'px';
} catch (e) {
// 跨域失敗時的 fallback
if (hideUnsupported === 'no') iframe.style.display = 'block';
}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', dynIframeSize);
} else {
dynIframeSize();
}
// 視窗大小改變時重新計算
window.addEventListener('resize', dynIframeSize);
margin、padding、box-sizing 影響高度,建議在子頁面 body { margin: 0; }。reportHeight()。iframe { display: block; } 避免底部縫隙。