防止浏览器拦截的window.open新窗口方案

背景

当前的浏览器为了保证用户体验,在很多场合下禁止了window.open打开新窗口,下面就给出一些方案,最大程度上的实现新窗口打开一个链接。

方案

复制代码

//打开新链接方法实现
function windowOpen(){
    var a = document.createElement("a");
    a.setAttribute("href", url);
    if(target == null){
        target = '';
    }
    a.setAttribute("target", target);
    document.body.appendChild(a);
    if(a.click){
        a.click();
    }else{
        try{
            var evt = document.createEvent('Event');
            a.initEvent('click', true, true);
            a.dispatchEvent(evt);
        }catch(e){
            window.open(url);
        }
    }
    document.body.removeChild(a);
}

//新窗口打开
windowOpen('http://niu.xunlei.com/', '_blank');
//当前窗口打开 
windowOpen('http://niu.xunlei.com/', '_self');

复制代码

思路

其实做法很简单,首先模拟A标签点击打开新窗口,若失败再直接调用window.open方法。

问题

目前无法在异步的情况下调用该方法。如下:

//以下做法将得不到期望的结果,会被浏览器阻止
$.get("http://www.a.com/ajax",function(){
    windowOpen('http://niu.xunlei.com/', '_blank');
});

本文为原创文章,转载请注明出处:http://www.cnblogs.com/zernmal/

原文地址:https://www.cnblogs.com/suizhikuo/p/3928412.html