在同域或跨域 (需協作) 情況下,透過 <iframe> 嵌入外部頁面並自動調整高度以消除雙滾動條,是常見需求。本文提供完整實作方案:動態計算高度、跨域通訊、樣式隔離。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>父頁面</title>
<style>
body, html { margin:0; padding:0; height:100%; overflow:hidden; }
#externalFrame { width:100%; border:none; display:block; }
</style>
</head>
<body>
<iframe id="externalFrame" src="https://example.com/page.html"></iframe>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
const $frame = $('#externalFrame');
// 方法 1: onload 後直接讀取內容高度 (同域)
$frame.on('load', function() {
try {
const doc = this.contentDocument || this.contentWindow.document;
const height = Math.max(
doc.body.scrollHeight, doc.documentElement.scrollHeight,
doc.body.offsetHeight, doc.documentElement.offsetHeight
);
$frame.height(height + 20); // 留白
} catch (e) {
console.warn('跨域無法讀取:', e);
}
});
// 方法 2: 監聽視窗大小變化重新計算
$(window).on('resize', () => $frame.trigger('load'));
});
</script>
</body>
</html>
**前提**:子頁面控制權在你手中,可植入腳本。
<iframe id="childFrame" src="https://child-domain.com/page.html" style="width:100%;border:none;"></iframe>
<script>
const $frame = $('#childFrame');
window.addEventListener('message', function(e) {
// 安全性:驗證來源
if (e.origin !== 'https://child-domain.com') return;
if (e.data && e.data.type === 'iframeResize') {
$frame.height(e.data.height + 20);
}
});
</script>
<script>
function reportHeight() {
const height = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight
);
parent.postMessage({ type: 'iframeResize', height }, 'https://parent-domain.com');
}
// 頁面載入、資源載入、視窗變化時上報
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// 圖片載入後也需重新計算
document.querySelectorAll('img').forEach(img => {
img.addEventListener('load', reportHeight);
});
// 定時輪詢兜底 (針對動態內容)
setInterval(reportHeight, 500);
</script>
// 父頁面引入
function setupIframeAutoHeight(iframeSelector, options = {}) {
const { allowedOrigin = '*', debounce = 100 } = options;
let timer;
window.addEventListener('message', e => {
if (allowedOrigin !== '*' && e.origin !== allowedOrigin) return;
if (e.data?.type === 'iframeResize') {
clearTimeout(timer);
timer = setTimeout(() => {
document.querySelector(iframeSelector).style.height = e.data.height + 'px';
}, debounce);
}
});
}
// 子頁面引入
function initIframeReporter(options = {}) {
const { targetOrigin = '*', interval = 500 } = options;
const calc = () => Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight
);
const report = () => parent.postMessage({ type: 'iframeResize', height: calc() }, targetOrigin);
['load', 'resize'].forEach(evt => window.addEventListener(evt, report));
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('img, iframe').forEach(el => el.addEventListener('load', report));
});
setInterval(report, interval);
}
<iframe sandbox="allow-scripts allow-same-origin allow-forms"> 限制子頁面權限。Content-Security-Policy: frame-src 'self' https://trusted.com;。SAMEORIGIN 或 DENY 防止被任意嵌入。overflow:hidden,iframe scrolling="no",由父頁面統一滾動。| 現象 | 原因 | 解決 |
|---|---|---|
| 高度為 0 或不變 | 跨域無法讀取 contentDocument | 改用 postMessage 方案 |
| 高度忽大忽小 | 圖片/字體載入後重排 | 子頁面監聽 img.onload、font loading API |
| 雙滾動條 | 父頁面未隱藏 overflow、iframe 有 scrolling | 父頁面 overflow:hidden, iframe scrolling="no" |
| 白屏/拒絕連線 | 目標站設定 X-Frame-Options: DENY | 無法解決,需對方開放或改用代理/截圖 |
同域用 onload 直接量測最簡單;跨域必須雙方協作用 postMessage。封裝成可複用函式庫並處理「圖片載入重排」、「動態內容輪詢」、「防抖」三大細節,即可獲得穩定體驗。安全性務必驗證 e.origin 並善用 sandbox。