用 window.open() 打開新窗口後,子頁面需要回調打開它的父窗口,靠的是 opener 對象。前提是父窗口上確實定義了對應的方法。
<!DOCTYPE HTML PUBLIC "-//IETF//DTD LEVEL1//EN">
<html>
<head>
<title>html.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<button id="btn">open new page</button>
</div>
<script>
window.onload = function () {
var btn = document.getElementById("btn");
btn.onclick = openPage;
function openPage() {
try {
window.open('newpage.html');
} catch (e) {
alert(e);
}
}
};
// 供子頁面調用的方法
function show() {
document.title = new Date();
}
</script>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD LEVEL1//EN">
<html>
<head>
<title>newpage.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<button id="btn" onclick="fun()">單擊</button>
<script>
function fun() {
opener.show();
}
</script>
</body>
</html>
瀏覽器為每個由 window.open() 開啟的窗口維護一個 opener 屬性,指向打開它的源窗口。子頁面通過 opener.show() 就能直接調用父窗口的全局函數,本例中效果是把父窗口的標題改為當前時間。
有幾個實踐細節值得注意。
opener 可能為 null。如果子頁面被用戶直接打開、或從收藏夾進入,opener 就不存在,直接調用會拋錯。應寫成 if (window.opener && typeof window.opener.show === 'function') window.opener.show();。
同源限制。跨域情況下 opener 對象的大部分屬性都不可訪問,這種調用方式只適用於同源頁面。跨域通信應改用 postMessage。
安全方面的考量。現代瀏覽器已引入 rel="noopener" 機制,通過帶此屬性的鏈接打開的頁面 opener 為 null,這正是為了防止惡意頁面通過 opener 操縱源頁面(反向 tabnabbing)。此外,window.open() 建議顯式傳入第三個參數並加上 noopener,例如 window.open('newpage.html', '_blank', 'noopener')。
與 iframe 場景的區別。如果是 iframe 而非新窗口,調用父頁面應使用 window.parent(多層嵌套用 window.top),並注意同源策略的限制。兩者容易混淆,選錯對象是常見的入門困惑。
時序問題。父窗口的 show 定義在 window.onload 之外的頂層,所以子頁面無論何時調用都能找到它。若把方法定義在 onload 內部,子頁面在父窗口加載完成前調用就會失敗,這一點與前一篇討論的加載順序問題同源。