window.open 打开新页面失效

在开发h5项目的时候 经常需要使用window.open 来打开新页面,但有时会出现失效的情况。
问题复现:
在接口请求完成后,根据返回的结果调用window.open 失效
原因:浏览器出于安全的考虑,会拦截掉非用户操作打开的新页面;实际上,在异步的方法中以及非用户操作打开的新页面都会被拦截(不同浏览器不同版本表现不同,不是所有情况都会被拦截,但是任然需要做兼容处理)
例如:

fetch(url,option).then(res=>{    
    window.open('http://www.test.com')
})
setTimeout(() => {
    window.open(this.url, '_blank')
}, 100)
。。。
if (success) window.open(data);

解决方案:
1、尽量让将调用window.open的方法 写在用户事件中,例如:

  if (success) {
          Dialog.alert({
            content: '即将跳转单证链接',
            onConfirm: () => {
              window.open(data);
            },
          });
        }

交互上的小修改,这样写需要用户手动确定才会跳转

2、 使用a标签进行跳转

ajax().then(res => {
	asyncOpen(res.url)
})

function asyncOpen(url) {
    var a = document.createElement('a')
    a.setAttribute('href', url)
    a.setAttribute("target", "_blank");
    a.setAttribute("download", 'name');
    document.body.appendChild(a);
    a.click();
    a.remove();
}


3、使用中转页面

一定要把window.open定义在接口请求的外部,保证新开空白窗口不会被拦截。
var newWin = window.open('loading page') 
ajax().then(res => {
	newWin.location.href = 'target url'
}).catch(() => {
	newWin.close()
})
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值