Iframe 常用於嵌入第三方內容或模組化頁面,但固定高度易造成雙滾動條或內容截斷。本文提供三種主流自適應高度方案,涵蓋同域簡單實作、跨域 postMessage 通訊、以及傳統 document.domain 降域相容,並附上完整程式碼與注意事項。
父頁面與 Iframe 同源(協議、域名、埠口相同),可直接讀取 iframe.contentDocument.body.scrollHeight。
function setIframeHeight(iframe) {
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.style.height = doc.documentElement.scrollHeight + 'px';
} catch (e) {
console.warn('同域高度獲取失敗', e);
}
}
// 綁定 onload 確保內容已渲染
document.getElementById('myIframe').onload = function() {
setIframeHeight(this);
};
適用於不同域名、協議或埠口。父頁面監聽 message 事件,子頁面定期發送高度資訊。
window.addEventListener('message', (e) => {
// 安全性:驗證來源
if (e.origin !== 'https://child.example.com') return;
if (e.data && e.data.type === 'iframeResize') {
document.getElementById('myIframe').style.height = e.data.height + 'px';
}
});
function sendHeight() {
const height = document.documentElement.scrollHeight;
parent.postMessage({ type: 'iframeResize', height }, 'https://parent.example.com');
}
// 頁面載入與內容變動時發送
window.addEventListener('load', sendHeight);
window.addEventListener('resize', sendHeight);
// 若內容動態變更(AJAX、Accordion),需手動呼叫 sendHeight()
父頁面與子頁面同屬 example.com 下不同子域(如 a.example.com、b.example.com),可雙方設定 document.domain = 'example.com' 後按方案一直接存取。
// 父頁面與子頁面皆須在 script 執行早期設定
document.domain = 'example.com';
注意:瀏覽器正逐步棄用 document.domain,新專案請優先採用 postMessage。
body { margin: 0; } 避免邊距干擾高度計算。scrolling="no" 或 CSS overflow: hidden。postMessage 必須驗證 e.origin,防止惡意注入。postMessage,可使用 ResizeObserver(現代瀏覽器)監聽子頁面 body 尺寸變化。包含同域、跨域兩套完整可執行範例:GitHub Repo 連結
Iframe 自適應高度的核心在於「子頁面知曉自身高度」與「父頁面安全接收高度」。現代專案首選 postMessage 方案,安全、跨域支援佳、擴充性高。搭配 ResizeObserver 可實現無感知的即時高度同步,徹底告別雙滾動條困擾。