萬盛學電腦網

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

JS showModalDialog 模態對話框用法詳解:參數傳遞、返回值、跨瀏覽器相容與替代方案

核心概念

window.showModalDialog() 開啟模態對話框:子視窗開啟時,父視窗凍結無法操作,直到子視窗關閉。支援雙向資料傳遞:父→子用 vArguments,子→父用 window.returnValue。

基本語法

var returnVal = window.showModalDialog(sURL[, vArguments][, sFeatures])

參數說明

  • sURL (必填):子視窗頁面 URL
  • vArguments (選填):傳給子視窗的任意資料,子視窗用 window.dialogArguments 接收
  • sFeatures (選填):外觀字串,分號分隔
    • dialogWidth:400px; dialogHeight:300px (單位建議用 px)
    • center:yes|no (預設 yes,置中)
    • resizable:yes|no (預設 no)
    • status:yes|no (預設 no)
    • scroll:yes|no (預設 yes)
    • help:yes|no (預設 yes)

完整範例:單一參數傳遞與返回

父視窗 (main.html)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>主視窗</title></head>
<body>
    <input type="text" id="txtResult" placeholder="等待回傳..." style="width:200px;">
    <button onclick="openSub()">開啟子視窗</button>

    <script>
        function openSub() {
            // 避免快取加上隨機數
            var url = 'sub.html?ts=' + Date.now();
            var ret = window.showModalDialog(url, '', 'dialogWidth:400px;dialogHeight:300px;center:yes;resizable:no;status:no');
            
            // Chrome 相容處理
            if (ret === undefined) ret = window.returnValue;
            
            if (ret) document.getElementById('txtResult').value = ret;
        }
    </script>
</body></html>

子視窗 (sub.html)

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>子視窗</title></head>
<body>
    <input type="text" id="txtInput" value="要傳回的值">
    <button onclick="sendBack()">傳回並關閉</button>

    <script>
        function sendBack() {
            var val = document.getElementById('txtInput').value;
            window.returnValue = val; // 標準方式
            
            // Chrome 相容:寫入 opener.returnValue
            if (window.opener) window.opener.returnValue = val;
            
            window.close();
        }
    </script>
</body></html>

進階:傳遞多個參數 (物件/陣列)

// 父視窗
var params = {
    userId: 123,
    userName: 'admin',
    roles: ['admin', 'editor'],
    config: { theme: 'dark', lang: 'zh-TW' }
};
var ret = window.showModalDialog('sub.html', params, 'dialogWidth:500px;dialogHeight:400px;');

// 子視窗
var args = window.dialogArguments;
console.log(args.userId);      // 123
console.log(args.roles[0]);    // 'admin'
console.log(args.config.theme); // 'dark'

// 子視窗修改參數物件,父視窗可同步取得 (物件傳參考)
args.config.theme = 'light'; // 父視窗的 params.config.theme 也會變成 'light'

瀏覽器相容性總表 (關鍵!)

瀏覽器模態行為dialogArgumentsreturnValue備註
IE 9+✅✅✅完整支援
Firefox⚠️ 需設定✅✅預設關閉,需 about:config 啟用或用 polyfill
Safari✅✅✅
Chrome 37+❌ 非模態✅❌ undefined已移除模態特性
Edge❌❌❌不支援

Chrome 兼容方案 (僅供舊專案維護)

核心思路:利用 window.opener.returnValue 當作橋樑。

父視窗修正

var ret = window.showModalDialog(url, args, features);
// Chrome 會回傳 undefined,改讀取 window.returnValue
if (ret === undefined) ret = window.returnValue;

子視窗修正

function closeAndReturn(val) {
    // 雙重保險
    window.returnValue = val;
    if (window.opener) window.opener.returnValue = val;
    window.close();
}
> ⚠️ **限制**:Chrome 必須在 HTTP/HTTPS 環境下測試 (localhost 或伺服器),file:// 協定無法運作。

現代替代方案:自訂 Modal + Promise (標準化、跨瀏覽器)

// 通用 Modal 開啟函數
function openModal(options) {
    return new Promise((resolve) => {
        // 建立 Modal DOM (略,參考 71107 文章方案一)
        // 設定標題、內容、預設值...
        
        document.getElementById('modalConfirm').onclick = () => {
            var val = document.getElementById('modalInput').value;
            closeModal();
            resolve(val);
        };
        document.getElementById('modalCancel').onclick = () => {
            closeModal();
            resolve(null);
        };
    });
}

// 使用方式
async function handleClick() {
    var result = await openModal({ title: '輸入姓名', default: '張三' });
    if (result) console.log('使用者輸入:', result);
}

常見問題 FAQ

  1. 模態視窗內表單送出不跳頁?:在子視窗放入隱藏 <iframe name="hiddenFrame">,表單 target="hiddenFrame"。
  2. Firefox 刷新子視窗 dialogArguments 丟失?:Firefox 特性,避免在子視窗刷新,或將參數存入 sessionStorage 共享。
  3. HTA 應用程式中使用?:HTA 享有較高權限,showModalDialog 行為較穩定,但仍建議遷移。

總結

showModalDialog 是 IE 時代的產物,已被 Web 標準淘汰。**新專案嚴禁使用**,舊專案應規劃遷移至自訂 Modal 或成熟 UI 庫 (Bootstrap Modal, SweetAlert2, Layer 等),以確保長期維護性與跨平台一致性。

copyright © 萬盛學電腦網 all rights reserved