在主頁面開啟另一個視窗,讓使用者在裡面填資料,按下確定後關閉視窗,並把剛剛輸入的值帶回主頁面。這是表單類後台很常見的互動。
做法是透過 window.showModalDialog 開啟子視窗,該方法的回傳值就是子視窗寫入的 window.returnValue。這裡把回傳值當成陣列使用,第 0 項放名字、第 1 項放年齡,回來後分別填進兩個輸入框。
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gbk">
<title>主頁</title>
<script type="text/javascript">
function EntryPoint() {
var style = 'dialogHeight:600px;dialogWidth:800px;status:no;help:0;scrool:yes';
var a = window.showModalDialog('other.html', '', style);
if (a == undefined) {
a = window.returnValue;
}
if (a != null && a.length > 0) {
document.getElementById("name").value = a[0];
document.getElementById("age").value = a[1];
}
}
</script>
</head>
<body>
<input type="button" value="調用" onclick="EntryPoint()"/><br/>
<input type="text" name="name" id="name" /><br/>
<input type="text" name="age" id="age" />
</body>
</html>
子視窗把兩個輸入值塞進陣列,然後設法寫回開啟者的 returnValue,最後關閉自己。這裡有個跨瀏覽器的細節:Chrome 用 window.opener.returnValue,而 IE 的 showModalDialog 則是設在自己的 window.returnValue 上,所以用 window.opener 是否存在來分流。
<html>
<head>
<title>操作界面</title>
<meta http-equiv="content-type" content="text/html; charset=gbk">
<script type="text/javascript">
function postValue() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var a = new Array();
a[0] = name;
a[1] = age;
if (window.opener != undefined) {
//for chrome
window.opener.returnValue = a;
}
else {
window.returnValue = a;
}
window.close();
}
</script>
</head>
<body>
<input type="button" value="確定" onclick="postValue();"/><br/>
名字:<input type="text" name="name" id="name" /><br/>
年齡:<input type="text" name="age" id="age" />
</body>
</html>
實作過程中遇到一個問題:Chrome 裡 window.close() 對非腳本開啟的視窗是不生效的。最後靠 window.opener 的存在與否來解決 Chrome 與 IE 的衝突。
值得一提的是,showModalDialog 早已被標準廢棄,Chrome 與 Firefox 都已移除。現代的等價做法是 window.open 搭配 postMessage:子視窗用 opener.postMessage(data, origin) 回傳,主視窗掛 message 事件接收,記得一定要檢查 event.origin 是否在白名單內,否則等於把資料交給任何網站。