私はコンソールでこのエラーに遭遇していますが、Googleサインインと統合するために this のドキュメントに従っています。
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>
スクリプトタグにonloadイベントを追加してみてください。スクリプトタグを次のように変更します
<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>
次に、コードをコールバック関数でラップします。
ドキュメントにあるように、onload
paramをリンクに追加します: 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>
リアクションアプリ(たとえば、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
}
}
})
});
}