Google Firebase Live Group Chat JavaScript
Hi guys, today I’m going to implement Live Group Chat Example using Google Firebase Real-time Database. The complete working example is available on Github, you can find the link at the bottom of this post. You may also check Demo.
Setup Firebase
If you don’t have a Firebase account, you can go to the Signup page and create an account. If you already have an account, you can Login here.
Once you are on Account’s page, you will have an option there to create a new Firebase app.
From Firebase Console find “Add Firebase to your web app”
You will find JavaScript Code with your project key & other credentials.
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "your-project-key-here", authDomain: "group-chat-codinginfinite.firebaseapp.com", databaseURL: "https://group-chat-codinginfinite.firebaseio.com", projectId: "group-chat-codinginfinite", storageBucket: "group-chat-codinginfinite.appspot.com", messagingSenderId: "129035491745" }; firebase.initializeApp(config); </script>
Setup Firebase Real-time Database
Create a Database to store the message and user id for each user. How my database looks like
Firebase Anonymous Authentication
Enable firebase anonymous authentication:
- In the Firebase console, open the Authentication section.
- On the Sign-in Methods page, enable the Anonymous sign-in method.
Now you can get a unique id for each user using this code
var user = firebase.auth().signInAnonymously(); firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. var isAnonymous = user.isAnonymous; user_id = user.uid; } else { // User is signed out. } });
Write Message to Firebase Database
This simple code will push an object of user id and message text into the firebase database with a unique id.
function writeUserData(message) { db_ref.push({ user_id: user_id, message: message }); }
Add Messages to Chat
Now we need to add Events for Adding Messages, we do not need to get all messages List from Firebase Database, Add Event will do the job automatically for us.
// get firebase database reference... var db_ref = firebase.database().ref('/'); db_ref.on('child_added', function (data) { var type; if(data.val().user_id == user_id){ type="sent"; } else{ type="replies"; } $('<li class="'+type+'"><p>' + data.val().message + '</p></li>').appendTo($('.messages ul')); $('.message-input input').val(null); $('.contact.active .preview').html('<span>You: </span>' + data.val().message); $(".messages").animate({ scrollTop: $(".messages")[0].scrollHeight }, 0); });
Combine the code to get Complete Live group chat or you can download complete example from Github.