iframe 嵌入第三方頁面、舊系統集成、沙箱隔離是常見場景。本文系統總結 jQuery 操作 iframe 的同域訪問、跨域 postMessage 通信、內容高度自適應、動態加載腳本/樣式、內存洩漏清理,並提供現代原生替代方案。
const $iframe = $('#myIframe');
const iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document;
// 等待加載完成
$iframe.on('load', function() {
const $body = $(this).contents().find('body');
$body.css('background', '#f0f0f0');
$body.find('button').on('click', () => alert('iframe 內按鈕被點擊'));
});
// 父頁面調用 iframe 內函數
$iframe[0].contentWindow.myIframeFunction();
// iframe 內調用父頁面函數
window.parent.parentFunction();
// 父頁面
const iframe = document.getElementById('crossIframe');
iframe.addEventListener('load', () => {
iframe.contentWindow.postMessage({ type: 'INIT', data: { token: 'abc' } }, 'https://child.example.com');
});
window.addEventListener('message', e => {
if (e.origin !== 'https://child.example.com') return;
if (e.data.type === 'RESIZE') {
iframe.style.height = e.data.height + 'px';
}
});
// 子頁面
window.addEventListener('message', e => {
if (e.origin !== 'https://parent.example.com') return;
if (e.data.type === 'INIT') { initApp(e.data.data.token); }
});
function notifyResize() {
const height = document.body.scrollHeight;
window.parent.postMessage({ type: 'RESIZE', height }, 'https://parent.example.com');
}
// 內容變化時調用
new MutationObserver(notifyResize).observe(document.body, { subtree: true, childList: true });
| 方案 | 原理 | 優點 | 缺點 |
|---|---|---|---|
| postMessage + scrollHeight | 子頁面計算高度發送給父頁面 | 跨域支援、精確 | 需修改子頁面代碼 |
同域 contentDocument.body.scrollHeight | 父頁面直接讀取 | 簡單、無需子頁面配合 | 僅同域、CSS transform 影響準確性 |
| ResizeObserver (現代) | 監聽 iframe 內容尺寸變化 | 自動、無需輪詢 | 需同域、較新瀏覽器 |
CSS iframe { width:100%; height:100%; } + 父容器定高 | 交由瀏覽器佈局 | 零 JS | 需已知高度或父容器撐開 |
function injectScript(iframe, src) {
const doc = iframe.contentDocument;
const script = doc.createElement('script');
script.src = src;
doc.head.appendChild(script);
return new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
});
}
function destroyIframe($iframe) {
const el = $iframe[0];
// 1. 移除事件監聽(若有綁定 load 等)
$iframe.off('load');
// 2. 斷開 postMessage 監聽(需保存 handler 引用)
window.removeEventListener('message', messageHandler);
// 3. 清空 src 釋放資源
el.src = 'about:blank';
// 4. 從 DOM 移除
$iframe.remove();
// 5. 釋放 jQuery 數據緩存
$iframe.removeData();
}
const iframe = document.getElementById('myIframe');
iframe.onload = () => {
const doc = iframe.contentDocument;
doc.body.style.background = '#f0f0f0';
doc.querySelectorAll('button').forEach(b => b.addEventListener('click', ...));
};
// 其餘邏輯同理,僅將 $() 改為原生 API