【问题标题】:"Cannot read property 'load' of undefined"“无法读取未定义的属性‘负载’”
【发布时间】:2017-10-28 00:36:59
【问题描述】:

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

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>

【问题讨论】:

    标签: javascript google-signin googlesigninapi


    【解决方案1】:

    尝试将 onload 事件添加到脚本标签。所以把你的脚本标签改成

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

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

    【讨论】:

      【解决方案2】:

      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 应用程序中加载 gapi(例如 create-react-app),请尝试将其添加到组件中:

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

      【讨论】:

      • 我怎样才能获得 %REACT_APP_GOOGLE_ID_OF_WEB_CLIENT%?我得到googleAuth.isSignedIn.get() 为假。我怎样才能把它当真?
      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2020-10-30
      • 2019-10-09
      相关资源
      最近更新 更多