我正在尝试关注this文档以与Google登录集成,但我在控制台中遇到此错误:
Uncaught TypeError: Cannot read property 'load' of undefined
at script.js:1
script.js
:
window.gapi.load('auth2', function() {
console.log('Loaded!');
});
我在大约一半时间内收到错误,并检查Chrome中的网络面板,只有在以下资源 <
时才会发生错误:
https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en.d2dliHDvPwE.O/m=auth2/exm=signin2/rt=j/sv=1/d=1/ed=1/am=AQ/rs=AGLTcCNGAKhVlpzmTUpjFgzBXLpLM_oEFg/cb=gapi.loaded_1
如何消除此错误?
如果它有用,这是我的index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Google Sign In Test</title>
<meta name="google-signin-client_id" content="*****.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="script.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
</body>
</html>
答案 0 :(得分:6)
尝试将onload事件添加到脚本标记中。因此,将脚本标记更改为
<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>
然后将代码包装在回调函数中。
答案 1 :(得分:1)
将onload
参数添加到链接中,如文档中所示:google sign in docs
如果您使用纯html / js进行操作,则可以将此摘录添加到head
标记中。
<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>
<script>
function init() {
gapi.load('auth2', function() { // Ready. });
}
</script>
如果您想在React应用程序(例如create-react-app)中加载gapi,请尝试将其添加到组件中:
loadGapiAndAfterwardsInitAuth() {
const script = document.createElement("script");
script.src = "https://apis.google.com/js/platform.js";
script.async = true;
script.defer = true;
script.onload=this.initAuth;
const meta = document.createElement("meta");
meta.name="google-signin-client_id";
meta.content="%REACT_APP_GOOGLE_ID_OF_WEB_CLIENT%";
document.head.appendChild(meta);
document.head.appendChild(script);
}
initAuth() {
window.gapi.load('auth2', function () {
window.gapi.auth2.init({
client_id: "%REACT_APP_GOOGLE_ID_OF_WEB_CLIENT%";
}).then(googleAuth => {
if (googleAuth) {
if (googleAuth.isSignedIn.get()) {
const googleUser = googleAuth.currentUser.get();
// do something with the googleUser
}
}
})
});
}