用 window.open() 開新視窗時,如何把資料送回母視窗?和模態對話框不同,window.open 沒有 returnValue 這種內建機制,必須靠 window.opener 反向操作。以下用兩個頁面完整示範。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>母視窗</title>
<script type="text/javascript">
function winOpen() {
window.open("test2.php", "", "height=400, width=400");
}
</script>
</head>
<body>
<textarea id="text1" name="text1"></textarea>
<input type="button" value="submit" name="submit" onclick="javascript:winOpen();" />
</body>
</html>
<script type="text/javascript">
function winBack() {
if (window.opener) { // 一定要先判斷
var fWindowText1 = window.opener.document.getElementById("text1");
fWindowText1.value = fWindowText1.value + "mayongzhan";
window.close();
}
}
</script>
<input type="button" name="back" value="back" onclick="javascript:winBack();" />
點擊 back,子視窗把文字追加到母視窗的 textarea,然後關閉自己。這裡的 if (window.opener) 判斷並非多餘——若母視窗已被關掉,opener 會是 null,直接取用就會報錯。
window.open(sURL, sName, sFeatures, bReplace);
sURL(選填):要載入的頁面網址,不指定則開啟 about:blank。
sName(選填):視窗名稱,可用於 form 或 a 標籤的 target。除自訂名稱外,也可使用特殊值:_blank(新視窗)、_parent(父框架)、_self(取代目前頁)、_top(最外層)。
sFeatures(選填):視窗外觀設定,多項以逗號分隔。
bReplace(選填):true 表示新文件寫入歷史紀錄尾端,false 則覆蓋當前文書的歷史位置。
height / width:視窗高寬,最小值為 100。top / left:相對於桌面的座標,單位為像素。location、menubar、toolbar、status、scrollbars、resizable:控制各項介面元件是否顯示,預設皆為 yes。fullscreen:全螢幕,會隱藏標題欄與選單,使用時務必在頁面內提供關閉入口。directories:是否顯示「連結」按鈕,預設 yes。channelmode:頻道模式,預設 no。titlebar:僅在 HTA 或受信任的對話框中有效。1. 未列出的裝飾一律關閉。當你指定了 sFeatures,凡是沒出現在清單中的項目都會被設為 no。也就是說只寫 "height=400,width=400",就會得到一個沒有工具列、沒有網址列、不可縮放的視窗。要保留某些元素,就必須明確寫出。
2. 返回值是新 window 物件的引用。var w = window.open(...) 之後可用 w.closed 判斷是否已關閉,或 w.focus() 把焦點切回去。
需要「一定要使用者回覆才能繼續」的流程,模態對話框語意更貼切;但考量跨瀏覽器相容性,window.open 加 opener 回寫反而更可靠。此外,若頁面會被瀏覽器阻擋彈窗(例如非由使用者點擊直接觸發),可先開一個空白視窗取得引用,再設定其 location,成功率會更高。