Click here to Skip to main content
15,867,835 members
Articles / Web Development / HTML

Chat Application Using Firebase, Javascript

Rate me:
Please Sign up or sign in to vote.
4.95/5 (6 votes)
15 Dec 2014CPOL6 min read 56.7K   2.5K   16   8
This is a simple example of a web based chat application implemented using Firebase.

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Image 1

Introduction

CHAT4U is real-time web-based chat application built on Firebase using Facebook authentication, which offers rich user Interface, built-In Web/Image Google search option, responsive design that makes this web app easy on any device with the feature of sharing your status using emojis.

Image 2

Image 3

What is Firebase?

Firebase is a scalable, real-time backend for your web application. It allows our development team to build rich, collaborative applications without the hassle of managing servers or writing server-side code

Don't just save data. Sync it. When data changes, apps built with Firebase update instantly across every device -- web or mobile. Firebase-powered apps work offline. Data is synchronized instantly when your app regains connectivity.

How Firebase Works?

A Firebase itself is your realtime database, hosted in the cloud. Since Firebase is a NoSQL database you can easily store data as simple JSON documents.

At a high level, Firebase is simply a database with a RESTFul API. Each individual Firebase has a name and its own URL endpoint. Therefore if your Firebase’s name is my-firebase, the URL would be https://my-firebase.firebaseio.com/. Using this API endpoint you can easily store and read data right out of your Firebase.

Firebase isn't just an API though. After data is stored in your Firebase it gets streamed in realtime to every connected client. This means that Firebase automatically updates all clients with the newest set of data.

Why Firebase?

Anyone with a basic understanding of HTML or Javascript can build an app, and Firebase will “do the rest".

Below is the key features of using Firebase:

  • Firebase has joined the Google

  • Store & Sync Data Instantly

  • Works on every platform

  • Easy authentication

  • Bulletproof Security

  • Instant Scalability

Using the code

1. Installation & Setup

First sign up for a Firebase account. A new Firebase will be created for you with a unique URL ending in firebaseio.com. You'll use this URL to store and sync data.

In this chat example the URL is:

new Firebase("https://chat4u.firebaseio.com/")

Therefore if your Firebase’s name is my-firebase, the URL would be https://my-firebase.firebaseio.com/.

Image 4

Next, you'll need to include the Firebase JavaScript client library in your website. Simply add a script tag to the "head" section of your HTML file. I recommend including the library directly from CDN:

JavaScript
<script src="https://cdn.firebase.com/js/client/2.0.6/firebase.js"></script>

Also, you'll need to include jQuery in your website as well, which makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

 

2. Facebook Authentication

To get started with Facebook authentication, you need to first create a new Facebook application. Click the Create New App button in the top right of that page. Choose a name, namespace, and category for your application.

Image 5

In your Facebook app configuration, click on the Settings tab on the left-hand navigation menu. Then go to the Advanced tab at the top and scroll down to the Security section. At the bottom of that section, add https://auth.firebase.com/v2/<YOUR-FIREBASE>/auth/facebook/callback to your Valid OAuth redirect URIs and click Save Changes at the bottom of the page.

Image 6

Next, you'll need to get your app credentials from Facebook. Click on the Basic tab at the top of the page. You should still be within the Settings tab. Towards the top of this page, you will see your App ID and App Secret. Your App ID will be displayed in plain text and you can view your App Secret by clicking on the Show button and typing in your Facebook password.

Image 7

Copy these Facebook application credentials (App ID and Secret) in the Login & Auth section in your Firebase Dashboard.

Image 8

 

3. Code Walkthrough

First of all, extract "Chat4U_src.zip".

The code is very light and simple, and all included in Index.html file.

Our data structure is very simple, data are split into separate paths which they could be effeciently downloaded in segments, we have two data paths called Messages and Users. Messages can be fetched separately and displayed as they arrive, allowing the UI to stay responsive and fast.
Users are easily accessible (or restricted) we also store these by facebook id.

JavaScript
// CREATE A REFERENCE TO FIREBASE (Messages)
var refMessages = new Firebase("https://chat4u.firebaseio.com/Messages");
// CREATE A REFERENCE TO FIREBASE (Users)
var refUsers = new Firebase("https://chat4u.firebaseio.com/Users");

