萬盛學電腦網

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

JavaScript 窗口間通訊:window.open、showModalDialog、postMessage

瀏覽器提供多種跨窗口通訊方式,從傳統 window.open/showModalDialog 到現代 postMessage,各有適用場景與安全性考量。

1. window.open(通用)

var win = window.open('child.html', 'childWin', 'width=400,height=300');
// 父 -> 子
win.onload = function() { win.initData({ token: 'abc' }); };
// 子 -> 父
window.opener.parentCallback('result');

缺點:同源策略限制跨域訪問;移動端常被攔截。

2. showModalDialog / showModelessDialog(IE 專屬,已棄用)

// 父頁
var obj = { user: 'admin' };
var ret = window.showModalDialog('modal.html', obj, 'dialogWidth:400px;dialogHeight:300px;');
console.log(ret); // 子頁返回值

// 子頁
var args = window.dialogArguments; // 獲取傳入物件
window.returnValue = 'ok'; // 返回值

現狀:Chrome/Firefox/Edge 均已移除,不建議新專案使用。

3. postMessage(現代標準,跨域安全)

// 父頁嵌入 iframe
var iframe = document.getElementById('myFrame');
iframe.onload = function() {
  iframe.contentWindow.postMessage({ type: 'init', data: 123 }, 'https://child.example.com');
};
window.addEventListener('message', function(e) {
  if (e.origin !== 'https://child.example.com') return;
  console.log('收到子頁回傳:', e.data);
});

// 子頁
window.addEventListener('message', function(e) {
  if (e.origin !== 'https://parent.example.com') return;
  if (e.data.type === 'init') {
    e.source.postMessage({ type: 'result', value: 'ok' }, e.origin);
  }
});

選型建議

  • 同域、簡單跳轉/彈窗:window.open + opener。
  • 跨域、嵌入 iframe/多窗口協作:強制使用 postMessage,驗證 origin 確保安全。
  • 避免使用 showModalDialog、arguments.callee 等已棄用 API。
copyright © 萬盛學電腦網 all rights reserved