How to implement Facebook Login in Javascript using Facebook SDK & Graph API

24th FEB 2019

javascript





Welcome folks I am back with another blog post. In this post we will be implementing How to implement Facebook Login in Javascript using Javascript SDK & Graph API from scratch. Facebook is one of the largest social networks in the world. In every modern Web Application today we see some kind of social login available for the user. So let’s start adding the functionality of Facebook Login.





First step is to create a new app in the facebook developer section. Add a new app and get the app id of it as shown below.
















Just copy paste this app id and store it. We will be using it in the application.




After that make a new file index.html to hold the login button and logout button for building this application. Copy paste the code given below.




<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<style>
</style>
<script src="init.js"></script>
<body>
    <button id="login">Login with Facebook</button>
    <button style="display:none;" id="logout">Logout</button>           
    <div id="status">
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</html>



In these lines of code we have just two buttons login and logout buttons. Apart from this we have included jQuery and we have additional script file which will hold the initialization of the Javascript SDK. We have created a separate file for this in the form of init.js. Apart from that we have another custom script.js file in which we will write the business logic of the application.




Make a new file init.js and copy paste the below code into it. In this code we are initializing the Javascript SDK for the application. Just below copy paste your app id which you generated earlier.




(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
 
  // initialize the facebook sdk
 
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '#### YOUR APP ID ########',
      cookie     : true,  // enable cookies to allow the server to access 
                          // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v3.1' // The Graph API version to use for the call
    });
 
}



After this just create the custom script file script.js. In this file we will writing the custom business logic of the application. Copy paste the code serial wise as described below.




$(document).ready(function(){   
 
 // add event listener on the login button
 
 $("#login").click(function(){

    facebookLogin();

   
 });
 
}



In these lines of code we are attaching a click event listener to the login button that we have in index.html. After clicking the login button we are calling a custom function facebookLogin which is described below.




function facebookLogin()
  {
    FB.getLoginStatus(function(response) {
        console.log(response);
        statusChangeCallback(response);
    });
  }

In this function we are calling a Facebook SDK standard function i.e. statusChangeCallback function which takes the response and updates the UI according to the status of the Login of the user. If the user is logged in then it will show user information otherwise it will show the Login button to the user. This basically acts as a inspector who watches the current state of the user whether he is logged in or not.


function statusChangeCallback(response)
  {
      console.log(response);
      if(response.status === "connected")
      {
         $("#login").hide();
         $("#logout").show(); 
         fetchUserProfile();
      }
      else{
          // Logging the user to Facebook by a Dialog Window
          facebookLoginByDialog();
      }
  }



In this function we are checking the response which is coming to the function and we are checking a certain property which is present in the response which is status. If the status of the response is equal to connected that means the user is logged in then we can hide the login button and show the logout button to the user. And also show the user profile to the user. Otherwise we will call the custom function which prompts the user with a Login screen allowing the user to log in.




function facebookLoginByDialog()
  {
    FB.login(function(response) {
       
        statusChangeCallback(response);
       
    }, {scope: 'public_profile,email'});
  }



In this function we are first of all presenting the user with the Login in window and after the user successfully logs in we are again calling the inspector i.e. statusChangedCallback function passing the actual response object. Thereby informing the status of the user which is logged in.




function fetchUserProfile()
  {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me?fields=id,name,email,gender,birthday', function(response) {
      console.log(response);
      console.log('Successful login for: ' + response.name);
      var profile = `<h1>Welcome {response.name}<h1>
      <h2>Your email is ${response.email}</h2>
      <h3>Your Birthday is ${response.birthday}</h3>`;
      $("#status").append(profile);
    });
  }



In this function we are just fetching the user profile with the response object. We are just calling the api and getting the details in the the form of name, email, birthday and presenting the details in the h1,h2 and h3 tags respectively.




// add event listener on the logout button
 
  $("#logout").click(function(){
 
    $("#logout").hide();
    $("#login").show();
    $("#status").empty();
    facebookLogout();
 
  });

Lastly we are setting the onClick listener for the logout button as we did before for the login button. As soon as the user clicks the button we are successfully calling the facebookLogout funtion which will logout the user from Facebook. And also we are hiding the logout button and also showing the login button back to the user.




function facebookLogout()
  {
    FB.logout(function(response) {
        statusChangeCallback(response);
    });
  }



Lastly in the logout function first of all we are calling the standard function of logout of the SDK. After that we are calling the function i.e. statusChangeCallback which will inform about the status of the user.




The entire code of the script.js is given as follows so please copy paste the entire code shown below.




$(document).ready(function(){   
 
 // add event listener on the login button
 
 $("#login").click(function(){

    facebookLogin();

   
 });

 // add event listener on the logout button

 $("#logout").click(function(){

   $("#logout").hide();
   $("#login").show();
   $("#status").empty();
   facebookLogout();

 });


 function facebookLogin()
 {
   FB.getLoginStatus(function(response) {
       console.log(response);
       statusChangeCallback(response);
   });
 }

 function statusChangeCallback(response)
 {
     console.log(response);
     if(response.status === "connected")
     {
        $("#login").hide();
        $("#logout").show(); 
        fetchUserProfile();
     }
     else{
         // Logging the user to Facebook by a Dialog Window
         facebookLoginByDialog();
     }
 }

 function fetchUserProfile()
 {
   console.log('Welcome!  Fetching your information.... ');
   FB.api('/me?fields=id,name,email,gender,birthday', function(response) {
     console.log(response);
     console.log('Successful login for: ' + response.name);
     var profile = `<h1>Welcome {response.name}<h1>
      <h2>Your email is ${response.email}</h2>
      <h3>Your Birthday is ${response.birthday}</h3>`;
     $("#status").append(profile);
   });
 }

 function facebookLoginByDialog()
 {
   FB.login(function(response) {
      
       statusChangeCallback(response);
      
   }, {scope: 'public_profile,email'});
 }

 // logging out the user from Facebook

 function facebookLogout()
 {
   FB.logout(function(response) {
       statusChangeCallback(response);
   });
 }


});




About Author

Gautam Sharma

Developer, Tech. Evangalist.