← 中文资源

简体中文版本

window.open 探测弹窗拦截

window.open 返回 null 即弹窗被拦截:降级为同页跳转而非静默失败,并用 win.closed 轮询观察弹窗被用户或拦截器关闭。

阅读英文原文

实现说明

window.open 探测弹窗拦截的核心是函数 startOAuthPopup。

使用要点

  • 这是浏览器侧代码——window 在 Node 里解析不到。
  • 每一步打印都带着自己的标签:popup blocked; falling back、popup closed by user or blocker。

常见问题

「window.open 探测弹窗拦截」能在裸 Node.js 里跑吗?

不能——window 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

主要签名是 function startOAuthPopup(url)

核心语句

const poll = setInterval(() => {
  if (win.closed) {
    clearInterval(poll);
    console.log('popup closed by user or blocker');
  }
}, 500);

代码示例

// window.open returns null when the browser blocks the popup; a blocked
// origin or the user can also close it later — both paths need handling.
function startOAuthPopup(url) {
  const win = window.open(url, 'oauth', 'width=480,height=640');

  if (!win) {
    console.log('popup blocked; falling back');
    window.location.assign(url); // same-tab fallback instead of silence
    return null;
  }

  win.focus();
  const poll = setInterval(() => {
    if (win.closed) {
      clearInterval(poll);
      console.log('popup closed by user or blocker');
    }
  }, 500);
  return win;
}