舊系統要沿用 IE 時代的 showModalDialog 關閉方式,實測下來發現一件事:不能只依賴單一屬性回傳值,window.dialogArguments 需要再驗一次,否則在部分情境下會拿不到結果。
核心寫法如下:
function OKEnd(vals) {
if (vals == null) vals = "TRUE";
if (typeof (window.opener) == "undefined") {
if (typeof (window.dialogArguments) != "undefined") {
if (window.dialogArguments && window.dialogArguments != null) {
window.opener = window.dialogArguments;
if (window.opener && window.opener != null) {
window.opener.ReturnValue = vals;
}
}
}
} else {
if (window.opener && window.opener != null) {
window.opener.ReturnValue = vals;
}
}
window.returnValue = vals;
self.close();
}
接收端也只需在原本 IE 的寫法上多驗一次 opener:
// 選擇變更部門
function SetOrganizeTree2() {
var url = "彈出頁面";
var ret = window.showModalDialog(url, window,
"dialogWidth=400px;dialogHeight=500px;status=no;help=no;scroll=yes;resizable=yes;");
if (typeof (ret) == "undefined") {
ret = window.ReturnValue;
}
if (ret) {
document.getElementById("hidDeptCode2").value = ret;
document.getElementById("btnDeptCodeAdd").click();
}
return false;
}
第一步,開窗時把 window 本身當參數傳進去。
var result = window.showModalDialog(url, window,
"dialogWidth=" + width + "px;dialogHeight=" + height + "px;resizable:yes;");
if (typeof (result) == 'undefined') {
result = window.ReturnValue;
}
return result;
第二步,彈出頁中接收傳入的 window。
if (typeof (window.opener) == 'undefined') window.opener = window.dialogArguments;
第三步,關閉前寫回返回值。
window.returnValue = vals; if (window.opener && window.opener != null) window.opener.ReturnValue = vals; window.close();
Chrome 下,標準做法在彈出頁沒有回發(postback)時能正常回傳;一旦發生回發,返回值就掉了。多寫一道 opener 的賦值可以補上這個缺口。
IE 下標準做法偶爾會莫名取不到值,同樣可以靠這段邏輯救回。Firefox 未詳細測試,但由於走的是標準屬性,問題應該不大。
順帶留意一個容易寫錯的細節:範例中曾出現 window.retureValue 這樣的拼字失誤,多打了字母,屬性名寫錯是不會報錯的,只會靜靜地什麼都沒發生——這類問題排查起來特別費工,建議複製貼上時多看一眼。
值得說明的是,showModalDialog 早已被標準廢除,主流瀏覽器陸續移除支援。上述技巧適合維護既有系統,新專案請改用 window.open 搭配 postMessage,或以 <dialog> 元素實作,跨來源與跨瀏覽器的行為都更可控。