Second part of the code we need to authenticate user, If user does not have an existing session, you can prompt the user to login and then invoke the Facebook login popup (e.g. after they have clicked a "Login" button) with the following snippet:

JavaScript
// prefer pop-ups, so we don't navigate away from the page
refMessages.authWithOAuthPopup("facebook", function (err, authData) {
    if (err) {
    if (err.code === "TRANSPORT_UNAVAILABLE") {
         // fall-back to browser redirects, and pick up the session
         // automatically when we come back to the origin page
         refMessages.authWithOAuthRedirect("facebook", function (err, authData) { });
    }
    } else if (authData) {
    if (authData) { 
    //Authenticated successfully 
    }
});

After user authenticated successfully, We need to save the user's profile into Firebase so we can list users, by using this line of code:

refUsers.child(authData.uid).set(authData);

Next step is to work on UI, User interface design important for several reasons. First of all the more intuitive the user interface the easier it is to use, and the easier it is to use and the less expensive to use it. The better the user interface the easier it is to train people to use it, reducing your training costs. The better your user interface the less help people will need to use it, reducing your support costs. The better your user interface the more your users will like to use it, increasing their satisfaction with the work that you have done.

These two functions are for UI purposes.

getLastBgColor: To get the background color of last submitted text message based on fabebook id in firebase.

JavaScript
function getLastBgColor(vfbid) {
   refMessages.orderByChild('fbid').equalTo(vfbid).limitToLast(1).on('child_added', function (snapshot){
      var data = snapshot.val();
      $('#hf_bgcolor').val(data.bgcolor);
   });
}

getLastDirection: To get the last submitted text message direction in firebase.

JavaScript
function getLastDirection() {
   refMessages.limitToLast(1).on('child_added', function (snapshot) 
   {
       var data = snapshot.val();
       $('#hf_lastfid').val(data.fbid);
       $('#hf_lastdir').val(data.dir);
   });
}

Next, we retrieve last 10 saved messages from our Firebase data and generate the html elements on the fly.

JavaScript
// Add a callback that is triggered for each chat message.
refMessages.limitToLast(10).on('child_added', function (snapshot) {
    //GET DATA
    var data = snapshot.val();
    var fbid_d = data.fbid;
    var username_d = data.name;
    var message_d = data.text;
    var dir_d = data.dir;
    var date_d = data.currentdate;
    var bgcolor_d = data.bgcolor;
    var strProfilePic = 'https://graph.facebook.com/' + fbid_d + "/picture";
    if (dir_d) {
        imgclass = dir_d == "R" ? "pull-right" : "pull-left";
        divdir = dir_d == "R" ? "divTxtR" : "divTxtL";
    }
    //CREATE ELEMENTS MESSAGE & SANITIZE TEXT
    var messageElement = $("<li class='media' f='" + fbid_d + "'>");
    var divmediabody = $("<div class='media-body'>");
    var divmedia = $("<div class='media'>");
    var a = $("<a class='" + imgclass + "' href='#'><img class='media-object img-circle' src='" + strPro             filePic + "' /></a>");
    var divmediabody2 = $("<div class='media-body " + divdir + "'>");
    divmediabody2.css('background', bgcolor_d);
    messageElement.append(divmediabody);
    divmediabody.append(divmedia);
    divmedia.append(a);
    divmedia.append(divmediabody2);
    var usernamediv = $("<small class='text-muted'>");
    divmediabody2.html(message_d);
    divmediabody2.append(usernamediv);
    usernamediv.html("<br />" + date_d);
    //ADD MESSAGE
    messageList.append(messageElement);
});

And the final step is to write data to Firebase by pressing the send button.

JavaScript
function pushData() {
    //FIELD VALUES
    var username = authUserName;
    var message = $(".emoji-wysiwyg-editor").html();
    //Clientside Datetime
    var cdate = new Date();
    //***********************************************************
    //Set current text message direction to push it to firebase.
    //***********************************************************
    getLastDirection();
    lastdir = $('#hf_lastdir').val();
    lastfid = $('#hf_lastfid').val();
    if (lastfid != fbid) {
       newdir = lastdir == "L" ? "R" : "L";
    }
    else {
       newdir = lastdir;
    }
    //***********************************************************
    bgcolor = $('#hf_bgcolor').val();
    if (!bgcolor) {
      //Generate random color to set the background color of the text body.
       var back = ["#dbeef3", "#f2dcdb", "#fac08f", "#ccc1d9", "#c4bd97"];
       bgcolor = back[Math.floor(Math.random() * back.length)];
    }
    //***********************************************************
    // Google search functionality
    //***********************************************************
    var keyword = '';
    var bSearchImg = false;
    var _url = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=';
    if (message.toLowerCase().match('^s ') ) {
       keyword = message.substring(2, message.length);
       _url = _url + keyword
    }
    if (message.toLowerCase().match('^s img ')) {
      keyword = message.substring(6, message.length);
      _url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' + keyword;
      bSearchImg = true;
    }
    if (keyword.length > 0) {
       $.ajax({
          url: _url,
          type: "GET",
          dataType: 'jsonp',
          async: 'true',
          success: function (data) {
              var strResult = '';
              if (!bSearchImg) {
                $.each(data.responseData.results, function (i, rows) {
                    strResult = strResult + rows.title + "<br />" + "<a href='" + rows.url + "' target='                                _blank'>" + rows.url + "</a>" + "<br /><br />";
                });
              }
              else{
                $.each(data.responseData.results, function (i, rows) {
                   strResult = strResult + rows.title + "<br />" + "<a href='" + rows.url + "' target='_                               blank'><img src='" + rows.url + "' height='100' width='100'></img></a>"                                 + "<br /><br />";
                });
              }
              message = message + "<br />" + strResult;
              //SAVE DATA TO FIREBASE.
              refMessages.push({ name: username, text: message, fbid: fbid, bgcolor: bgcolor, 
                                 currentdate: cdate.toLocaleString(), dir: newdir });
          }
      });
    }
    else {
       //SAVE DATA TO FIREBASE.
       refMessages.push({ name: username, text: message, fbid: fbid, bgcolor: bgcolor, 
                      currentdate: cdate.toLocaleString(), dir: newdir });
    }       
    $(".emoji-wysiwyg-editor").html('');
}

 

4. Deploying your site

Firebase Hosting gives you a fast, secure and reliable way to host your app's static assets such as HTML, CSS, JavaScript, and media files. You can set on your own custom domain or on a subdomain of firebaseapp.com.

Once you set up the Firebase command line tool,

1) Initializing Your Site

