在开发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()
})
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