(Javascript)Google登录网站无效

时间:2018-03-22 08:18:45

标签: javascript google-signin googlesigninapi

我把它放在<头>部分:

<!-- Google Authentication -->
<script async defer src="https://apis.google.com/js/api.js?"></script>

<script type="text/javascript">
    var auth2;
    var initClient = function() {
        gapi.load('auth2', function(){
            auth2 = gapi.auth2.init({
                client_id: '*********.apps.googleusercontent.com',
                fetch_basic_profile : false,
                scope : 'profile'
            });
            auth2.then(function(){
                if (auth2.isSignedIn.get() == true) {
                    auth2.signIn();
                }
            })
            auth2.then(function(){
              if (!auth2.isSignedIn.get()) {
                    location.href("index.html")
              }
        }
        });
    };
</script>

但是从未达到&#34; location.href(&#34; index.html&#34;)。谁知道为什么?

如果我将location.href(...)放在.init(...)函数的正上方,则会到达。但是,如果我把它放在下面它将无法正常工作。所以错误在.init()函数内,但我无法找出它是什么

(auth2.isSignedIn.get()的结果是&#34;未定义&#34;,它应该是真或假)

2 个答案:

答案 0 :(得分:0)

替换你的代码:

<script type="text/javascript">
    var auth2;
    var initClient = function() {
        gapi.load('auth2', function(){
            auth2 = gapi.auth2.init({
                client_id: '*********.apps.googleusercontent.com',
                fetch_basic_profile : false,
                scope : 'profile'
            });
            auth2.then(()=>{
                if (auth2.isSignedIn.get() == true) {
                    auth2.signIn();
                } else{
                     window.location.href="index.html";
                  }
            })

        }
        });
    };
</script>

答案 1 :(得分:0)

解决

<script src="https://apis.google.com/js/platform.js?onload=initLoad" async defer></script>
<script>
    try{
        window.initLoad = function(){
            gapi.load('auth2', function(){
                var auth2 = gapi.auth2.init({
                    client_id: '********.apps.googleusercontent.com'
                });
                if (auth2.isSignedIn.get() == true) {
                    auth2.signIn();
                }else{
                    window.location.assign("index.html");
                }
            });
        }
    }catch(err){
        console.log(err.message);
    }
</script>

现在我发现了一个新问题,“登录”按钮没有更多工作......它在另一个页面上,我一整天都没有接触到新的问题......