2012-04-26 181 views
1

我有'用Facebook登錄'按鈕,生成一個彈出窗口,要求用戶輸入FB憑證。如何阻止我的Facebook登錄彈出窗口出現,如果用戶已經登錄到FB?

在用戶已經加入我的應用程序,離開應用程序,然後回來(雖然仍然登錄到Facebook)的情況下,我希望用戶能夠點擊'用Facebook登錄',而不是顯示彈出窗口。

目前,鑑於上述情況,彈出窗口打開一秒,然後頁面重定向到應用程序的登錄狀態。

我已經實現了下面的代碼 - 我是一個完整的noob當涉及到Javascript,所以雖然答案可能很明顯,我不知道該怎麼做!

window.fbAsyncInit = function() { 
    FB.init({ 
     appId : '372191216164729', 
     status : true, // check login status 
     cookie : true, // enable cookies to allow the server to access the session 
     xfbml : true // parse XFBML 
    }); 
    }; 

    (function(d) { 
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all.js"; 
    d.getElementsByTagName('head')[0].appendChild(js); 
    }(document)); 

    $(function() { 
    $('#fb_connect').click(function(e) { 
     e.preventDefault(); 

     FB.login(function(response) {      
     if (response.authResponse) { 
      // $('#connect').html('Connected! Hitting OmniAuth callback (GET /auth/facebook/callback)...'); 

        //this might not be the best way to do this ... 
        $('#welcome_form').submit(); 
      // since we have cookies enabled, this request will allow omniauth to parse 
      // out the auth code from the signed request in the fbsr_XXX cookie 
      // $.getJSON('/auth/facebook/callback', function(json) { 
      //    $('#connect').html('Connected! Callback complete.'); 
      //    $('#results').html(JSON.stringify(json)); 
      //   }); 
     } 
     }, { scope: 'email, read_stream' }); 
    }); 
    }); 

回答

4

頁面加載後,以後你再加載並初始化FB SDK使用FB.getLoginStatus方法來檢查用戶狀態。 如果用戶已經登錄並授權您的應用程序,然後響應應該有訪問令牌,用戶ID等

例如:

FB.getLoginStatus(function(response) { 
    if (response.status === "connected") { 
     // use the response.authResponse 
    } 
    else if (response.status === "not_authorized") { 
     FB.login(function(response) { 
      ... 
     }, { scope: "email, read_stream" }); 
    } 
    else { 
     // user not logged in to facebook 
    } 
}); 
+0

謝謝!我的下一個問題是當你說//使用response.authResponse時要做什麼。我使用了一個名爲omniauth的Rails gem,它說omniauth應該能夠解析授權碼。考慮到這一點,我是否需要填寫上面的代碼(您已放置註釋的地方)? – ralphos 2012-04-26 22:37:36

+0

我不知道這是什麼* omniauth *的東西,我從來沒有使用鐵軌。但它聽起來像你正在嘗試實現[服務器端身份驗證](http://developers.facebook.com/docs/authentication/server-side/),但使用JavaScript這是一個客戶端端身份驗證。一旦進入「//使用response.authResponse」部分,用戶已經通過身份驗證,過程完成,您可以開始使用jd sdk進行api調用。如果你想在服務器中使用這種功能,那麼就使用服務器端的認證。 – 2012-04-26 22:43:12

+0

好的,謝謝,我想你已經給了我足夠的工作。感謝你的幫助。 – ralphos 2012-04-26 22:50:11

相關問題