![](/img/trans.png)
[英]How to make new Sign In With Google button preserve user signed-in state on page reload?
[英]How to detect if a user is signed in on page load with Google Sign In
我正在使用这个简单的代码,如下所示:https://developers.google.com/identity/sign-in/web/build-button
<script>
function renderSignInButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile',
'width': 220,
'height': 40,
'longtitle': true,
'theme': 'dark',
'prompt': 'select_account',
'onsuccess': onSignIn,
'onfailure': onSignInFailed
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=renderSignInButton" async defer></script>
登录后一切正常,当用户稍后返回页面时,它会记住 state 中的登录。
问题:如何检测用户何时到达页面但当前未登录? (按钮已呈现,但成功或失败处理程序永远不会触发,所以我不清楚在哪里/如何检查当前登录状态)
我认为这应该很简单,但是我搜索并尝试过的各种解决方案都不起作用。
这个答案对我有用:https://stackoverflow.com/a/60084966/6281777
我所做的唯一编辑是调用 window.gapi.auth2.init 没有选项,因为它们与 gapi.signin2.render 已经设置的选项冲突。
因此,在此处指定的 onload 内:
<script src="https://apis.google.com/js/platform.js?onload=renderSignInButton" async defer></script>
未登录的检查如下所示:
async function renderSignInButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile',
'width': 220,
'height': 40,
'longtitle': true,
'theme': 'dark',
'prompt': 'select_account',
'onsuccess': onSignIn,
'onfailure': onSignInFailed
});
//BEGIN CHECK IF USER IS NOT SIGNED IN
window.gapi.load('auth2', async () => {
window.auth2 = await window.gapi.auth2.init({
});
var authInstance = await window.gapi.auth2.getAuthInstance();
var signedIn = authInstance.isSignedIn.get();
if (!signedIn) {
console.log("USER IS NOT SIGNED IN");
//do stuff
}
})
//END CHECK IF USER IS SIGNED IN
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.