showModalDialog 是 IE 提供的一個強力方法,能在不離開主頁面的情況下打開一個「只能操作、無法返回父頁」的子窗口,並透過 returnValue 回傳數據。本文從概念、示例、參數到跨瀏覽器兼容逐一剖析。
它是 window 對象的一個方法,和 window.open 一樣打開新頁面,但不同點在於:showModalDialog 打開子窗口後,父窗口無法獲取焦點(無法操作)。子窗口可以透過設置 window.returnValue,把結果回傳給父窗口。
主窗口 main.html:
代碼如下:
<HTML>
<HEAD>
</HEAD>
<script>
function showmodal()
{
var ret=window.showModalDialog("sub.html?temp="+Math.random());
alert("sub return value is "+ret);
}
</script>
<BODY>
<INPUT id=button1 type=button value="open sub" name=button1 onclick="showmodal();">
</BODY>
</HTML>
子窗口 sub.html:
代碼如下:
<HTML>
<HEAD>
</HEAD>
<script>
function returnMain()
{
window.returnValue="return from sub";
window.close();
}
</script>
<BODY>
<INPUT id=button1 type=button value="return and close" name=button1 onclick="returnMain()">
</BODY>
</HTML>
特別說明:main.html 中在 URL 後拼接 Math.random(),目的是避免瀏覽器讀取緩存。
vReturnValue = window.showModalDialog(sURL[, vArguments][, sFeatures])
sURL(必選,字符串):對話框要顯示的文檔 URL。
vArguments(可選,變體):向對話框傳遞的參數,類型不限,包括數組、對象等;對話框內用 window.dialogArguments 接收。
sFeatures(可選,字符串):描述對話框外觀,多項以分號隔開,包括 dialogHeight(不小於 100px)、dialogWidth、dialogLeft、dialogTop、center、help、resizable、status、scroll 等,取值多為 yes/no 或 1/0。
並非所有瀏覽器都支持該方法。在 Chrome 中運行上述例子,父窗口仍可任意獲取焦點,效果等同 window.open,且得到的 returnValue 為 undefined。各主流瀏覽器支持情況大致如下:IE9、Firefox、Safari 支持模態對話框;Chrome 只是 open 了新窗體;Opera 則毫無反應。若傳入 vArguments 為 window,則 returnValue 只有 Chrome 返回 undefined,其餘瀏覽器都正常。
思路是:在 Chrome 中改用 window.opener.returnValue 來回傳值。子窗口返回時判斷 opener 是否存在:
代碼如下:
function returnMain()
{
if(window.opener!=undefined)
{
window.opener.returnValue = "return from sub";
}else{
window.returnValue = "return from sub";
}
window.close();
}
父窗口接收時也做兼容判斷:若 ret 為 undefined,則改讀 window.returnValue。此外,若父窗口的 returnValue 另有用途,可先備份再還原:var oldValue = window.returnValue; var newValue = showModalDialog(); window.returnValue = oldValue。
在 Chrome 下測試時,需要把 HTML 文件放到 Web 服務器(如 Tomcat)上,透過 http URL 訪問測試,否則用本地文件路徑直接打開會失敗。