Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot read property 'load' of undefined"

I'm attempting to follow this documentation to integrate with Google sign in, though I'm running into this error in console:

Uncaught TypeError: Cannot read property 'load' of undefined
        at script.js:1

script.js:

window.gapi.load('auth2', function() {
    console.log('Loaded!');
});

I get the error about half of the time, and inspecting the network panel in Chrome, it only happens when the following resource is not loaded:

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

How can I eliminate this error?

If it's useful, here's my 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>
like image 527
Bennett Avatar asked May 27 '17 04:05

Bennett


2 Answers

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.

like image 193
thewolff Avatar answered Sep 27 '22 21:09

thewolff


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
          }
        }
      })
    });
  }
like image 35
GA1 Avatar answered Sep 27 '22 20:09

GA1