打開彈窗後,主頁面常常需要知道「用戶什麼時候關掉了它」,以便刷新列表、恢復焦點或載入新數據。做法很簡單:用 setInterval 輪詢彈窗對象的 closed 屬性。
var win = window.open('foo.html', 'windowName',
"width=200,height=200,scrollbars=no");
var timer = setInterval(function () {
if (win.closed) {
clearInterval(timer); // 已關閉,停止輪詢
alert('closed');
}
}, 1000);
window.open 的返回值是打開窗口的引用,若被瀏覽器攔截則返回 null。因此健壯的代碼應先判空:
if (!win) {
alert('彈窗被瀏覽器攔截了,請允許本站彈出窗口');
return;
}
closed 是只讀布爾屬性,窗口被關閉後變為 true,這是我們唯一的判斷依據。
記得 clearInterval。 少了這一步,定時器會一直跑到頁面卸載,屬於典型的資源洩漏。
輪詢有 1 秒的延遲,也更耗資源。更好的做法是在彈窗內部掛一個卸載監聽,主頁面提供一個函數供其調用:
// 主頁面
function onPopupClosed() {
console.log('彈窗已關閉,刷新列表');
location.reload();
}
// 彈窗頁面 foo.html 中
window.addEventListener('beforeunload', function () {
if (window.opener && !window.opener.closed) {
window.opener.onPopupClosed();
}
});
這種方式即時且無需輪詢。不過要注意跨域場景下 window.opener 的訪問會受限,此時可用 postMessage 通信。
如今絕大多數「彈窗」需求其實用 <dialog> 元素加遮罩層就能實現,好處很明顯:始終處於同一文檔內,沒有被攔截的風險,關閉時直接觸發 close 事件,無需任何輪詢:
var dialog = document.querySelector('dialog');
dialog.showModal();
dialog.addEventListener('close', function () {
console.log('對話框已關閉');
});
只有在確實需要打開獨立瀏覽上下文(例如第三方頁面、支付流程)時,才值得使用 window.open。