gapi未定义 - 谷歌与gapi.auth2.init签订了问题 [英] gapi is not defined - Google sign in issue with gapi.auth2.init

查看:167
本文介绍了gapi未定义 - 谷歌与gapi.auth2.init签订了问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施Google登录并检索用户的个人资料信息。
错误是:未捕获的ReferenceError:未定义gapi。这是为什么?

I'm trying to implement Google Sign In and retrieve the profile information of the user. The error is: Uncaught ReferenceError: gapi is not defined. Why is that?

<!doctype html>
<html>
<head>      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
    <script type="text/javascript">
    $(function(){
        gapi.auth2.init({
            client_id: 'filler_text_for_client_id.apps.googleusercontent.com'
        });
    });
</head>
<body>
</body>
</html>


推荐答案

这是因为你有脚本标记上的async defer 属性。 gapi 将在您的脚本标记后加载 gapi.auth2.init ...

It happens because you have async and defer attributes on your script tag. gapi would be loaded after your script tag with gapi.auth2.init...

要在执行此代码之前等待 gapi ,您可以在脚本标记中使用onload query param,如下所示:

To wait for gapi before executing this code you can use onload query param in script tag, like following:

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script>
<script>
window.onLoadCallback = function(){
  gapi.auth2.init({
      client_id: 'filler_text_for_client_id.apps.googleusercontent.com'
    });
}
</script>

或者,如果您在很多地方需要它,您可以使用promises来更好地构建它:

Or for case when you need it in many places, you can use promises to better structure it:

// promise that would be resolved when gapi would be loaded
var gapiPromise = (function(){
  var deferred = $.Deferred();
  window.onLoadCallback = function(){
    deferred.resolve(gapi);
  };
  return deferred.promise()
}());

var authInited = gapiPromise.then(function(){
  gapi.auth2.init({
      client_id: 'filler_text_for_client_id.apps.googleusercontent.com'
    });
})


$('#btn').click(function(){
  gapiPromise.then(function(){
    // will be executed after gapi is loaded
  });

  authInited.then(function(){
    // will be executed after gapi is loaded, and gapi.auth2.init was called
  });
});

这篇关于gapi未定义 - 谷歌与gapi.auth2.init签订了问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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