window.open()彈窗被瀏覽器攔截

什麼狀況下會彈窗被攔截

當window.open爲用戶觸發事件內部或者加載時,不會被攔截,一旦將彈出代碼移動到ajax或者一段異步代碼內部,立刻就出現被攔截。
obj.onclick = function(){
         window.open(url)     // 會被攔截
    }
    
    
    obj.onclick = function () {
        ajax({
            url: '/xxxxxx/',
            success: function (url) {
                window.open(url);  //會被攔截
             }
        })
    }
});  

解決

obj.onclick = function () {
        var newWindow = window.open();  //先在回調函數以前打開新窗口,後再加載url
        ajax({
            url: '/xxxxxx/',
            success: function (url) {
                newWindow.location.href = url;
            }
        })
    }
相關文章
相關標籤/搜索