JavaScript - 必须点击两次自定义 Google 登录

标签 javascript google-oauth google-signin

这是 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
        });
  }

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

提前致谢!

最佳答案

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

您为什么不想像 Google 提供的示例那样做呢?

只需添加 <script>startApp();</script>收盘前</body>标记并删除 onclick="startApp();来自按钮的属性。

关于JavaScript - 必须点击两次自定义 Google 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010110/

相关文章:

javascript - 节点和浏览器在 package.json 中的不同主要入口点

php - 定期从服务器端调用函数?

javascript - 我无法在 Dreamweaver 中使用 Javascript

javascript - Google platform.js 有时不会触发 onload 回调

node.js - 我无法在 heroku 中部署 google oauth 应用程序

google-apps-script - YouTube API 和品牌帐户

javascript - 新的 Google 登录服务按钮自定义

javascript - 可以使用 PHP 创建文件,但半小时后浏览器无法加载

google-api - 从 Google oauth2 API 获取错误 { "error": "invalid_grant", "error_description": "Token has been expired or revoked."}

android - Facebook 登录因 app-release.apk 崩溃