Reputation: 1
I'm trying to implement a custom Google login button using the Google Identity Services SDK. I want to style the button myself, instead of using the default Google button. However, when I click on my custom button, nothing happens.
Here's the code I'm using:
<!DOCTYPE html>
<html>
<head>
<title>Google Sign-In</title>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
function handleCredentialResponse(response) {
console.log("Encoded JWT ID token: " + response.credential);
// You can decode and use the JWT ID token here
}
function triggerGoogleLogin() {
google.accounts.id.initialize({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
callback: handleCredentialResponse
});
google.accounts.id.prompt();
}
window.onload = function () {
document.getElementById('loginButton').addEventListener('click', function() {
triggerGoogleLogin();
});
};
</script>
</head>
<body>
<button id="loginButton">Login with Google</button>
</body>
</html>
What could be wrong or what am I missing?
Any help or suggestions would be greatly appreciated. Thank you!
What I've tried:
Verified that the triggerGoogleLogin function is called when the button is clicked.
Upvotes: 0
Views: 92
Reputation: 519
google.accounts.id.prompt()
confusingly doesn't prompt for a Google login, it opens the One Tap prompt, which only works if the user is already logged in. Google has (intentionally it appears) restricted the styling options for the Google Identity Services process that everyone is being forced onto. There is no method in the library to manually trigger the login prompt from your own button, and their stated intended alternative is fully managing the OAuth 2.0 flow yourself.
This post details a hacky workaround for this restriction, where you render their default button without displaying it, and when your button is clicked you trigger a click of theirs. Given their stated intent, it's unclear how long that workaround will last though.
The workaround from that post is:
const createFakeGoogleWrapper = () => {
const googleLoginWrapper = document.createElement("div");
googleLoginWrapper.style.display = "none";
googleLoginWrapper.classList.add("custom-google-button");
document.body.appendChild(googleLoginWrapper);
window.google.accounts.id.renderButton(googleLoginWrapper, {
type: "icon",
width: "200",
});
const googleLoginWrapperButton =
googleLoginWrapper.querySelector("div[role=button]");
return {
click: () => {
googleLoginWrapperButton.click();
},
};
};
with
<script>
const googleButtonWrapper = createFakeGoogleWrapper();
window.handleGoogleLogin = () => {
googleButtonWrapper.click();
};
</script>
<button class="my-awesome-button" onclick="handleGoogleLogin()">
Login with new Google Sign-in
</button>
Which will then call whatever you set as the callback
in the library initialization code
Upvotes: 0