萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

iframe 跨幀調用 JS 函數:父子、同級幀雙向通信完整方案

經典框架頁面(左側導航 + 右側內容)中,如何實現左側鏈接點擊後:① 切換右側 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()` 函數。

核心難點:同源策略與 window 代理

  • 同域下,`iframe` 元素的 `contentWindow` 屬性返回內部 `window` 代理
  • 跨幀調用鏈:`左幀 → 父頁 → 右幀 → 目標函數`

標準實現步驟(左幀代碼)

// 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()

兼容性備註

  • ✅ IE6+、Firefox 3+、Chrome 2+、Safari 3+、Edge 全支持
  • ⚠️ **必須同域**(協議、域名、埠一致),否則拋出安全錯誤
  • 跨域場景請用 `window.postMessage` API
  • `contentWindow` 在 iframe 載入完成前為 `null`,建議在 `onload` 後調用

常見錯誤避雷

  1. 用 `document.frames['name']`(IE 專屬)而非標準 `contentWindow`
  2. 2. 直接 `window.parent.rightFrame.fn()` 假設 iframe 自動成為 window 屬性(不標準) 3. 忽略 iframe 加載狀態,導致 `contentWindow` 為 `null` 4. 混淆 `id` 與 `name`:`getElementById` 取 `id`,`window.frames['name']` 取 `name`

現代替代方案:postMessage

若涉及跨域或解耦,推薦使用 `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`** 鏈路。封裝通用工具函數、做好同域檢查、異步加載保護,即可構建健壯的多幀應用架構。

copyright © 萬盛學電腦網 all rights reserved