这是 HTML:
<div id="button_google_login" class="customGPlusSignIn" onclick="startApp();">
<span class="dont_close" style="padding-left: 12px;">Sign In with Google</span>
</div>
JavaScript:
var googleUser = {};
var startApp = function() {
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '[Secret].apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('button_google_login'));
});
};
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}, function(error) {
// error or break up
});
}
我需要点击按钮两次才能启动登录过程,可能是什么问题?我还尝试了普通的非自定义版本,它按预期工作。
提前致谢!
最佳答案
我猜你复制了 Google Documentation 中的示例.有 startApp()
函数在 body 标签的末尾被调用。因此,当文档已加载时,将分配给 Google 按钮的点击处理程序。您更改了行为,因为仅当有人单击按钮时才分配单击处理程序。因此,您必须点击该按钮两次。
您为什么不想像 Google 提供的示例那样做呢?
只需添加 <script>startApp();</script>
收盘前</body>
标记并删除 onclick="startApp();
来自按钮的属性。
关于JavaScript - 必须点击两次自定义 Google 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010110/