showModalDialog 是 IE 家族提供的 window 方法,用來開啟一個「模態」子視窗。它和 window.open() 最大的差別在於:模態視窗開啟後,父視窗會失去焦點、無法操作,直到子視窗關閉。這讓它非常適合做資料挑選、確認視窗這類必須取得使用者回覆才能繼續的互動。
子視窗只要設定 window.returnValue,父視窗就能取得回傳值:
<!-- main.html -->
<script>
function showmodal() {
// 加上 Math.random() 是為了避免快取
var ret = window.showModalDialog("sub.html?temp=" + Math.random());
alert("sub return value is " + ret);
}
</script>
<input id="button1" type="button" value="open sub" onclick="showmodal();">
<!-- sub.html -->
<script>
function returnMain() {
window.returnValue = "return from sub";
window.close();
}
</script>
<input id="button1" type="button" value="return and close" onclick="returnMain()">
vReturnValue = window.showModalDialog(sURL[, vArguments][, sFeatures])
window.dialogArguments 接收。常用的 sFeatures 設定包括:dialogHeight(高度,不建議小於 100px)、dialogWidth、dialogLeft、dialogTop、center、help、resizable、status、scroll。另有 dialogHide、edge、unadorned 主要用於 HTA,一般網頁較少使用。
建議一律以 px 為單位:IE4 預設单位是 em,IE5 之後才是 px,寫死單位可避免版本差異造成的尺寸錯亂。
這是使用這個 API 最必須評估的一點。大致情況如下:
window.open(),且 returnValue 回傳 undefined。另一個要注意的細節是:Firefox 下若子視窗被重新整理,window.dialogArguments 會變成 undefined。
思路是改借用父視窗的 returnValue 作為溝通管道。子視窗優先嘗試寫入 window.opener.returnValue,父視窗則在偵測到 undefined 時改讀自己的 returnValue:
<!-- main.html -->
<script>
function showmodal() {
var ret = window.showModalDialog("sub.html?temp=" + Math.random(), window);
// for Chrome
if (ret == undefined) {
ret = window.returnValue;
}
alert("sub return value is " + ret);
}
</script>
<!-- sub.html -->
<script>
function returnMain() {
if (window.opener != undefined) {
window.opener.returnValue = "return from sub";
} else {
window.returnValue = "return from sub";
}
window.close();
}
</script>
如果父視窗本身的 returnValue 另有用途,可以用暫存的方式還原:
var oldValue = window.returnValue;
var newValue = showModalDialog();
window.returnValue = oldValue;
第一,測試 Chrome 的行為時,務必把 html 檔放在 web server(如 Tomcat)上透過 http 網址存取;直接用 file:// 開啟往往測不出正確結果。
第二,也是更根本的建議:在新專案中請不要採用 showModalDialog。它已被標準移除,僅存在於舊 IE 的相容需求場景。今日的對等方案是 <dialog> 元素搭配 showModal(),或任何成熟的 Modal 元件;需要回傳資料時用 Promise 或回呼函式處理,跨瀏覽器行為一致,也不必再寫相容分支。