防止浏览器拦截的新窗口打开链接方案

背景

  当前的浏览器为了保证用户体验,在很多场合下禁止了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');
});

 

posted @ 2014-08-13 11:14  zernmal  阅读(830)  评论(3编辑  收藏  举报