經典框架頁面(左側導航 + 右側內容)中,如何實現左側鏈接點擊後:① 切換右側 iframe `src` ② 調用右側頁面內部 JS 函數?本文提供**兼容 IE6+、Firefox、Chrome** 的標準化跨幀調用方案。
<!-- index.html 容器頁 -->
<iframe id="leftFrame" src="left.html" style="width:180px; height:100%;"></iframe>
<iframe id="rightFrame" src="right.html" style="flex:1; height:100%;"></iframe>
需求:在 `left.html` 中點擊鏈接,調用 `right.html` 內的 `right()` 函數。
// 1. 獲取父頁面 window
const parentWin = window.parent;
// 2. 獲取右側 iframe 元素
const rightFrame = parentWin.document.getElementById('rightFrame');
// 3. 關鍵:獲取右側頁面的 window 代理
const rightWin = rightFrame.contentWindow;
// 4. 調用目標函數
if (typeof rightWin.right === 'function') {
rightWin.right();
}
// 5. 同時切換 src(可選)
rightFrame.src = 'new-page.html';
/**
* 跨幀調用工具
* @param {string} targetFrameId 目標 iframe id
* @param {string} fnName 要調用的函數名
* @param {...any} args 傳遞參數
*/
function callFrameFn(targetFrameId, fnName, ...args) {
try {
const frame = window.parent.document.getElementById(targetFrameId);
if (!frame) throw new Error(`iframe#${targetFrameId} not found`);
const win = frame.contentWindow;
if (typeof win[fnName] === 'function') {
return win[fnName](...args);
}
console.warn(`Function ${fnName} not found in ${targetFrameId}`);
} catch (e) {
console.error('Cross-frame call failed:', e);
}
}
// 使用示例
// 左幀調用右幀函數
callFrameFn('rightFrame', 'refreshData', {page: 2});
// 右幀調用左幀函數
callFrameFn('leftFrame', 'highlightMenu', 'menu-3');
| 方向 | 代碼 |
|---|---|
| 父 → 子 | document.getElementById('childFrame').contentWindow.childFn() |
| 子 → 父 | window.parent.parentFn() |
| 子 → 兄/弟幀 | window.parent.document.getElementById('brotherFrame').contentWindow.fn() |
若涉及跨域或解耦,推薦使用 `postMessage`:
<!-- 發送端(左幀) -->
window.parent.postMessage({type: 'CALL_FN', fn: 'right', args: [1,2]}, '*');
<!-- 接收端(右幀) -->
window.addEventListener('message', e => {
if (e.data.type === 'CALL_FN' && typeof window[e.data.fn] === 'function') {
window[e.data.fn](...e.data.args);
}
});
iframe 跨幀調用的核心是 **`window.parent` + `contentWindow`** 鏈路。封裝通用工具函數、做好同域檢查、異步加載保護,即可構建健壯的多幀應用架構。