showModalDialog 的返回值機制(window.returnValue)是其區別於 window.open 的核心特性。本文系統梳理返回值傳遞、參數傳遞技巧、模態/非模態差異、常見問題與現代替代方案。
// 父頁
var result = window.showModalDialog('child.html', params, features);
// 同步阻塞,直到子頁調用 window.close()
// result === 子頁設置的 window.returnValue
// 子頁
window.returnValue = { id: 1, name: '選中項' }; // 任意可序列化值
window.close(); // 必須調用才能返回
window.showModalDialog('child.html', '單個字符串', features);
// 子頁: window.dialogArguments === '單個字符串'
// 父頁
var context = {
config: { theme: 'dark' },
onSave: function(data) { console.log('保存:', data); },
selectedIds: []
};
window.showModalDialog('child.html', context, features);
// 子頁
var ctx = window.dialogArguments;
ctx.selectedIds.push(100); // 修改父頁數組
ctx.onSave({name: '新數據'}); // 調用父頁函數
// 父頁 context 實時同步,無需 returnValue
// 父頁
window.showModalDialog('child.html', window, features);
// 子頁
var parentWin = window.dialogArguments;
parentWin.document.getElementById('input').value = '直接操作父頁 DOM';
parentWin.someGlobalFunction(); // 調用父頁全局函數
| 特性 | showModalDialog | showModelessDialog |
|---|---|---|
| 阻塞父頁 | 是(模態) | 否(非模態) |
| 返回值 | window.returnValue | 無同步返回,需回調 |
| 用戶可切換回父頁 | 否 | 是 |
| 適用場景 | 必須完成的選擇/輸入 | 輔助工具、面板、聊天窗 |
<!-- 子頁 head 中添加 -->
<base target="_self">
<body onkeydown="if(event.keyCode===116){location.reload()}">
<a id="reload" href="child.html" style="display:none"></a>
<script> document.onkeydown = function(e) { if(e.keyCode===116) document.getElementById('reload').click(); }; </script>
<input type="button" value="關閉" onclick="window.close()">
字符串參數限制 ~4KB。大數據用對象引用或 sessionStorage.setItem('key', JSON.stringify(data)) 子頁讀取。
function showModal(url, data) {
return new Promise((resolve, reject) => {
// 方案 A:
showModalDialog 返回值機制本質是同步阻塞 + 共享內存引用。核心技巧:傳遞對象引用實現雙向綁定,避免返回值大小限制和序列化開銷。新項目請使用 <dialog> + postMessage 或組件庫 Modal + Promise,獲得標準化、跨瀏覽器、非阻塞的等效體驗。