Real-Time Simple Chat Application
Let’s create a simple real-time chat application to demonstrate Firebase Realtime Database in action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realtime Chat App</title>
</head>
<body>
<h1>Realtime Chat</h1>
<div id="chat-box"></div>
<input type="text" id="message" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js"></script>
<script>
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
const chatBox = document.getElementById('chat-box');
function sendMessage() {
const message = document.getElementById('message').value;
database.ref('messages/').push({
message: message,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
document.getElementById('message').value = '';
}
database.ref('messages/').on('value', (snapshot) => {
chatBox.innerHTML = '';
snapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const messageElement = document.createElement('p');
messageElement.textContent = childData.message;
chatBox.appendChild(messageElement);
});
});
</script>
</body>
</html>
Output:
Explanation:
- HTML Structure: The HTML file includes input fields for typing messages and a button to send them.
- Initialize Firebase: Firebase is initialized with the configuration details.
- Sending Messages: The sendMessage function pushes messages to the messages node in the database.
- Listening for Messages: The on method listens for changes in the messages node and updates the chat box in real time.
Firebase Realtime Database: Reading and Writing Data
Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients.
In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, write data or read data to Firebase Realtime Database with an example of a Real-Time Simple Chat Application.
Contact Us