企业网站用什么建站最快优化师培训机构
谷歌开发者文档写得一坨,浪费了一白天时间,决定自己写一篇
1,配置域名注册ID
1,先有一个谷歌账号,然后访问https://console.cloud.google.com/auth/clients用谷歌账号登录--注册一个项目(类型选择Web应用)--左侧选择客户端,创造客户端--里面会有一个很长的ID,用来调用API(图1)
2,点击右边的编辑进入客户端后,在已获授权的 JavaScript 来源下注册你的域名:如果是本地开发,选择localhost:的对应端口---保存即可(图2)
这样我们就能调用谷歌API了
在代码中使用
谷歌会提供一个登录按钮和登录弹窗,但是按钮的样式固定不灵活,难免需要和UI对齐的时候,而文档也没由对外暴露的登录函数,于是主包通过JSAPI, 隐藏谷歌给的登录按钮,设置函数手动触发点击事件,让UI按钮点击也能触发谷歌登录
1,创建一个div 绑定实例作为谷歌登录的按钮,设置隐藏属性
<!-- 谷歌登录按钮 -->
<div ref="googleButtonRef" class="hidden"></div>
2,组件加载时挂载谷歌登录脚本,并调用初始化配置的函数
onMounted(() => {initGoogleLogin();
});// 初始化谷歌登录配置initGoogleLogin = () => {if (typeof window.google === 'undefined') {const script = document.createElement('script');script.src = 'https://accounts.google.com/gsi/client';script.async = true;script.defer = true;script.onload = () => this.renderGoogleButton();document.head.appendChild(script);} else {this.renderGoogleButton();}}
3,配置函数:调用谷歌的方法进行配置,client_id对应客户端ID ,callback对应成功登录后的函数,其他的无关紧要
// 渲染初始配置const renderGoogleButton = () => {if (!googleButtonRef.value || typeof window.google === 'undefined') return;// 上传账号初始化函数window.google.accounts.id.initialize({client_id: '客户端ID',callback: 成功等陆后的函数,auto_select: false,cancel_on_tap_outside: true,use_fedcm_for_prompt: false,itp_support: true});// 渲染按钮window.google.accounts.id.renderButton(googleButtonRef.value, {theme: 'outline',size: 'large',type: 'standard',shape: 'pill',text: 'signin_with',logo_alignment: 'left'});}
4,登陆成功的响应函数:返回的response中由对应用户的谷歌toke,可以传递给后端
// 谷歌响应函数const handleGoogleCredentialResponse = (response: any) => {console.log('谷歌登录成功!');console.log('令牌前10个字符:', response.credential.substring(0, 10) + '...');localStorage.setItem('googleToken', response.credential);}
5,初步登录函数:执行内带的prompt方法登录,如果失败则尝试手动登录
// 谷歌登录函数const handleGoogleLogin = () => {try {if (typeof window.google !== 'undefined') {console.log('尝试触发谷歌登录...');window.google.accounts.id.prompt((notification: any) => {if (notification.isNotDisplayed() || notification.isSkippedMoment()) {console.log('登录窗口未显示,原因:',notification.getNotDisplayedReason() ||notification.getSkippedReason());this.clickHiddenGoogleButton();}});} else {console.log('谷歌API未加载,尝试重新加载...');this.initGoogleLogin();setTimeout(() => {this.clickHiddenGoogleButton();}, 1000);}} catch (error) {console.error('触发谷歌登录失败:', error);// this.useRedirectLogin();}}
6,手动登录:访问隐藏按钮,强制使用click事件,如果第一步登录失败才会执行这一步
// 手动触发隐藏按钮const clickHiddenGoogleButton = () => {if (this.googleButtonRef.value) {const googleButton = this.googleButtonRef.value.querySelector('div[role="button"]');if (googleButton) {console.log('通过点击隐藏按钮触发登录');(googleButton as HTMLElement).click();} else {console.log('找不到谷歌按钮元素,使用重定向方式');// this.useRedirectLogin();}} else {console.log('无法登录');}}
7,这时候基本就行了,绑定事件后,点击对应按钮跳出谷歌登录的弹窗:
实际可以至情况而定6/7选一种方法保留 主包也没搞懂为什么6不能执行,才保留6和7