如果用户已登录FB,如何阻止我的Facebook登录弹出窗口出现?

时间:2012-04-26 22:00:05

标签: javascript facebook ruby-on-rails-3 omniauth

我有一个'登录Facebook'按钮,会生成一个弹出窗口,要求用户输入FB凭据。

如果用户已加入我的应用程序,离开应用程序然后返回(同时仍然登录Facebook),我希望用户能够点击“使用Facebook登录”而不显示弹出窗口。

目前,鉴于上段中的情况,弹出窗口打开一秒钟,然后页面重定向到应用程序的登录状态。

我已经在下面实现了以下代码 - 当谈到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' });
     });
   });

1 个答案:

答案 0 :(得分: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
    }
});