萬盛學電腦網

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

showModalDialog 模態對話框完整指南:用法、參數、跨瀏覽器相容與 Chrome 解決方案

什麼是 showModalDialog?

window.showModalDialog() 會開啟一個模態對話框:子視窗開啟期間,父視窗無法獲得焦點、無法操作,直到子視窗關閉。這與 window.open() 的非模態行為截然不同。

基本語法與參數詳解

vReturnValue = window.showModalDialog(sURL[, vArguments][, sFeature])
參數類型說明
sURLString (必填)對話框要載入的頁面 URL
vArgumentsVariant (選填)傳遞給子視窗的參數 (任意類型,含物件、陣列)。子視窗透過 window.dialogArguments 取得。
sFeatureString (選填)外觀設定,分號分隔。常用:
dialogWidth:400px; dialogHeight:300px; center:yes; resizable:no; status:no; scroll:no; help:no

完整範例:父視窗與子視窗雙向資料傳遞

父視窗 (parent.html)

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>父視窗</title></head>
<body>
    <input type="text" id="result" placeholder="等待子視窗回傳..." style="width:300px;">
    <button onclick="openDialog()">開啟模態對話框</button>

    <script>
        function openDialog() {
            // 傳遞參數物件給子視窗
            var args = { 
                title: '請輸入姓名', 
                defaultValue: '張三' 
            };
            
            var ret = window.showModalDialog('child.html', args, 
                'dialogWidth:400px; dialogHeight:200px; center:yes; resizable:no; status:no');
            
            // Chrome 相容處理:若 ret 為 undefined,嘗試讀取 window.returnValue
            if (ret === undefined) ret = window.returnValue;
            
            if (ret) {
                document.getElementById('result').value = ret;
            }
        }
    </script>
</body>
</html>

子視窗 (child.html)

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>子視窗</title></head>
<body>
    <h3><span id="title"></span></h3>
    <input type="text" id="inputVal">
    <button onclick="returnValue()">確定並關閉</button>

    <script>
        // 取得父視窗傳入的參數
        var args = window.dialogArguments;
        document.getElementById('title').innerText = args.title;
        document.getElementById('inputVal').value = args.defaultValue;

        function returnValue() {
            var val = document.getElementById('inputVal').value;
            
            // 標準方式:設定 returnValue
            window.returnValue = val;
            
            // Chrome 相容:同時設定 opener.returnValue
            if (window.opener) {
                window.opener.returnValue = val;
            }
            
            window.close();
        }
    </script>
</body>
</html>

瀏覽器相容性現況 (重要!)

瀏覽器支援備註
IE 4+✅ 完整支援原生實作
Firefox 3+✅ 支援需啟用 dom.disable_window_open_feature.modal 或使用 polyfill
Safari 5.1+✅ 支援
Chrome 37+❌ 已移除表現同 window.open(),非模態,returnValue 為 undefined
Edge❌ 不支援
Opera❌ 不支援
> ⚠️ 關鍵結論:showModalDialog 已被 Web 標準棄用,Chrome 37+、Edge、現代瀏覽器均不支援。**新專案嚴禁使用**,舊專案需儘快遷移。

現代替代方案

方案一:自訂 Modal 元素 (推薦,零依賴)

<!-- HTML -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <h3>標題</h3>
        <input type="text" id="modalInput">
        <button id="modalConfirm">確定</button>
    </div>
</div>

<style>
.modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; }
.modal-content { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:white; padding:20px; border-radius:8px; min-width:300px; }
</style>

<script>
function showCustomModal(title, defaultVal) {
    return new Promise((resolve) => {
        document.getElementById('myModal').style.display = 'block';
        document.querySelector('.modal-content h3').innerText = title;
        document.getElementById('modalInput').value = defaultVal;
        
        document.getElementById('modalConfirm').onclick = function() {
            resolve(document.getElementById('modalInput').value);
            document.getElementById('myModal').style.display = 'none';
        };
    });
}

// 使用方式 (async/await)
async function test() {
    var result = await showCustomModal('請輸入', '預設值');
    console.log('回傳:', result);
}
</script>

方案二:成熟 UI 函式庫

  • Bootstrap Modal:最普及,功能完整
  • SweetAlert2:美觀、Promise-based、支援輸入框
  • Layer (layui):國產輕量級,API 類似 showModalDialog

遷移檢查清單

  1. 搜尋專案所有 showModalDialog 呼叫點
  2. 評估是否需阻斷父視窗互動 (真模態) 或僅需視覺模態
  3. 選擇替代方案並統一介面 (建議 Promise-based)
  4. 處理 vArguments 傳遞邏輯改為參數注入
  5. 處理 returnValue 改為 Promise resolve / callback
  6. 測試跨瀏覽器、行動裝置相容性

總結

showModalDialog 曾是 IE 時代的特色 API,但已成為歷史遺物。現代 Web 開發應採用原生 Modal + Promise 或成熟 UI 庫,確保跨瀏覽器一致性、無障礙存取 (a11y) 與響應式設計支援。

copyright © 萬盛學電腦網 all rights reserved