ajax回调中window.open弹出的窗口会被浏览器拦截的解决方法

存在问题:处理页面ajax请求过程中,异步请求成功后需要新开窗口打开 url,使用的是 window.open() 方法 来实现,最终都被浏览器拦截了。不会跳到对应的页面,如下

原因:浏览器之所以拦截新开窗口因为该操作不是用户主动触发的,它认为这是不安全的所以拦截了( _self 不会限制),即使 ajax 回调函数中执行 click 或者 submit 等用户行为(trigger('click')),浏览器也会认为不是由用户主动触发的,不能被安全执行,所以被拦截。

百度了很多方法:比如

1:下面两种封装的方法放到ajax中不起效

 (1)function newOpenWindow(url, id) { 

    var a = document.createElement(‘a‘);
    a.setAttribute(‘href‘, url);
    a.setAttribute(‘target‘, ‘_blank‘);
    a.setAttribute(‘id‘, id);
    // 防止反复添加
    if(!document.getElementById(id)) {
      document.body.appendChild(a);
    }
    a.click();
  }

 

(2)function newOpenWindow(url) {
    var a = $('<a href="'+url+'" target="_blank"></a>')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    a.dispatchEvent(e);
  }

 

2:通过定时器,无效(时间长短无关)

var newOpenWindow=window.open();
setTimeout(function(){
  newOpenWindow.location=locationurl;
}, 1000);

 

 

最终的解决方法如下

var newOpenWindow=window.open('about:blank');  // 在ajax外部先打开空白新窗口

 $.ajax({
    success:function(data){
       if(data){
          //window.open('http://www.jb51.net'); 这种方法会被浏览器拦截     (错误方法)
          newOpenWindow.location="http://www.baidu.com";  //异步成功之后再给新窗口的localtion赋值
     }
  }
 })

3:当遇到两层回调的时候,不用先弹页面的时候会出问题。

这次 解决方法:async:false, 把所有的请求都改成同步解决的,但是有隐患。

posted @ 2017-08-01 14:32  小_Li_Kelly_前端  阅读(1291)  评论(0编辑  收藏  举报