首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

showModalDialog 獲取父窗口對象技巧:dialogArguments 替代 opener

     編輯:Java 相關知識

核心差異

窗口打開方式父窗口引用適用場景
window.open()window.opener普通彈窗、標籤頁
showModalDialog()window.dialogArguments模態對話框 (已棄用)
<iframe>window.parent頁面嵌套

showModalDialog 正確用法

1. 父頁面調用(關鍵:第二參數傳 self)

var url = "child.html?param=value";
var returnValue = window.showModalDialog(url, self, "dialogWidth:600px;dialogHeight:400px;");
  • 第二參數 self 將當前 window 作為 dialogArguments 傳遞
  • 第三參數為特性字符串

2. 子頁面獲取父窗口

// 獲取父窗口 window 對象
var parentWindow = window.dialogArguments;

// 操作父頁面元素
var processId = parentWindow.document.getElementsByName("processId")[0].value;
parentWindow.document.getElementById("result").innerText = "處理完成";

// 調用父頁面函數
parentWindow.refreshData();

// 返回值給父頁面
window.returnValue = { success: true, data: "xxx" };

3. 父頁面接收返回值

var result = window.showModalDialog(...);
if (result && result.success) {
    console.log("子頁面返回:", result.data);
}

opener vs parent vs dialogArguments

  • opener:誰打開的我(window.open 彈窗的父窗口)
  • parent:iframe/frame 的父窗口
  • dialogArguments:showModalDialog 顯式傳遞的參數對象(通常為父 window)

⚠️ 重要警告

showModalDialog 已從 Web 標準移除:Chrome 37+、Firefox 44+、Edge 79+、Safari 13+ 均不再支持。
現代替代方案:
  • 同源頁面:window.open() + postMessage 通信
  • 模態交互:Bootstrap Modal / Layer / SweetAlert2 / 原生 <dialog> 元素
  • 複雜表單:單頁應用路由 + 狀態管理

遷移代碼模式

// 現代模態對話框模式 (以 Bootstrap 5 為例)
/* 父頁面 */
const modal = new bootstrap.Modal(document.getElementById('myModal'));
document.getElementById('myModal').addEventListener('hidden.bs.modal', () => {
    // 子頁面通過 postMessage 或全局事件總線通信
});
modal.show();

/* 子頁面 (iframe/src) */
window.parent.postMessage({type: 'RESULT', data: {...}}, '*');
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved