TypeError:gapi.auth2 undefined

时间:2015-04-23 06:55:14

标签: google-openid

我完全遵循整合Google登录的说明:

https://developers.google.com/identity/sign-in/web/sign-in#specify_your_apps_client_id

登录有效,但注销会在行中出现javascript错误:

  

var auth2 = gapi.auth2.getAuthInstance();

错误是:

  

gapi.auth2 undefined

我按照说明添加了Google平台库:

    <script type='text/javascript' src='https://apis.google.com/js/platform.js' async defer></script>

为什么不起作用?

1 个答案:

答案 0 :(得分:56)

在同一页面上使用signIn和signOut吗? Div g-signin2加载并插入gapi.auth2所以只要它们在同一页面上就可以工作。

如果signOut位于单独的页面上,则应手动加载并初始化gapi.auth2库。

完整示例(您必须将YOUR_CLIENT_ID替换为您的实际client_id):

<html>
<head>
   <meta name="google-signin-client_id" content="YOUR_CLIENT_ID">
</head>
<body>
  <script>
    function signOut() {
      var auth2 = gapi.auth2.getAuthInstance();
      auth2.signOut().then(function () {
        console.log('User signed out.');
      });
    }

    function onLoad() {
      gapi.load('auth2', function() {
        gapi.auth2.init();
      });
    }
  </script>
  <a href="#" onclick="signOut();">Sign out</a>

  <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>