"Cannot read property 'load' of undefined"
Try adding an onload event to the script tag. So change your script tag to
<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>
Then wrap your code in the callback function.
Add onload
param to the link, as in the docs: google sign in docs
If you do it in pure html/js, you can just add this excerpt into the head
tag.
<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>
<script>
function init() {
gapi.load('auth2', function() { // Ready. });
}
</script>
If you want to load gapi inside a react app (for instance create-react-app) try to add this to a component:
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
}
}
})
});
}