JavaScript - пользовательский вход в Google должен быть нажат дважды - PullRequest
1 голос
/ 19 сентября 2019

Это 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
        });
  }

Мне нужно дважды нажать кнопку, чтобы начать процесс входа, в чем может быть проблема?Я также попробовал обычную нестандартную версию, и она работала так, как и должна.

Заранее спасибо!

Ответы [ 2 ]

1 голос
/ 19 сентября 2019

Я бы на onClick событие на btn, а затем вызвать login функцию

function login() {
              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.
} 
1 голос
/ 19 сентября 2019

Полагаю, вы скопировали пример из Документация Google .Там функция startApp() вызывается в конце тега тела.Поэтому обработчик щелчка для кнопки Google назначается после загрузки документа.Вы изменили поведение, поскольку обработчик щелчков назначается только тогда, когда кто-то нажимает кнопку.Из-за этого вам нужно нажать эту кнопку два раза.

Почему бы вам не сделать это, как в примере, представленном Google?

Просто добавьте <script>startApp();</script> перед закрытием </body> Отметьте и удалите атрибут onclick="startApp(); со своей кнопки.

...