Js打开新窗口拦截问题整理

一.js打开新窗口,经常被拦截

//js打开新窗口,经常被拦截
//指定本窗口打开,可以使用
window.open('http://www.tianma3798.cn', '_self');
//不指定或指定新窗口打开被拦截
window.open('http://www.tianma3798.cn');
window.open('http://www.tianma3798.cn', '_blank');

二、

1.如果是用户点击操作,打开新窗口不被拦截

2.如果在ajax回调函数中调用打开新窗口会被拦截

<a href="#" id="a">AAAAA</a>
<input type="button" id="btn" value="Open Baidu" onclick="openwin();" />
<script>
    //如果在ajax回调函数中调用打开新窗口会被拦截
    //如果是用户点击操作,打开新窗口不被拦截

    //可以打开新窗口
    document.getElementById('a').onclick = function () {
        window.open('http://segmentfault.com');
        return false;
    };
    //可以打开新窗口
    function openwin() {
        var url = "http://www.baidu.com";
        var a = document.createElement("a");
        a.setAttribute("href", url);
        a.setAttribute("target", "_blank");
        a.setAttribute("id", "openwin");
        document.body.appendChild(a);
        a.click();
    }
    //其他事件中,触发打开新窗口
    $(window).click(function () {
        //$('#a').trigger('click');
        openwin();
    });
</script>

三、Ajax毁掉函数中,打开新窗口解决方案

$(window).click(function () {
    //Ajax 请求毁掉函数中打开新窗口
    var w = window.open();
    $.get('../view/test.html', function (data) {
        w.location.href = '../view/test.html';
    })
});
原文地址:https://www.cnblogs.com/tianma3798/p/5461266.html