Use custom image for google signin button

18.9k views Asked by At

I want to provide users a facility to sign in with google. However, I want to use my image(only image, no css) as "sign in with google" button. I am using the following code:

<div id="mySignin"><img src="images/google.png" alt="google"/></div> 

I am also using gapi.signin.render function as mentioned on google developer console. The code is:

<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
 <script>
  function render(){
    gapi.signin.render("mySignIn", { 
 // 'callback': 'signinCallback',
  'clientid': 'xxxx.apps.googleusercontent.com', 
  'cookiepolicy': 'single_host_origin', 
  'requestvisibleactions': 'http://schema.org/AddAction',
  'scope': 'profile'
});
  }

The problem is that google signin popup is not opening and I cannot figure out how to solve it. Please suggest. Thanks in advance.

  <script type="text/JavaScript">
  /**
   * Handler for the signin callback triggered after the user selects an account.
   */
    function onSignInCallback(resp) {
    gapi.client.load('plus', 'v1', apiClientLoaded);
  }

  /**
   * Sets up an API call after the Google API client loads.
   */
  function apiClientLoaded() {
    gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
  }

  /**
   * Response callback for when the API client receives a response.
   *
   * @param resp The API response object with the user email and profile information.
   */
  function handleEmailResponse(resp) {
    var primaryEmail;
    var jsonobj=JSON.stringify(resp);alert(jsonobj);
    var uid= jsonobj.id;
    var user_name1= jsonobj.name;
    for (var i=0; i < resp.emails.length; i++) {
      if (resp.emails[i].type === 'account') primaryEmail = resp.emails[i].value;
    }
    /* document.getElementById('response').innerHTML = 'Primary email: ' +
        primaryEmail + '<br/>id is: ' + uid; */
  }
2

There are 2 answers

0
JBaczuk On BEST ANSWER

To use an image as your "Google Sign-in" button, you can use the GoogleAuth.attachClickHandler() function from the Google javascript SDK to attach a click handler to your image. Replace <YOUR-CLIENT-ID> with your app client id from your Google Developers Console.

HTML example:

<html>
  <head>
    <meta name="google-signin-client_id" content="<YOUR-CLIENT-ID>.apps.googleusercontent.com.apps.googleusercontent.com">
  </head>
  <body>
    <image id="googleSignIn" src="img/your-icon.png"></image>
    <script src="https://apis.google.com/js/platform.js?onload=onLoadGoogleCallback" async defer></script>
  </body>
</html>

Javascript example:

function onLoadGoogleCallback(){
  gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
      client_id: '<YOUR-CLIENT-ID>.apps.googleusercontent.com',
      cookiepolicy: 'single_host_origin',
      scope: 'profile'
    });

  auth2.attachClickHandler(element, {},
    function(googleUser) {
        console.log('Signed in: ' + googleUser.getBasicProfile().getName());
      }, function(error) {
        console.log('Sign-in error', error);
      }
    );
  });

  element = document.getElementById('googleSignIn');
}
0
yongju lee On

For those who come to here trying to get the button work out: The code below should do the trick.

It looks like the 'callback' method doesn't seem to work not sure if this is something to do with Vue as I am building it on Vue, or Google changed it as this was posted 5 years ago. Anyways, use the example below.

        window.onload =() =>{
            var GoogleUser = {}
          gapi.load('auth2',() =>{
            var auth2 = gapi.auth2.init({
              client_id: '<client-unique>.apps.googleusercontent.com',
              cookiepolicy: 'single_host_origin',
              scope: 'profile'
            });

          auth2.attachClickHandler(document.getElementById('googleSignup'), {},
           (googleUser) =>{
                console.log('Signed in: ' + googleUser.getBasicProfile().getName());
              },(error) =>{
                console.log('Sign-in error', error);
              }
            );
          });


        }

Change 'client_id' to your client id, and element id to your customized button id.

I hope this saves time for anyone!

Plus: I ended up using the code below, which is clearer:


window.onload = () => {
    
    gapi.load('auth2', () => {
    
        let auth2 = gapi.auth2.init({
          client_id: '<client_id>.apps.googleusercontent.com',
          cookiepolicy: 'single_host_origin',
          scope: 'profile email'
        });
    
      document.getElementById('googleSignup').addEventListener('click',() => {
        auth2.signIn().then(() => {
            let profile = auth2.currentUser.get().getBasicProfile();
           ... profile functions ...
          }).catch((error) => {
            console.error('Google Sign Up or Login Error: ', error)
          });
    
        });;
    
    
    });


}