javascript - 使用 JavaScript 的 Google 身份自定义登录
问题描述
通过 Google 登录,我们使用自定义按钮皮肤(遵循https://developers.google.com/identity/sign-in/web/build-button中提到的品牌指南),然后调用手动登录JS 基本上使用这个:
gapi.load('auth2', function(){
gapi.auth2.init().signIn().then(function(response) {
// handle success
}).catch(function(error) {
// handle error/cancel
});
});
我正在查看 Google Identity 的文档,但似乎这些(自定义按钮或通过 JS 触发登录)都不可能?有没有办法做到这一点,我错过了?我们真的希望能够使 Google 登录按钮与我们的其他登录按钮保持一致,并处理 UI 友好的大小调整等。非常感谢!
注意:我知道这google.accounts.id.prompt()
在文档中,但这似乎并不普遍。当我尝试它时,我只是得到一个opt_out_or_no_session
错误,没有任何反应。另外,我们希望使用 Google 按钮,而不是一键,这就是我认为的目的。
解决方案
您可以通过执行以下操作来做到这一点:
const clientLoad = new Promise(resolve => {
gapi.load('auth2', () => {
resolve(gapi.auth2.init({ client_id: '<your_client_id>' }));
});
});
async function login() {
const client = await clientLoad;
const response = client.signIn().catch((e) => {
// in case user closes the popup
if (e.error === 'popup_closed_by_user') {
return null;
}
throw e;
});
// handle your authentication flow with the token received
console.log(response.getAuthResponse());
}
在您的按钮中:
<button class="your-custom-style" onclick="login()">
Login with google
</button>
推荐阅读
- vba - 使用 VBA 移动到 MSAccess ADO 子窗体中的下一条记录
- javascript - 从括号中提取文本但括号内没有括号
- python - 烧瓶`基本查询`对象不可调用?
- node.js - 在节点js中捕获异常获取ReferenceError
- amazon-web-services - Amazon RDS 备份窗口中的持续时间是什么意思
- eclipse - 如何创建 Eclipse 插件来签出项目并对其进行配置
- java - 实现静态 util 方法应遵循的标准
- kendo-ui - 无法配置在没有工具栏的 div 元素上应用的剑道编辑器
- postgis - 在 Geoserver 2.15.1 Postgis 数据存储中不可见,即使我之前创建了 postgis 数据存储
- python - Opening and closing a file while logging data