window.open 被拦截的解决方法

4,722 阅读1分钟

一、拦截的原因

直接在回调事件中调用window.open()函数去打开一个新窗口,如果 window.open不处于异步中则可以直接进行跳转,如果处于异步中,浏览器处于安全策略的原因无法分辨出是因为人为点击触发还是脚本自动触发而打开的一些不安全的页面,所以新开的页面就会被拦截,对于不懂技术的人员来说,基本就可以断定这是一个bug。

二、解决方案

1、模拟a标签进行跳转


function openUrl() {
        let tempALink = document.createElement("a");
        
        tempALink.setAttribute("target", "_blank");
        
        tempALink.setAttribute("id", "openWin");
        
        tempALink.setAttribute("href", url);
        
        document.body.appendChild(tempALink);
        
        document.getElementById("openWin").click();
        
        document.body.removeChild(tempALink);   
    }
    

2、使用window.open() 模拟用户直接点击的行为骗过浏览器。如果觉得白页时间长可以修改标题增加过度等。

let tempWindow = window.open('','_blank');

异步.then((res) => {
    tempWindow.location = res.url;
}).catch(() => {
    tempWindow.close();
})