Login with Google Account using JavaScript


We’ve already published Login with Google account using PHP, but if your project is built with another technology and you want to integrate Google Sign-In in a single page, this article will help you lot. Here we’ll provide the easiest way to implement login using google account on your website.

Using Google APIs and few lines of JavaScript code, single page login can be integrated into the web app. Follow the step-by-step guide and simple script to implement Login with Google Account using JavaScript.

Create a Google Developers Console Project

Before you begin Create a Google Developers Console project and client ID. You should need to set Authorized JavaScript origins and Authorized redirect URIs for the Web application. Also need to specify the client ID in your script.

For better understanding, we’ll demonstrate a sample project on Login with Google Account using JavaScript. This sample project would be hosted on the localhost server. This sign-in process will be implemented on a single page, so this sample Google login JavaScript API project has only one file index.html and the file and folder structure would be the simple like the below.
login-with-google-account-using-javascript-file-folder-structure-by-codexworld

After creating the Google Developers Console project, the following 3 things should be done.

  • Google+ API is enabled in the Google Developers Console.
  • http://localhost is set as Authorized JavaScript origins in the Google Developers Console.
  • Genarated Client ID for Web application.

index.html File:

Specify your app’s Client ID which you have created in the Google Developers Console with the google-signin-client_id meta element.

<head>
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
</head>

Include the Google Platform Library with the query string of onload render function.

<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer></script>

Here we’ve used the jQuery library for displaying user information after sign-in. You can omit to include jQuery library as per your requirement.

<script src="jquery.min.js"></script>

JavaScript code contains 4 functions, renderButton(), onSuccess(), onFailure(), and signOut().
renderButton() method will automatically rendered sign-in button in the specified div. renderButton() function calls gapi.signin2.render() with your style and scope settings. Also, the login success and failure functions are specified in it.

function onSuccess(googleUser) {
    var profile = googleUser.getBasicProfile();
    gapi.client.load('plus', 'v1', function () {
        var request = gapi.client.plus.people.get({
            'userId': 'me'
        });
        //Display the user details
        request.execute(function (resp) {
            var profileHTML = '<div class="profile"><div class="head">Welcome '+resp.name.givenName+'! <a href="javascript:void(0);" onclick="signOut();">Sign out</a></div>';
            profileHTML += '<img src="'+resp.image.url+'"/><div class="proDetails"><p>'+resp.displayName+'</p><p>'+resp.emails[0].value+'</p><p>'+resp.gender+'</p><p>'+resp.id+'</p><p><a href="'+resp.url+'">View Google+ Profile</a></p></div></div>';
            $('.userContent').html(profileHTML);
            $('#gSignIn').slideUp('slow');
        });
    });
}
function onFailure(error) {
    alert(error);
}
function renderButton() {
    gapi.signin2.render('gSignIn', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSuccess,
        'onfailure': onFailure
    });
}
function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
        $('.userContent').html('');
        $('#gSignIn').slideDown('slow');
    });
}

The following HTML produces Google Sign-In button and logged in user details.

<!-- HTML for render Google Sign-In button -->
<div id="gSignIn"></div>
<!-- HTML for displaying user details -->
<div class="userContent"></div>

We’ve used some CSS for styling the user details section.

.profile{
    border: 3px solid #B7B7B7;
    padding: 10px;
    margin-top: 10px;
    width: 350px;
    background-color: #F7F7F7;
    height: 160px;
}
.profile p{margin: 0px 0px 10px 0px;}
.head{margin-bottom: 10px;}
.head a{float: right;}
.profile img{width: 100px;float: left;margin: 0px 10px 10px 0px;}
.proDetails{float: left;}

You can see the following Google Sign-In button by opening the script URL (http://localhost/login-with-google-account-using-javascript/index.html) file in the browser.

login-with-google-account-using-javascript-google-sign-in-button-by-codexworld

1 Comment

  1. LE TUAN ANH Said...

Leave a reply

Connect With CodexWorld