問題現象
最近在做項目的時候碰到了使用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(); }