window.open被chrome浏览器阻止的问题

在js里的异步回调中调用window.open被浏览器拦截.

原因分析

  • 当浏览器检测到非用户操作产生的新弹出窗口,则会对其进行阻止。因为浏览器认为这不是用户希望看到的页面
  • 在chrome的安全机制里面,非用户触发的window.open方法,是会被拦截的。

解决方法

既然浏览器拦截的是非用户操作的window.open , 那么我们可以再click事件里直接执行window.open, 再在异步事件里给新打开的窗口链接值

click下的事件如下:

1
2
3
4
5
6
7
8
9
10
11
12
clickOpenUrl() {
let newWindow = window.open();
this.getUrl().subscribe(rs => {
this.wechatAuthUrl = rs.url;
// 如果成功给新窗口附链接值
newWindow.location.href = this.wechatAuthUrl;
}, _ => {
// 如果失败关闭新窗口
newWindow.close();
});

}