首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Chrome 下實現 Dialog 父子頁面傳值的現代方案

     編輯:程式設計綜合問答

背景:showModalDialog 已被廢棄

window.showModalDialog 是 IE 專有 API,Chrome、Firefox、Edge 等現代瀏覽器均不支持。舊代碼依賴 window.dialogArguments 和 window.returnValue 進行父子頁通信,需遷移到標準化方案。

推薦方案:使用 window.open + postMessage

父頁面

// 打開子頁面
var childWin = window.open('child.html', '_blank', 'width=600,height=400');

// 監聽子頁面發送的消息
window.addEventListener('message', function(event) {
  // 安全性驗證來源
  if (event.origin !== 'https://your-domain.com') return;
  console.log('收到子頁數據:', event.data);
  // 業務處理...
});

子頁面

// 向父頁發送數據
function sendToParent(data) {
  // 確保父頁面已就緒
  if (window.opener) {
    window.opener.postMessage(data, 'https://your-domain.com'); // 目標源
  }
}

// 示例:按鈕點擊傳值
document.getElementById('btn').onclick = function() {
  sendToParent({ type: 'result', value: '用戶輸入的內容' });
};

優勢

  • 跨域安全:postMessage 支持指定 targetOrigin,防止消息被惡意頁面竊取。
  • 雙向通信:父頁也可向子頁發送消息(childWin.postMessage(...)),子頁通過 window.addEventListener('message', ...) 接收。
  • 標準化:HTML5 規範,所有現代瀏覽器支持,無需插件或 hack。

兼容舊代碼的過渡方案

若項目仍依賴 showModalDialog 風格的同步阻塞行為,可考慮:

  1. 使用 showModalDialog Polyfill,模擬原生行為。
  2. 將業務邏輯改為異步回調/ Promise 模式,配合 postMessage 實現。

總結

拋棄 showModalDialog,擁抱 window.open + postMessage,是現代 Web 開發中實現彈窗父子頁傳值的標準、安全、跨瀏覽器方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved