.attachClickHandler()在页面刷新/重定向时不起作用 [英] .attachClickHandler() does not work on page refresh/redirect

查看:0
本文介绍了.attachClickHandler()在页面刷新/重定向时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在index.html中实现一个定制的Google登录按钮,它在页面加载时工作得很好,但在页面重新加载或从另一个页面重定向时却不能。在页面加载时,控制台语句1、2和3自动按顺序打印,4在登录时打印。当从另一个页面重定向或刷新时,控制台仅打印1和2,并且该按钮不可点击。

包含要包含GAPI的脚本
<script src="https://apis.google.com/js/api:client.js"></script>

在index.html中。我正在使用AngularJS,如果这与此有关的话。

  var googleUser = {};
  var startApp = function() { 
  console.log("1");
gapi.load('auth2', function(){
  // Retrieve the singleton for the GoogleAuth library and set up the client.
  console.log("2");
  auth2 = gapi.auth2.init({
    client_id: '*************.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    scope: 'profile email'
  });
  setTimeout(function(){
  attachSignin(document.getElementById('g_login'));
}, 1000);
  // attachSignin(document.getElementById('g_login'));
});
  };

function attachSignin(element) {
console.log("3");
auth2.attachClickHandler(element, {},
    function(googleUser) {
      console.log("4");
      document.getElementById('name').innerText = "Signed in: " +
          googleUser.getBasicProfile().getName();
      angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
    }, function(error) {
      alert(JSON.stringify(error, undefined, 2));
    });
  }
startApp();
</script>

推荐答案

已解决。

全局变量‘auth2’在每次加载页面时自动初始化,可用于用户登录。

脚本调用方式为:

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

<script>
var auth2;
var googleUser = {};
var auth3;

window.onLoadCallback = function(){
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
    client_id: '**********.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    scope: 'profile email'
  });

auth3 = true;
startApp();
})

}

var startApp = function() {


  element = document.getElementById('g_login');
  auth2.attachClickHandler(element, {},
function(googleUser) {
    console.log("4");
  document.getElementById('name').innerText = "Signed in: " +
      googleUser.getBasicProfile().getName();
  angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
    console.log("5");
  alert(JSON.stringify(error, undefined, 2));
});
};

if (auth3)
 startApp();

</script>

这篇关于.attachClickHandler()在页面刷新/重定向时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