Cd to that app's directory and run:

$ firebase init

You will need to sign into your firebase account.

Image 9

Enter your firebase app name and press enter, for public directory just press enter to continue.

Image 10

As you can see the new file has been generated in your application directory called firebase.json, now we are ready to delpoy the files to Firebase hosting environment.

2) Deploying Your Site

To deploy run "firebase depoly", this will deploy your application to your-firebase-name.firebaseapp.com.

$ firebase deploy

Image 11

Once all the files deployed successfully, open the browser and go to your-firebase-name.firebaseapp.com

For this example the URL will be: https://chat4u.firebaseapp.com/

History

15th December, 2014: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to upgrade the authentication SDKs ? Pin
Member 1320329216-May-17 19:42
Member 1320329216-May-17 19:42 
QuestionNo datastructure for messages and users in firebase Pin
Member 1191993521-Feb-17 19:23
Member 1191993521-Feb-17 19:23 
No datastructure for messages and users in firebase

QuestionHow to Chat one to one ?? Pin
Member 116635436-Feb-16 18:33
Member 116635436-Feb-16 18:33 
Generallink is not working Pin
cookieburner13-Sep-15 0:06
cookieburner13-Sep-15 0:06 
GeneralRe: link is not working Pin
Arlen Navasartian16-Nov-15 10:47
Arlen Navasartian16-Nov-15 10:47 
QuestionAbout the snippets Pin
Nelek16-Dec-14 12:33
protectorNelek16-Dec-14 12:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.