首页 > 解决方案 > JavaScript - 自定义 Google 登录必须点击两次

问题描述

这是 HTML:

            <div id="button_google_login" class="customGPlusSignIn" onclick="startApp();">
                <span class="dont_close" style="padding-left: 12px;">Sign In with Google</span>
            </div>

JavaScript:

  var googleUser = {};
  var startApp = function() {
    gapi.load('auth2', function(){
      // Retrieve the singleton for the GoogleAuth library and set up the client.
      auth2 = gapi.auth2.init({
        client_id: '[Secret].apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        // Request scopes in addition to 'profile' and 'email'
        //scope: 'additional_scope'
      });
      attachSignin(document.getElementById('button_google_login'));
    });
  };

  function attachSignin(element) {
    console.log(element.id);
    auth2.attachClickHandler(element, {},
        function(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()); // This is null if the 'email' scope is not present.
        }, function(error) {
          // error or break up
        });
  }

我需要单击两次按钮才能启动登录过程,可能是什么问题?我还尝试了普通的非自定义版本,它应该如何工作。

提前致谢!

标签: javascriptgoogle-oauthgoogle-signin

解决方案


我猜您从Google 文档中复制了示例。该startApp()函数在主体标签的末尾被调用。因此,当文档已加载时,将分配给 Google 按钮的点击处理程序。您更改了行为,仅当有人单击按钮时才分配单击处理程序。因此,您必须单击该按钮两次。

你为什么不想像谷歌提供的例子那样做呢?

只需<script>startApp();</script>在结束</body>标记之前添加并onclick="startApp();从按钮中删除属性。


推荐阅读