0


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()})
标签: javascript ajax 前端

本文转载自: https://blog.csdn.net/MissXu666/article/details/129210313
版权归原作者 MissXu666 所有, 如有侵权,请联系我们删除。

“window.open 打开新页面失效”的评论:

还没有评论