您的位置:首页 > 运维架构

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

2014-08-22 00:44 295 查看
背景

当前的浏览器为了保证用户体验,在很多场合下禁止了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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: