如何调用 google 的 getBasicProfile() 来仅单击按钮即可登录 google?

2024-05-17

我在我的网站上使用谷歌登录:

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

<script>
    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('Image URL: ' + profile.getImageUrl());
      //console.log('Name: ' + profile.getName());
      //console.log('Email: ' + profile.getEmail());
      var user_uname = profile.getName();
      var user_email = profile.getEmail();
      alert(user_uname);
    }

</script>

这是登录谷歌的按钮:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

我想为用户提供谷歌登录功能,但问题是每当页面加载时 onSignIn() 函数都会自动调用。 我只需要单击按钮即可。有谁能够帮助我?


最佳解决方案是仅在用户未登录时呈现登录按钮。

<html>
<head>
   <meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
  <script>
    function onSignIn(googleUser) {
      var profile = googleUser.getBasicProfile();
      var user_name = profile.getName();
      alert(user_name);
    }

    function onLoad() {
      gapi.load('auth2,signin2', function() {
        var auth2 = gapi.auth2.init();
        auth2.then(function() {
          // Current values
          var isSignedIn = auth2.isSignedIn.get();
          var currentUser = auth2.currentUser.get();

          if (!isSignedIn) {
            // Rendering g-signin2 button.
            gapi.signin2.render('google-signin-button', {
              'onsuccess': 'onSignIn'  
            });
          }
        });
      });
    }
  </script>

  <div id="google-signin-button"></div>

  <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何调用 google 的 getBasicProfile() 来仅单击按钮即可登录 google? 的相关文章

随机推荐