Google 最近宣布了一种新的用户登录方式。
https://developers.google.com/identity/gsi/web?hl=en
在本教程中,按钮是通过添加 HTML 代码或 javascript 创建的。
看起来像,
但是由于按钮都是在新的 Iframe 中创建和渲染的,所以我无法按照自己的意愿自定义按钮样式。
有什么办法可以改变以前提供的按钮样式吗?
之前我用过
window.gapi.load('auth2', () => {
const auth2 = window.gapi.auth2.init(options);
auth2.attachClickHandler(
idButtonRef.current,
{},
onSuccessCallback,
onFailCallback,
);
});
idButtonRef.current
是按钮,我所需要的只是附加按钮和事件监听器,如上面的代码所示。所以我能够创建我想要的按钮样式。
有没有办法通过谷歌用户签名的新方式来做到这一点?
这是我自己的(而不是优雅的)自定义按钮的方式。我使“右”Google 按钮不可见,然后将点击处理程序添加到我的自定义按钮。我们需要在具有 role=button 属性的 div 上触发 click() 。
我的示例使用纯 JavaScript,但您应该可以轻松地使用 React.js 制作类似的东西:
CSS:
.g_id_signin {
display: none;
}
HTML:
<div id="g_id_onload"
data-client_id="{{GOOGLE_CLIENT_ID}}"
data-login_uri="http://localhost:3000/google"
data-ux_mode="redirect">
</div>
<div class="g_id_signin"
data-type="icon"
data-size="large"
data-theme="outline"
data-text="sign_in_with"
data-shape="rectangular"
data-logo_alignment="left">
</div>
<button id="custom-google-btn">Continue with Google</button>
JavaScript:
const googleBtn = document.getElementById('custom-google-btn');
googleBtn.addEventListener('click', () => {
document.querySelector('.g_id_signin div[role=button]').click();
});
从 javascript 调用按钮包装单击不起作用。需要获取内部按钮,但是我们无法获取位于 iframe 下的按钮。