我正在尝试在我的网站上构建一个Google登录按钮。我试图避免使用他们的内置按钮。下面的代码用于登录用户,但我无法弄清楚如何让我的网页记住,当用户刷新页面或离开网站并返回时,他们已登录。
使用Chrome的开发者工具,我可以看到https://accounts.google.com
和Local Storage
下的Session Storage
条目。它们似乎或多或少包含相同的信息,包括用户的验证令牌。
我不明白的是如何让gapi.auth2.init()
函数识别并使用此令牌。 documentation似乎没有涵盖它。
<html>
<head>
<title>Login Test</title>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</head>
<script>
var googleUser = {};
function renderButton() {
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'MY_CREDENTIALS.apps.googleusercontent.com',
});
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function(googleUser) {
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
}
);
}
</script>
<body>
<div id="gSignInWrapper">
<span class="label">Sign in with:</span>
<input type="button" id="customBtn" value="Google"></input>
</div>
<p id="name"></p>
</body>
</html>
答案 0 :(得分:4)
您可以使用listeners。这是相关部分:
// Listen for sign-in state changes.
auth2.isSignedIn.listen(signinChanged);
// Listen for changes to current user.
auth2.currentUser.listen(userChanged);
您还可以通过
获取最新值var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
要严格检测返回的用户,您可以执行以下操作:
var auth2 = gapi.auth2.init(CONFIG);
auth2.then(function() {
// at this point initial authentication is done.
var currentUser = auth2.currentUser.get();
});
说到我的代码,我会这样做:
auth2 = gapi.auth2.init(CONFIG);
auth2.currentUser.listen(onUserChange);
auth2.attachClickHandler(element, {});
这样,登录状态的所有更改都会传递给onUserChange(这包括返回用户,来自attachClickHandler的新登录,来自不同标签的新登录)。