“Cannot read property 'load' of undefined”

白昼怎懂夜的黑 提交于 2021-02-08 13:58:11

问题


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>

回答1:


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.




回答2:


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
          }
        }
      })
    });
  }


来源:https://stackoverflow.com/questions/44213061/cannot-read-property-load-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!