解决弹出的窗口window.open会被浏览器阻止的问题

问题现象

最近在做项目的时候碰到了使用window.open被浏览器拦截的情况,有时候会一直连接,有时候会偶尔拦截,

尝试了很多方法,走了很多弯路,总结一下结果分享大家

原因分析&深入研究

1 当浏览器检测到非用户操作产生的新弹出窗口,则会对其进行阻止。因为浏览器认为这不是用户希望看到的页面

2 在chrome的安全机制里面,非用户触发的window.open方法,是会被拦截的。

复制代码
var btn = $('#btn');
btn.click(function () {
    //不会被拦截
    window.open('http://cssha.com')
});
复制代码

如上  window.open是用户触发的时候,是不会被拦截的,可以正常打开新窗口

复制代码
var btn = $('#btn');
btn.click(function () {
    $.ajax({
        url: 'ooxx',
        success: function (url) {
            //会被拦截
            window.open(url);
        }
    })
});
复制代码

如上 用户没有直接出发window.open,而是发出一个ajax请求,window.open方法被放在了ajax的回调函数里,这样的情况是会被拦截的

解决方案

先弹出一个页面,再进行ajax请求,这样就不会被拦截, 实例代码如下

复制代码
var btn = $('#btn');
btn.click(function () {
    //打开一个不被拦截的新窗口
    var newWindow = window.open();
    $.ajax({
        url: 'ooxx',
        success: function (url) {
            //修改新窗口的url
            newWindow.location.href = url;
        }
    })
});
复制代码

继续进行优化

复制代码
var btn = $('#btn');
btn.click(function () {

    //打开一个不被拦截的新窗口
  var adPopup = window.open('about:blank', '_blank','width='+window.screen.width+',height='+window.screen.height+', ...');
    $.ajax({
        url: 'ooxx',
     type:'post',
     dataType:'json',
        success: function (url) {
            //修改新窗口的url
       adPopup.blur();
       adPopup.opener.focus();
       adPopup.location = url;

        }
    })
});
复制代码

附带其他弹框方式

复制代码
//a标签动态click
function newWin(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();
  }
 //定时弹框 setTimeout('window.open(url);', 1);

//I LIKE THIS
function openwin(url) {
    var a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("target", "_blank");
    a.setAttribute("id", "openwin");
    document.body.appendChild(a);
    a.click();
} 

猜你喜欢

转载自blog.csdn.net/qq_37838223/article/details/80671161
今日推荐