window.open 開啟新視窗後,新視窗可以透過 window.opener 取得開啟它的父視窗參考,進而對父視窗做操作。以下範例同時示範兩個方向:新視窗寫入自己的內容,並回頭寫入父視窗的內容。
<!DOCTYPE html>
<html>
<head>
<script>
function openWin() {
myWindow = window.open('', '', 'width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
// 透過 opener 取得父視窗並寫入內容
myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</head>
<body>
<input type="button" value="Open 'myWindow'" onclick="openWin()" />
</body>
</html>
同源限制。opener 取得的是一個視窗物件,若該視窗的來源與目前頁面不同,存取它的 document 會拋出跨域錯誤。跨來源情境請改用 postMessage 溝通。
document.write 會清空文件。父視窗若已載入完成,呼叫 document.write 等同於重新寫入整份文件,原有的 DOM、事件綁定與狀態都會消失。上例之所以「看起來正常」,是因為它出現在載入階段的行內 script 中。父視窗載入完成後請改用 DOM API:
myWindow.opener.document.getElementById("msg").textContent = "回來了";
opener 是安全風險。被開啟的頁面能透過 opener 取得你的視窗並將你導向釣魚網站(reverse tabnabbing)。因此使用 target="_blank" 時請加上 rel="noopener noreferrer";用 window.open 時,可在開啟後立刻 myWindow.opener = null; 切斷關聯。現代瀏覽器對 target="_blank" 已預設隱含 noopener,但寫出來更保險。
另外,window.open 若你不是由使用者點擊直接觸發(例如放在 setTimeout 或非同步回呼裡),會被瀏覽器的彈出視窗阻擋機制攔下。需要延後開啟時,請先開一個空視窗再設定其 location。