Google API 使用 gapi.load 时未捕获异常



当我使用这种类型的初始化时:

var auth2;
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'MY_CLIENT_ID.apps.googleusercontent.com',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly        
});
});

我收到以下错误:

uncaught exception: gapi.auth2.ExternallyVisibleError: Missing required parameter 'client_id'  (unknown)
TypeError: auth2 is undefined

但是如果我使用元标记初始化

<meta name="google-signin-client_id" content="MY_CLIENT_ID.apps.googleusercontent.com">

这有效,但是auth2.isSignedIn.get((给了我不一致的值。

如何解决此问题?

您可能已经包含以下代码行来显示Google的"登录"按钮。

<div class="g-signin2" data-onsuccess="onSignIn"></div> 

如果是这样,请从您的 html 页面中删除它,并检查您是否仍然在控制台中收到错误。

基于克里希纳的回答,具体来说,你想删除data-onsuccess="onSignIn"></div>部分,然后创建一个自定义按钮:

<div id="my-signin2"></div>
<script>
function renderButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
});
}
</script>

由于我的登录是在服务器端处理的,因此我添加了另一个 jquery 函数来重定向到我的后端流,但您可以相应地进行调整:

<script>
$('#my-signin2').click(function() {
// if your sign in is handled by your backend:
location.href = "/signin";
// signInCallback defined in step 6.
// auth2.grantOfflineAccess().then(signInCallback);
});
</script>

最新更新