如何使用新版Google Identity Services for Web实现谷歌登录登出及用户信息获取
新版Google Identity Services 登录/登出实现代码
登录页代码
核心实现谷歌登录按钮,获取用户姓名、邮箱、头像信息:
<!DOCTYPE html> <html> <head> <title>谷歌登录</title> </head> <body> <!-- 谷歌登录按钮容器 --> <div id="g_id_onload" data-client_id="YOUR_CLIENT_ID" <!-- 替换为你的谷歌客户端ID --> data-callback="handleCredentialResponse"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> <script src="https://accounts.google.com/gsi/client" async defer></script> <script> // 处理登录回调,解析用户信息 function handleCredentialResponse(response) { // 解码JWT获取用户数据 const payload = JSON.parse(atob(response.credential.split('.')[1])); // 提取所需信息 const userInfo = { name: payload.name, email: payload.email, avatar: payload.picture, userId: payload.sub }; // 这里可以把用户信息发送到后端,或存储到本地 console.log('用户信息:', userInfo); // 示例:跳转到主页或登出页 window.location.href = '/logout.html'; } </script> </body> </html>
登出页代码
实现登出按钮,清除谷歌登录状态:
<!DOCTYPE html> <html> <head> <title>谷歌登出</title> </head> <body> <h1>登录成功</h1> <button onclick="handleLogout()">登出</button> <script src="https://accounts.google.com/gsi/client" async defer></script> <script> function handleLogout() { // 禁用谷歌自动登录选择 google.accounts.id.disableAutoSelect(); // 清除本地存储的用户信息(如果有) localStorage.removeItem('googleUserInfo'); // 跳回登录页 window.location.href = '/login.html'; } </script> </body> </html>
关键注意事项
- 替换代码中的
YOUR_CLIENT_ID为你在谷歌开发者控制台获取的客户端ID - 确保你的域名已在开发者控制台的「授权 JavaScript 来源」和「授权重定向 URI」中配置
- JWT解码逻辑已内置,无需额外库,直接提取
payload中的字段即可获取所需信息
内容的提问来源于stack exchange,提问作者Curious Developer
相关产品推荐
相关产品推荐

