萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 跨窗口元素訪問全指南:parent、top、opener、iframe 通信詳解

核心選擇器語法

// 父頁面文檔上下文查找
$("#elementId", window.parent.document);

// 父頁面的父頁面
$("#elementId", window.parent.parent.document);

// 頂層窗口
$("#elementId", window.top.document);

// 打開當前窗口的窗口
$("#elementId", window.opener.document);

// 頂層窗口下的第 1 個 iframe
$("#elementId", window.top.frames[0].document);

// 指定 name 的 iframe
$("#elementId", window.frames["iframeName"].document);

原生 JavaScript 等價寫法

window.parent.document.getElementById("elementId");
window.top.document.getElementById("elementId");
window.opener.document.getElementById("elementId");
window.top.frames[0].document.getElementById("elementId");

窗口打開方式與通信對比

1. window.open() - 普通彈窗

// 父頁面
const child = window.open('child.html', '_blank', 'width=600,height=400');
// 子頁面訪問父頁面
window.opener.document.getElementById('parentInput').value = 'from child';
window.opener.location.reload(); // 刷新父頁面

特點:雙向自由訪問(同源前提下),父頁面可通過 child.document 訪問子頁面。

2. showModalDialog() - 模態對話框 (IE 專有,已棄用)

// 父頁面
const result = window.showModalDialog('dialog.html', window, 'dialogWidth:400px;dialogHeight:300px;');
// 父頁面接收返回值
if (result !== undefined) { /* ... */ }

// 子頁面訪問父頁面
const parent = window.dialogArguments; // 接收父頁面傳入的第二個參數
parent.document.getElementById('age').value = 25;

// 子頁面返回值
window.returnValue = { name: 'John', age: 25 };
window.close();

⚠️ 已從 Web 標準移除,現代瀏覽器不支持,請勿在新項目使用。

3. showModelessDialog() - 非模態對話框 (IE 專有,已棄用)

類似 showModalDialog 但不阻塞父頁面,同樣已棄用。

現代跨窗口通信最佳實踐:postMessage

// 父頁面
const child = window.open('child.html');
window.addEventListener('message', e => {
  if (e.origin !== 'https://trusted-origin.com') return; // 安全驗證來源
  if (e.data.type === 'FORM_SUBMIT') {
    document.getElementById('result').textContent = e.data.payload;
  }
});

// 子頁面
window.opener.postMessage({ type: 'FORM_SUBMIT', payload: '用戶提交的數據' }, 'https://parent-origin.com');

優點:跨域安全、解耦、不依賴同源策略、支持結構化數據傳遞。

iframe 父子通信

<!-- 父頁面 -->
<iframe id="myFrame" src="child.html"></iframe>
<script>
const iframe = document.getElementById('myFrame');
iframe.onload = () => {
  // 父 -> 子
  iframe.contentWindow.postMessage({ action: 'init', data: 123 }, '*');
  
  // 子 -> 父
  window.addEventListener('message', e => {
    if (e.source === iframe.contentWindow) {
      console.log('收到子頁面消息:', e.data);
    }
  });
};
</script>

<!-- 子頁面 child.html -->
<script>
window.addEventListener('message', e => {
  if (e.data.action === 'init') {
    console.log('初始化數據:', e.data.data);
    // 回傳
    e.source.postMessage({ status: 'ready' }, e.origin);
  }
});
</script>

安全檢查清單

  • ✅ 始終驗證 e.origin 白名單。
  • ✅ 使用 e.source 確認消息發送方身份。
  • ✅ 定義嚴格的消息協議 { type, payload },避免任意代碼執行。
  • ✅ 敏感操作(支付、刪除)需雙向確認,防 CSRF。
copyright © 萬盛學電腦網 all rights reserved