iframe 嵌套頁面間的 JavaScript 互調,是很多後台管理系統、微前端架構的核心需求。本文系統總結 **父調子、子調父、同級幀互調** 的標準寫法、兼容性陷阱、封裝工具與現代 `postMessage` 解耦方案。
頂層 window (index.html)
├── iframe#leftFrame (left.html) → window.parent === 頂層 window
└── iframe#rightFrame (right.html) → window.parent === 頂層 window
<iframe id="childFrame" src="child.html"></iframe>
<script>
// 方式一:contentWindow(標準,推薦)
document.getElementById('childFrame').contentWindow.childFn();
// 方式二:window.frames 集合(需 iframe 有 name 屬性)
window.frames['childFrame'].childFn();
// 或
window.frames[0].childFn();
<!-- child.html -->
<script>
// 直接訪問父窗口 window
window.parent.parentFn();
// 修改父頁面元素
window.parent.document.getElementById('someId').src = 'new.html';
// 甚至調用父頁面的其他 iframe 函數
window.parent.document.getElementById('brotherFrame').contentWindow.brotherFn();
<!-- left.html 中調用 right.html 的函數 -->
<script>
const rightWin = window.parent.document.getElementById('rightFrame').contentWindow;
rightWin.rightFn('param1', 'param2');
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
| `document.frames.iframeId.fn()` | IE 專屬,非標準 | `document.getElementById('iframeId').contentWindow.fn()` |
| `window.parent.iframeId.fn()` | iframe 不會自動掛載為 window 屬性 | 同上,通過 DOM 獲取 |
| 遍歷 `document.all` 找 iframe | 性能差、非標準、極易出錯 | 直接 `getElementById` 或 `querySelector` |
| 用 `id` 當 `name` 用 `window.frames[id]` | `frames` 集合索引的是 `name` 屬性 | 給 iframe 加 `name="xxx"` 或用 `contentWindow` |
const FrameMessenger = {
// 從任意幀調用目標幀函數
call(targetFrameId, fnName, ...args) {
const frame = window.parent.document.getElementById(targetFrameId);
if (!frame) return Promise.reject(`Frame ${targetFrameId} not found`);
// 等待 iframe 加載完成
return new Promise((resolve, reject) => {
if (frame.contentWindow && typeof frame.contentWindow[fnName] === 'function') {
resolve(frame.contentWindow[fnName](...args));
} else {
frame.onload = () => {
if (typeof frame.contentWindow[fnName] === 'function') {
resolve(frame.contentWindow[fnName](...args));
} else {
reject(`Function ${fnName} not found in ${targetFrameId}`);
}
};
}
});
},
// 父頁廣播給所有子幀
broadcast(fnName, ...args) {
const frames = window.parent.document.querySelectorAll('iframe');
frames.forEach(f => {
if (f.contentWindow && typeof f.contentWindow[fnName] === 'function') {
f.contentWindow[fnName](...args);
}
});
}
};
// 使用示例
// left.html 中
FrameMessenger.call('rightFrame', 'loadData', {page: 1}).catch(console.error);
若 iframe `id` 從配置動態獲取,無法寫死:
// 假設配置對象
const config = { iframeId: 'dynamicFrame_123' };
// 錯誤:document.frames[config.iframeId] 只認 name
// 正確:
const frame = window.parent.document.getElementById(config.iframeId);
frame.contentWindow.targetFn();
// 或統一規範:iframe 同時設置 id 和 name 相同值
<iframe id="dynamicFrame_123" name="dynamicFrame_123" ...>
window.parent.frames[config.iframeId].targetFn(); // 此時可行
當需要**跨域**、**解耦邏輯**、**支持多實例**時,拋棄直接調用,改用消息總線:
<!-- 發送端 -->
window.parent.postMessage({
action: 'invoke',
target: 'rightFrame', // 或 'broadcast'
method: 'refreshList',
payload: {filter: 'active'}
}, '*'); // 生產環境請指定具體 origin
<!-- 接收端(每個 iframe 內掛載一次) -->
window.addEventListener('message', e => {
if (e.data.action !== 'invoke') return;
if (e.data.target !== 'broadcast' && e.data.target !== window.name) return;
const fn = window[e.data.method];
if (typeof fn === 'function') {
fn(...(e.data.payload || []));
}
});