2013-05-03 87 views
11

當從服務器(如Twitter和Facebook)處理OAuth時,很可能會將用戶重定向到請求應用程序權限的URL。通常,點擊鏈接後,您通過AJAX將請求發送到服務器,然後返回授權URL。window.open沒有彈出窗口攔截器使用AJAX和操縱window.location

但是,當您在收到答案時嘗試使用window.open時,瀏覽器會阻止彈出窗口,使其無效。當然,你可以將用戶重定向到新的URL,但這會破壞用戶體驗,而且很煩人。你不能使用IFRAMES,但它們是不允許的(因爲你看不到地址欄)。

那麼該怎麼做呢?

回答

26

答案很簡單,並且可以跨瀏覽器工作,沒有任何問題。在進行AJAX調用時(我將在本例中使用jQuery),請執行以下操作。假設我們有一個帶有兩個按鈕的窗體,Login with TwitterLogin with Facebook

<button type="submit" class="login" value="facebook" name="type">Login with Facebook</button> 
<button type="submit" class="login" value="twitter" name="type">Login with Twitter</button> 

然後在魔術發生

$(function() { 
    var 
     $login = $('.login'), 
     authWindow; 

    $login.on('click', function (e) { 
     e.preventDefault(); 
     /* We pre-open the popup in the submit, since it was generated from a "click" event, so no popup block happens */ 
     authWindow = window.open('about:blank', '', 'left=20,top=20,width=400,height=300,toolbar=0,resizable=1'); 
     /* do the AJAX call requesting for the authorize URL */ 

     $.ajax({ 
      url: '/echo/json/', 
      type: "POST", 
      data: {"json": JSON.stringify({"url": 'http://' + e.target.value + '.com'})} 
      /*Since it's a jsfiddle, the echo is only for demo purposes */ 
     }) 
     .done(function (data) { 
      /* This is where the magic happens, we simply redirec the popup to the new authorize URL that we received from the server */ 
      authWindow.location.replace(data.url); 
     }) 
     .always(function() { 
      /* You can poll if the window got closed here, and so a refresh on the main page, or another AJAX call for example */ 
     }); 
    }); 
}); 

這裏的Javascript代碼是的jsfiddle http://jsfiddle.net/CNCgG/

的POC這是簡單而有效的:)

+0

這是一個非常好的解決方法,但如果您使用FB.ui()我不認爲它會工作。 – deathemperor 2013-05-13 07:10:26

+0

編輯:我的壞,我誤讀你的短語。是的,我認爲使用FB.ui是行不通的,因爲它只有在您可以將對話框重定向到新URL時纔有效。如果FB.ui有一個服務器端對應的,那麼它將工作。 – pocesar 2013-05-13 14:32:18

+1

這是一個非常簡單而有效的解決方法,確保ajax打開的彈出窗口獲得焦點。謝謝pocesar! – neokio 2013-10-09 08:42:23

8

嘗試增加異步:假的。它應該是工作

$('#myButton').click(function() { 
$.ajax({ 
    type: 'POST', 
    async: false, 
    url: '/echo/json/', 
    data: {'json': JSON.stringify({ 
     url:'http://google.com'})}, 
    success: function(data) { 
     window.open(data.url,'_blank'); 
    } 
}); 
}); 
+1

這使得它也可以在iOS上運行,謝謝 – comeOnGetIt 2015-05-18 23:16:54

+0

很高興知道它也適用於iOS ...感謝您指出這一點 – rajesh 2016-08-22 20:12:21

+0

,但這對於chrome /(ㄒoㄒ)/ ~~不適用 – C0de8ug 2016-08-24 13:31:31

相關問題