2016-02-27 154 views
0

我写这段代码。如果用户之前登录过,它可以正常工作,但如果用户没有登录到Facebook,他将被重定向到Facebook登录页面,并且在成功登录后,他重定向到之前在开发人员提供的页面。 facebook.com/app。在这种情况下,我无法获取用户信息。下面是我的代码:如何获取用户使用javascript登录Facebook时的信息

<html> 
<body> 
    <script> 
     var client_id = my_client_id; 
     var url  = 'http://localhost/myitems.html'; 
     var scope  = 'email,public_profile'; 

     window.fbAsyncInit = function() { 
      FB.init({ 
       appId  : client_id, 
       xfbml  : true, 
       status  : true, 
       version : 'v2.5' 
      }); 
     }; 

     (function(d, s, id){ 
      var js, fjs = d.getElementsByTagName(s)[0]; 
      if (d.getElementById(id)) {return;} 
      js = d.createElement(s); js.id = id; 
      js.src = "//connect.facebook.net/en_US/sdk.js"; 
      fjs.parentNode.insertBefore(js, fjs); 
     }(document, 'script', 'facebook-jssdk')); 

     function loginFacebook(){ 
      FB.getLoginStatus(handleLoginFacebook); 
     } 

     function handleLoginFacebook(res){ 
      if(res.status==='connected'){ 
       var user={}; 
       user.access_token=res.authResponse.accessToken; 

       FB.api('/me?fields=email,first_name,last_name,picture',function(res){ 
        alert(JSON.stringify(res)); 
        user.first_name = res.first_name; 
        user.last_name = res.last_name; 
        user.network  = 'facebook'; 
        user.image  = res.picture; 
        user.network_id = res.id; 
        user.deviceToken = 0; 
        user.email  = res.email; 
        loginSocial(user, function(data){ 
         var d=JSON.stringify(data); 
         alert(d); 
         d=JSON.parse(d); 

         if(d.success==true){ 
          store(d); 
          window.location='myitems.html'; 
         }else{ 
          window.location='index.html'; 
         } 
        }); 
       }); 
      }else{ 
       window.location='https://www.facebook.com/dialog/oauth/?client_id='+client_id+'&redirect_uri='+url+'&scope='+scope; 
      } 
     } 
    </script> 

    <button onclick='loginFacebook()'>Facebook Login</button> 
</body> 
</html> 

回答

0

你别的应该是这样的:

FB.login(function (response) { 
    //Get date here from the response.authResponse 
    //In 'scope:' declare the scope of information you need 
}, {scope: 'email, public_profile, user_friends', return_scopes: true}); 
+0

尼古拉,我要重新导向至Facebook登录页面,而不是弹出窗口。让我清楚。当用户点击它时,我有一个按钮,它们被重定向到Facebook登录页面。在Facebook上成功登录后,重定向到我的页面,现在这就是我需要的,意味着当前用户 – korush

相关问题