繁体   English   中英

使用Google登录检查登录的Google用户

[英]Checking for signed in Google user with Google Sign-in

我正在使用Google登录库。

如果我使用页面上Google 提供的登录按钮 ,它会快速更改状态以显示我已登录,然后再执行任何操作。

是否可以在不使用Google默认按钮的情况下检测到此登录状态?

主要问题是其按钮不允许检查已登录帐户的托管域。

我试图使用GoogleAuth.currentUser.get()函数来获取用户,但如文档所述

在新初始化的GoogleAuth实例中,当前用户尚未设置。 使用currentUser.listen()方法或GoogleAuth.then()获取初始化的GoogleAuth实例。

GoogleAuth.then(onInit, onFailure)使用GoogleAuth.then(onInit, onFailure)可以正确检索用户的登录状态。

/**
 * The Sign-In client object.
 */
var auth2;

/**
 * Initializes the Sign-In client.
 */
var initClient = function() {
  gapi.load('auth2', function(){
    /**
     * Retrieve the singleton for the GoogleAuth library and set up the
     * client.
     */
    auth2 = gapi.auth2.init({
        client_id: CLIENT_ID,
        scope: 'profile'
    });

    // Called once auth2 has finished initializing
    auth2.then(checkForLoggedInUser, onFailure);

  });
};

function checkForLoggedInUser() {
  var user = auth2.currentUser.get();
  var profile = user.getBasicProfile();
  console.log('Email: ' + profile.getEmail());
}

您可以使用GoogleAuth.isSignedIn.get()方法:

// 1. Make gapi.auth2 available (using gapi.load("auth2", ...))
// 2. Initialize the library (using gapi.init({ ... }))
const isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get();

如果用户已登录Google,则isSignedIntrue ,否则为false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM