如何使新的登录与谷歌按钮保留用户登录状态页面重新加载?



Google不支持旧的登录按钮,而支持新的登录按钮。我有一个单页的小应用程序,服务器只是返回静态页面内容。该页要求用户登录并在客户端处理返回的令牌。旧按钮很好地处理了页面重新加载的情况,可以立即使用新令牌调用回调。但是,新按钮似乎不能处理页面重新加载。当使用JavaScript API与HTML,如:

<div id="parent" />
<script>
function initGoogleSignIn() {
google.accounts.id.initialize({
client_id: 'YOUR_GOOGLE_CLIENT_ID',
auto_select: true,
callback: onSignIn,
});
google.accounts.id.renderButton(document.getElementById('parent'),{});
}
function onSignIn(payload) {
let unverifiedResponsePayload = JSON.parse(atob(payload.credential.split('.')[1])); //this is just an example - instead you should _verify_ the token before any actual use
console.log(unverifiedResponsePayload.email);
}
</script>
<script src="https://accounts.google.com/gsi/client" onload="initGoogleSignIn()"></script>

根据文档,将auto_select设置为true应该会导致"一个ID令牌[…]]在没有任何用户交互的情况下自动返回,当只有一个Google会话之前已经批准了你的应用。"但是,登录然后重新加载页面不会调用回调。在类似的设置中,旧按钮会调用回调。

问题是如何实现在没有用户交互的情况下获得令牌的旧行为在页面上重新加载新的按钮?

我发现可以配置"一键点击"这将导致在页面重新加载时调用回调,但只有在显示One Tap块和几秒钟延迟之后。我仍然想知道这是一个有意的行为,只是没有正确记录或文档是正确的,行为是由谷歌在库中修复。

这里是如何initGoogleSignIn函数可以改变,以使用一键:

function initGoogleSignIn() {
google.accounts.id.initialize({
client_id: 'YOUR_GOOGLE_CLIENT_ID',
auto_select: true,
callback: onSignIn,
prompt_parent_id: 'parent', //DOM ID of the container element for One Tap block
});
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed() || notification.isSkippedMoment() || (notification.isDismissedMoment() && notification.getDismissedReason() != 'credential_returned')) {
// no sign-in happened, display the button
google.accounts.id.renderButton(document.getElementById('parent'),{});
}
});
}

这种方法仍然会为回调调用增加明显的延迟(在我的例子中是4秒)。

最新更新