一般我們討論的是父視窗控制彈出視窗,但反過來也做得到。每個由 window.open() 開啟的視窗,都有一個 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();
// 從彈出視窗寫入父視窗
myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</head>
<body>
<input type="button" value="Open 'myWindow'" onclick="openWin()" />
</body>
</html>
範例中 myWindow.opener 就是目前的頁面,因此能直接對它的 document 進行操作。這個機制常被用來做「小視窗選值、選完回填到主視窗表單」的互動。
opener 是一把雙面刃。若你的頁面被以 window.open 開啟,對方頁面就能透過 window.opener.location = 'phishing-site.com' 把你的頁面導向偽造網站——這是 reverse tabnabbing 攻擊的原理。
因此開啟外部連結時,務必加上 noopener:
<a href="https://example.com" target="_blank" rel="noopener noreferrer">連結</a>
window.open('https://example.com', '_blank', 'noopener');
加上 noopener 之後,新視窗的 window.opener 會是 null,雙向都無法互相操作。現代瀏覽器對 target="_blank" 多已預設隱含 noopener 行為,但明確寫出來仍是好習慣。
若父子視窗屬於不同來源(origin,即通訊協定+網域+連接埠三者不同),大部分的屬性存取都會被同源政策擋下,只有極少數如 location(只能寫入導向)例外。這種情況下要溝通,請改用 postMessage():
// 傳送
otherWindow.postMessage({ type: 'SELECTED', value: 42 }, 'https://trusted.example');
// 接收端務必驗證來源
window.addEventListener('message', function (e) {
if (e.origin !== 'https://trusted.example') return;
// 處理 e.data
});
記得永遠要驗證 e.origin,否則任何網站都能對你的頁面發訊息。