showModalDialog 創建的模態窗口會阻塞父頁面交互,直到關閉。其獨特優勢在於:子頁可直接訪問父頁變量/函數/對象(通過 dialogArguments),實現極簡的雙向通信。本文深度解析參數、通信模式、常見坑點與遷移方案。
var returnValue = window.showModalDialog(sURL, vArguments, sFeatures);
// 父頁
var result = window.showModalDialog('selectUser.html', null, 'dialogWidth:600px;dialogHeight:400px;center:yes');
if (result) { console.log('選中用戶:', result); }
// 子頁 selectUser.html
function selectUser(user) {
window.returnValue = user; // {id: 1, name: '張三'}
window.close();
}
// 父頁 parent.html
var pageContext = {
formData: { name: '', email: '' },
save: function(data) { console.log('父頁保存:', data); },
userList: [{id:1, name:'張三'}, {id:2, name:'李四'}]
};
window.showModalDialog('editUser.html', pageContext, 'dialogWidth:500px;dialogHeight:400px;resizable:yes');
// 子頁 editUser.html
var ctx = window.dialogArguments; // 直接拿到父頁對象引用
// 讀取父頁數據
console.log(ctx.userList);
// 修改父頁數據(實時生效)
ctx.formData.name = '王五';
// 調用父頁方法
ctx.save({id: 3, name: '新用戶'});
// 關閉無需設置 returnValue,父頁對象已同步更新
window.close();
| 參數 | 說明 | 示例 |
|---|---|---|
| dialogWidth / dialogHeight | 寬高(px/em),最小 100px | dialogWidth:600px;dialogHeight:400px |
| dialogLeft / dialogTop | 屏幕座標 | dialogLeft:200;dialogTop:100 |
| center | 是否居中 | center:yes |
| resizable | 可否拖拽調整大小 | resizable:yes |
| scroll | 滾動條 | scroll:no |
| status | 狀態欄 | status:no |
| help | 幫助按鈕(IE4) | help:no |
// toolbar.html 中的按鈕點擊
function onSave() {
var contentWin = parent.content; // 獲取同級 frame
var data = contentWin.getFormData(); // 調用 content 頁面函數
window.dialogArguments.formData = data; // 寫入父頁共享對象
window.returnValue = data; // 兼容性設置
window.close(); // 關閉整個模態框
}
<head> 加 <base target="_self">,否則 target="_blank" 或默認行為會在新標籤打開。keydown 攔截 F5 (keyCode 116) 執行 location.reload()。window.close() 配合 base target="_self" 使用。sessionStorage 中轉。// 統一 Modal 服務
const ModalService = {
open: function(options) {
return new Promise((resolve, reject) => {
// 這裡接入 Bootstrap Modal / Element Plus Dialog / Ant Design Modal
// 組件確認回調 resolve(data),取消回調 reject(reason)
});
}
};
// 業務調用
async function handleEdit() {
try {
const result = await ModalService.open({
title: '編輯用戶',
component: EditUserDialog,
props: { userId: 1001 }
});
console.log('用戶保存:', result);
await refreshTable();
} catch (e) {
console.log('用戶取消或錯誤:', e);
}
}
showModalDialog 的「阻塞式調用 + 共享對象引用」模式在當時極具創新性,但已不符合現代 Web 標準。新項目使用 <dialog> 或組件庫 Modal + Promise/async-await 實現同樣語義且跨瀏覽器。老項目維護時,掌握 dialogArguments 引用傳遞技巧能大幅簡化父子頁耦合。