ajax回調中window.open彈出的窗口會被瀏覽器攔截的解決方法

 

 

存在問題:處理頁面ajax請求過程當中,異步請求成功後須要新開窗口打開 url,使用的是 window.open() 方法 來實現,最終都被瀏覽器攔截了。不會跳到對應的頁面,以下ajax

緣由:瀏覽器之因此攔截新開窗口由於該操做不是用戶主動觸發的,它認爲這是不安全的因此攔截了( _self 不會限制),即便 ajax 回調函數中執行 click 或者 submit 等用戶行爲(trigger('click')),瀏覽器也會認爲不是由用戶主動觸發的,不能被安全執行,因此被攔截。瀏覽器

百度了不少方法:好比安全

1:下面兩種封裝的方法放到ajax中不起效app

 (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(); 
  }async

 

(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:經過定時器,無效(時間長短無關)post

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

 

 

最終的解決方法以下spa

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, 把全部的請求都改爲同步解決的,可是有隱患。

相關文章
相關標籤/搜索