im试图使用他们新的API实现google登录:https://developers.google.com/identity/sign-in/web/
登录和注销操作正常。我的问题是,如果没有服务器端,我不知道如何管理其他页面上的会话。
所以我尝试了这个代码-https://developers.google.com/identity/sign-in/web/session-state
而且对我来说效果不好。我不想在每一页都有谷歌登录按钮。如果我删除"auth2.attachClickHandler.."部分,整个代码将无法工作。
我只想在其他页面(而不是带有谷歌按钮的页面)中指示用户是否仍连接到。你能帮我吗?
编辑:我尝试了答案中建议的以下代码,但我得到了一个错误:"Uncaught TypeError:无法读取未定义的的属性'init'"
代码:
var auth2 = gapi.auth2.init({
client_id : 'ID.apps.googleusercontent.com'
});
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
console.log("signed in");
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
console.log("NOT signed in");
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
您可以在所有页面上加载gap.auth2并调用:
var auth2 = gapi.auth2.init(...);
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
在此解决方案中,只有当用户未登录时,才会显示登录按钮。