Javascript 未定义gapi-Google登录问题与gapi.auth2.init有关
我正在尝试实现Google登录并检索用户的个人资料信息。 错误为:未捕获引用错误:未定义gapi。为什么呢Javascript 未定义gapi-Google登录问题与gapi.auth2.init有关,javascript,google-signin,Javascript,Google Signin,我正在尝试实现Google登录并检索用户的个人资料信息。 错误为:未捕获引用错误:未定义gapi。为什么呢 <!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/j
<!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>
$(函数(){
gapi.auth2.init({
客户端id:'filler\u text\u for\u client\u id.apps.googleusercontent.com'
});
});
之所以发生这种情况,是因为脚本标记上有async
和defer
属性gapi
将在脚本标记后加载gapi.auth2.init
要在执行此代码之前等待gapi
,可以在脚本标记中使用onload query param,如下所示:
<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>
我想,在上面的例子中,您会发现这也不起作用,因为
gapi.auth2
尚未定义(我知道这一点,因为我今天犯了同样的错误),您首先需要调用gapi.load('auth2',callback)
,并传递一个回调,然后调用gapi.auth2.init
。下面是我的\u onGoogleLoad
函数的一个示例,它是用于加载第一个platform.js
脚本的回调
var _auth2
var _onGoogleLoad = function () {
gapi.load('auth2', function () {
_auth2 = gapi.auth2.init({
client_id: 'OUR_REAL_ID_GOES_HERE',
scope: 'email',
fetch_basic_profile: false
})
_enableGoogleButton()
})
}
之后,您可以使用
\u auth2
变量实际登录用户。虽然这些答案对我有所帮助,但我相信官方文档中有更好的答案
看
问题不仅存在于gapi中。要调用
init
方法,必须初始化auth2对象。
一旦GoogleAuth对象完全初始化,就有一个承诺
这对我很有用:
包括此脚本标记
<script src="https://apis.google.com/js/platform.js"></script>
适用于Vue.JS应用程序
- 为
platform.js
- 设置分派事件的函数
- 在组件的
挂载的
钩子中捕获该事件
vue cli
project中
别忘了提供自己的客户ID
public/index.html
函数triggerGoogleLoaded(){
dispatchEvent(新事件(“google加载”));
}
App.vue
已登录用户配置文件
{{profile}}
注销。
导出默认值{
组件:{},
数据(){
返回{
个人资料:假
};
},
方法:{
onSignIn(用户){
const profile=user.getBasicProfile();
this.profile=profile;
},
签出(){
var auth2=gapi.auth2.getAuthInstance();
auth2.signOut()。然后(()=>{
位置。重新加载(true);
});
},
RenderGoogelLoginButton(){
gapi.signn2.render(“谷歌登录btn”{
onsuccess:this.onSignIn
});
}
},
安装的(){
window.addEventListener(“谷歌加载”,this.renderGoogelLoginButton);
}
};
我应该在哪里添加onSignOut功能?它也需要gapi,但我只在用户单击按钮时调用它。您也可以将它添加到onLoadCallback
,例如将$(function(){..})
放在那里。这是我尝试的第一件事。对不起,我以前没提过。尝试调用注销会导致“未捕获引用错误:未定义注销”哦,等等,无所谓。您正在谈论document.ready函数lol。等一下,让我试试。添加了示例如何使用promisesThanks构造此函数。谢谢您的回答,我会试试!或者,如文档中所述,包括一个
(等…)按钮。如果存在,platform.js将自动下载auth2
。这似乎触发了正在下载的完全相同的内容。不幸的是,文件在这方面不是很好。此外,index.html中的
可以是https://apis.google.com/js/api.js
而不是platform.js
,在你的例子中,它包含的代码少了一点。@phil294有什么方法可以抑制这种行为吗?@beppe9000我不知道,对不起,我需要的是这应该是公认的答案!如果您使用的是Vue.js,并且您使用的是单独的组件进行注销,那么这是可行的!你救了我一天!这是正确的答案。谢谢万岁!这具有缩小版:
var auth2; // The Sign-In object.
var googleUser; // The current user.
/**
* Calls startAuth after Sign in V2 finishes setting up.
*/
var appStart = function() {
gapi.load('auth2', initSigninV2);
};
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
scope: 'profile'
});
// Listen for sign-in state changes.
auth2.isSignedIn.listen(signinChanged);
// Listen for changes to current user.
auth2.currentUser.listen(userChanged);
// Sign in the user if they are currently signed in.
if (auth2.isSignedIn.get() == true) {
auth2.signIn();
}
// Start with the current live values.
refreshValues();
};
/**
* Listener method for sign-out live value.
*
* @param {boolean} val the updated signed out state.
*/
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
document.getElementById('signed-in-cell').innerText = val;
};
/**
* Listener method for when the user changes.
*
* @param {GoogleUser} user the updated user.
*/
var userChanged = function (user) {
console.log('User now: ', user);
googleUser = user;
updateGoogleUser();
document.getElementById('curr-user-cell').innerText =
JSON.stringify(user, undefined, 2);
};
/**
* Updates the properties in the Google User table using the current user.
*/
var updateGoogleUser = function () {
if (googleUser) {
document.getElementById('user-id').innerText = googleUser.getId();
document.getElementById('user-scopes').innerText =
googleUser.getGrantedScopes();
document.getElementById('auth-response').innerText =
JSON.stringify(googleUser.getAuthResponse(), undefined, 2);
} else {
document.getElementById('user-id').innerText = '--';
document.getElementById('user-scopes').innerText = '--';
document.getElementById('auth-response').innerText = '--';
}
};
/**
* Retrieves the current user and signed in states from the GoogleAuth
* object.
*/
var refreshValues = function() {
if (auth2){
console.log('Refreshing values...');
googleUser = auth2.currentUser.get();
document.getElementById('curr-user-cell').innerText =
JSON.stringify(googleUser, undefined, 2);
document.getElementById('signed-in-cell').innerText =
auth2.isSignedIn.get();
updateGoogleUser();
}
}
gapi.load('auth2', initSigninV2);
function initSigninV2() {
gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com'
}).then(function (authInstance) {
// now auth2 is fully initialized
});
}
<script src="https://apis.google.com/js/platform.js"></script>
<template>
<div id="app">
<div id="nav">
<div id="google-signin-btn"></div>
<a href="#" class="sign-out" @click="signOut" v-if="profile">Sign out</a>
</div>
<div v-if="profile" class="">
<h2>Signed In User Profile</h2>
<pre>{{ profile }}</pre>
</div>
<div v-if="!profile">
<h2>Signed out.</h2>
</div>
<router-view />
</div>
</template>
<script>
export default {
components: {},
data() {
return {
profile: false
};
},
methods: {
onSignIn(user) {
const profile = user.getBasicProfile();
this.profile = profile;
},
signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(() => {
location.reload(true);
});
},
renderGoogleLoginButton() {
gapi.signin2.render("google-signin-btn", {
onsuccess: this.onSignIn
});
}
},
mounted() {
window.addEventListener("google-loaded", this.renderGoogleLoginButton);
}
};
</script>