检查返回的用户。谷歌登录会话(JavaScript)

问题描述:

我正在尝试使用他们的新API实现Google登录:https://developers.google.com/identity/sign-in/web/
登录,注销和显示用户数据均正常工作。
我很难让我的网页记住用户在刷新页面或离开网站并返回时登录。我想显示(例如在控制台中)用户数据,隐藏按钮等。
看来我必须使用listeners作为explained here, and marked as solved,但仍然无法使其工作。
这是我目前的工作:检查返回的用户。谷歌登录会话(JavaScript)

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://apis.google.com/js/platform.js" async defer></script> 
    <meta name="google-signin-client_id" content="***.apps.googleusercontent.com"> 

    <script type="text/javascript">  
    function onSignIn(googleUser) { 
    var profile = googleUser.getBasicProfile();  
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. 
    console.log('Name: ' + profile.getName()); 
    console.log('Image URL: ' + profile.getImageUrl()); 
    console.log('Email: ' + profile.getEmail()); 
    } 
    function signOut() { 
    var auth2 = gapi.auth2.getAuthInstance();  
     auth2.disconnect().then(function() {   
     console.log('User signed out.'); 
    }); 
    } 
    </script> 

</head> 
<body> 
    <div id="but" class="g-signin2" data-onsuccess="onSignIn"></div> 
    <a href="#" onclick="signOut();">Sign out</a> 
</body> 
</html> 

正如我已经在这里一段时间,才会真正apreciate一个完整的工作示例。谢谢!

看起来您在加载platform.js时缺少回调并且未初始化您的客户端。更改包括到:

<script src="https://apis.google.com/js/client:platform.js?onload=startApp" async defer></script> 

然后你就可以在的startApp执行任何初始化后的步骤,例如:

function startApp() { 
    gapi.load('auth2', function() { 
    gapi.client.load('plus','v1').then(function() { 
     gapi.signin2.render('signin-button', { 
      scope: 'profile', 
      fetch_basic_profile: false }); 
     gapi.auth2.init({fetch_basic_profile: false, 
      scope:'profile'}).then(
      function(){ 
       console.log('init'); 
       auth2 = gapi.auth2.getAuthInstance(); 
       auth2.isSignedIn.listen(function() { 
        console.log(auth2.currentUser.get()); 
       }); 
       auth2.then(function(resp){ 
        console.log(auth2.currentUser.get()); 
       }); 
      }); 
    }); 
    }); 
} 

我放在一起a demo here

+0

是的。我忘了你提到的第一行。 感谢您的演示,但我的优先考虑是不要使用Google+登录,因为有关“圈子”的权限无法消除并且会让一些用户恼火。 无论如何,你的演示可能会有所帮助。似乎我需要实施[从Google+登录](https://developers.google.com/identity/sign-in/web/quick-migration-guide) 如果可以,将发布完整代码并检查您的答案如解决。 – Bernard

+0

要排除Google+,您只需更改范围,我更新了示例代码。请注意,当您不使用Google+范围时,该按钮呈现为蓝色而不是红色。 – class