這個範例示範如何用 showModalDialog 開啟子視窗,並在兩個方向傳遞資料:父頁把物件傳給子頁,子頁再把使用者輸入回傳給父頁。
<html>
<head>
<title>主頁面</title>
<script language="javascript" type="text/javascript">
function OpenNew() {
var im = new IDAndMethod();
im.ID = document.getElementById("txtID").value;
window.showModalDialog("ddd.html", im, "");
}
function IDAndMethod() {
this.ID = "ddd";
this.Method = SetTxt; // 把回傳時要呼叫的函數一起帶過去
}
function SetTxt(str) {
document.getElementById("txtID").value = str;
}
</script>
</head>
<body>
<form action="#">
<input id="txtID" style="width:400px" type="text" value="XXX!在這裡輸入 ID!" /><br />
<input type="button" value="打開新的視窗" onclick="OpenNew()" />
</form>
</body>
</html>
<html>
<head>
<title>主頁面</title>
<script language="javascript" type="text/javascript">
var im;
function Load() {
im = window.dialogArguments; // 取得父頁傳來的物件
if (im.ID == "XXX!在這裡輸入 ID")
document.getElementById("txtID1").value = "你怎麼不輸入呢!";
else
document.getElementById("txtID1").value = im.ID;
}
function Set() {
im.Method(document.getElementById("txtID1").value); // 回呼父頁的函數
}
</script>
</head>
<body onload="Load()">
<form action="#">
<input id="txtID1" style="width:400px" type="text" value="ddd" /><br />
<input type="button" value="傳遞數據" onclick="Set()" />
</form>
</body>
</html>
這個技巧的巧妙之處在於:第二個參數傳入的物件不只是資料容器,還附帶了一個函數參照。子視窗呼叫 im.Method(...),等於直接執行父頁面的函數,形成雙向溝通。而 showModalDialog 的呼叫會阻塞父頁,直到子視窗關閉才繼續,因此流程上也近似同步。
但必須說明:showModalDialog 已被主流瀏覽器移除,這套寫法今天無法運行。現代做法有兩種。
若使用 window.open 開啟視窗,父子之間可直接透過 window.opener 與 opener 的 window 參照互動(需同源):
var child = window.open("ddd.html");
child.onload = function () {
child.document.getElementById("txtID1").value = "從父頁傳來的值";
};
若需要跨來源或更彈性的溝通,則應使用 postMessage:
// 父頁發送
child.postMessage({ id: "abc" }, "https://child.example.com");
// 子頁接收
window.addEventListener("message", function (e) {
if (e.origin !== "https://parent.example.com") return; // 務必驗證來源
document.getElementById("txtID1").value = e.data.id;
});
使用 postMessage 時,一定要驗證 e.origin,否則任何頁面都能對你的視窗送訊息,這是常見的安全疏失。