萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 檢測彈出窗口是否已關閉:window.closed 輪詢與事件驅動方案

核心屬性:window.closed

window.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();
}

進階:Promise 封裝(現代異步風格)


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 雙向通信(替代輪詢)

若彈窗頁面同源或可控制代碼,用 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();
}

跨域場景:OAuth/支付回調標準模式


// 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 參數傳遞

現代替代:Web Authentication API / Payment Request API

  • WebAuthn:無密碼認證,瀏覽器原生彈窗,無需手動 window.open。
  • Payment Request API:標準化支付流程,瀏覽器原生 UI。
  • OAuth 2.0 PKCE + 系統瀏覽器標籤頁:移動端最佳實踐,避免 WebView/彈窗問題。

總結

  • win.closed 輪詢是通用兜底方案,簡單可靠,適用於所有同域/跨域彈窗監控。
  • 同域/可控子頁面:postMessage 事件驅動 更優雅、實時、低資源佔用。
  • OAuth/支付等關鍵流程:彈窗關閉檢測 + 後端狀態查詢 雙重保障,不信任前端單向通知。
  • 移動端優先考慮標籤頁跳轉 / 系統瀏覽器 / 原生 SDK,避開彈窗不可靠問題。
  • 封裝通用 openPopupPromise 工具函數,統一錯誤處理、超時、清理邏輯,業務代碼保持乾淨。
copyright © 萬盛學電腦網 all rights reserved