window.closedwindow.open() 返回的窗口引用對象擁有只讀屬性 closed,值為 true 表示該窗口已關閉,false 表示仍打開。
function openAndMonitor(url, name, features) {
const win = window.open(url, name, features);
if (!win) {
console.warn('彈窗被攔截');
return null;
}
const timer = setInterval(() => {
if (win.closed) {
clearInterval(timer);
console.log('彈窗已關閉');
onPopupClosed(); // 業務回調
}
}, 500); // 500ms 輪詢間隔,平衡實時性與性能
return win;
}
// 使用
const popup = openAndMonitor('/oauth/callback', 'oauth', 'width=500,height=600');
function onPopupClosed() {
// 輪詢授權結果、刷新頁面、執行後續邏輯
checkAuthStatus();
}
function openPopupPromise(url, name, features, timeout = 30000) {
return new Promise((resolve, reject) => {
const win = window.open(url, name, features);
if (!win) return reject(new Error('彈窗被攔截'));
const timer = setInterval(() => {
if (win.closed) {
clearInterval(timer);
resolve({ closed: true });
}
}, 500);
// 全局超時保護
setTimeout(() => {
if (!win.closed) {
clearInterval(timer);
win.close();
reject(new Error('彈窗超時未關閉'));
}
}, timeout);
});
}
// 使用
try {
await openPopupPromise('/pay/checkout', 'payment', 'width=400,height=600');
const result = await fetch('/api/payment/result').then(r => r.json());
if (result.paid) showSuccess();
} catch (e) {
showError(e.message);
}
若彈窗頁面同源或可控制代碼,用 postMessage 實現事件驅動,無需輪詢。
// 父頁面
const win = window.open('/child.html', 'child', 'width=400,height=300');
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted.example.com') return;
if (event.data.type === 'CHILD_READY') {
win.postMessage({ type: 'INIT_DATA', payload: { token: 'xxx' } }, event.origin);
} else if (event.data.type === 'CHILD_CLOSE') {
console.log('子頁面主動通知關閉', event.data.payload);
// 執行業務邏輯
}
});
// 子頁面 (child.html)
window.opener.postMessage({ type: 'CHILD_READY' }, 'https://parent.example.com');
window.addEventListener('message', (event) => {
if (event.data.type === 'INIT_DATA') {
initApp(event.data.payload);
}
});
function closeAndNotify() {
window.opener.postMessage({ type: 'CHILD_CLOSE', payload: { result: 'ok' } }, 'https://parent.example.com');
window.close();
}
// 1. 父頁面生成唯一 state,存入 sessionStorage
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);
const url = `https://auth.example.com?client_id=xxx&redirect_uri=${encodeURIComponent(origin + '/oauth/callback')}&state=${state}`;
// 2. 開啟彈窗
const popup = window.open(url, 'oauth', 'width=500,height=600');
// 3. 輪詢檢測關閉 + 監聽回調頁面 postMessage
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed);
// 彈窗關閉後,去後端查詢授權結果(或讀取 sessionStorage 由回調頁寫入)
checkAuthResult(state);
}
}, 500);
// 4. 回調頁面 (oauth/callback) 邏輯:
// - 驗證 state
// - 調用後端換取 token
// - window.opener.postMessage({ type: 'OAUTH_SUCCESS', token }, parentOrigin)
// - window.close()
| 問題 | 原因 | 解決 |
|---|---|---|
win.closed 在某些瀏覽器始終為 false |
跨域窗口引用受限、或瀏覽器 Bug | 同域用 postMessage;跨域改用輪詢 + 後端狀態查詢兜底 |
| 彈窗被瀏覽器攔截 | 非用戶直接點擊觸發、或瀏覽器策略 | 綁定在 click 事件中調用 window.open;引導用戶允許彈窗 |
| 移動端無彈窗概念 | iOS/Android 瀏覽器通常在新標籤頁打開 | 改用 location.href 跳轉 + 回調頁 window.close() 返回,或 WebView 內部處理 |
| 輪詢導致性能問題 | 間隔過短、大量定時器 | 間隔 500-1000ms;頁面隱藏時暫停輪詢 document.hidden |
window.opener 為 null |
跨域且無 rel="noopener"、或用戶手動複製鏈接打開 |
不依賴 opener,改用後端狀態輪詢或 URL 參數傳遞 |
win.closed 輪詢是通用兜底方案,簡單可靠,適用於所有同域/跨域彈窗監控。openPopupPromise 工具函數,統一錯誤處理、超時、清理邏輯,業務代碼保持乾淨。