开发者问题收集

“无法读取未定义的属性‘load’”

2017-05-27
24090

我尝试按照 文档集成 Google 登录,但在控制台中遇到了此错误:

未捕获的 TypeError:无法读取未定义的属性“load”
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>
2个回答

尝试向脚本标记添加 onload 事件。因此,请将您的脚本标记更改为

<script src="https://apis.google.com/js/platform.js?onload=myFunc" async defer></script>

然后将您的代码包装在回调函数中。

thewolff
2017-05-27

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
          }
        }
      })
    });
  }
GA1
2018-11-11