Blogger Chat CODE_01

shyamprasadam2pm@gmail.com
0

Step-by-Step Guide to Adding a Custom Chat Box in Blogger using Firebase

This guide will help you create a real-time chat box in your Blogger site where users can send messages, links, and files (PDF, DOC, CBZ, Images, etc.). We'll use Firebase as the backend.


📌 Step 1: Create a Firebase Project

  1. Go to Firebasehttps://console.firebase.google.com/
  2. Click "Create a Project" and give it a name (e.g., BloggerChat).
  3. Disable Google Analytics (not required) and click Continue.
  4. Wait for the project to be created, then click Continue.

📌 Step 2: Set Up Firebase Database

  1. In your Firebase project, go to Build → Realtime Database.
  2. Click Create Database.
  3. Choose Start in test mode (this allows anyone to send messages).
  4. Click Enable.
  5. Your database is now ready.

📌 Step 3: Get Firebase Config Keys

  1. In Firebase, go to Project settings (⚙️ icon on the left).
  2. Scroll down to Your apps and click "Web" (</>).
  3. Register an app (e.g., BloggerChatApp).
  4. Click Register app, then Continue to console.
  5. Copy the Firebase SDK Config (it looks like this 👇):
javascript
const firebaseConfig = { apiKey: "YOUR-API-KEY", authDomain: "your-project-id.firebaseapp.com", databaseURL: "https://your-project-id.firebaseio.com", projectId: "your-project-id", storageBucket: "your-project-id.appspot.com", messagingSenderId: "your-messaging-id", appId: "your-app-id" };

Save this; you'll need it in Step 5.



📌 Step 4: Add Chat Box Code to Blogger

Now, we will create the chat box where users can send messages and upload files.

  1. Go to Blogger → Layout → Add a Gadget → HTML/JavaScript.
  2. Paste this full HTML, CSS, and JavaScript code:



Final Fixed Code (Messages in Correct Order)

html
<!-- 💬 Chat Box with Firebase --> <div id="chat-box" style="width: 100%; max-width: 400px; margin: auto; background: #f9f9f9; padding: 10px; border-radius: 10px; border: 1px solid #ddd; font-family: Arial;"> <h3 style="text-align: center;">Chat Box</h3> <div style="display: flex; flex-direction: column; gap: 5px; margin-bottom: 10px;"> <!-- Name Input (Now Above Message Box) --> <input type="text" id="username" placeholder="Enter your name..." style="width: 95%; padding: 8px; border: 1px solid #ccc; border-radius: 5px;"> <!-- Message Input & Send Button --> <div style="display: flex;"> <input type="text" id="msg" placeholder="Type a message..." style="flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 5px;"> <button id="sendBtn" style="padding: 8px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; margin-left: 5px;">Send</button> </div> </div> <!-- Messages Box (New Messages on Top) --> <div id="messages" style="height: 250px; overflow-y: auto; background: white; padding: 10px; border-radius: 5px; border: 1px solid #ccc; display: flex; flex-direction: column;"></div> </div> <!-- Firebase SDK --> <script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"; import { getDatabase, ref, push, onChildAdded, query, orderByChild } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js"; // 🔐 Replace with YOUR Firebase Config 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 const app = initializeApp(firebaseConfig); const db = getDatabase(app); const messagesRef = query(ref(db, "messages"), orderByChild("timestamp")); // Order by timestamp function formatMessage(msg) { return msg.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" style="color: blue; text-decoration: underline;">$1</a>'); } function sendMessage() { let name = document.getElementById("username").value.trim(); let msgInput = document.getElementById("msg"); let msg = msgInput.value.trim(); if (!name) { alert("Please enter your name before sending a message!"); return; } if (msg) { push(ref(db, "messages"), { name: name, text: msg, timestamp: Date.now() }); msgInput.value = ""; } } // ✅ Click "Send" button document.getElementById("sendBtn").addEventListener("click", sendMessage); // ✅ Press "Enter" to send document.getElementById("msg").addEventListener("keypress", function (event) { if (event.key === "Enter") { sendMessage(); } }); // 🔄 Load Messages in Correct Order (New Messages on Top) onChildAdded(messagesRef, (snapshot) => { let msgData = snapshot.val(); let msgDiv = document.createElement("div"); msgDiv.style.padding = "10px"; msgDiv.style.background = "#f1f1f1"; msgDiv.style.marginBottom = "5px"; msgDiv.style.borderRadius = "5px"; msgDiv.innerHTML = `<strong style="color: #007bff;">${msgData.name}:</strong> ${formatMessage(msgData.text)}`; let messagesContainer = document.getElementById("messages"); // 🔹 Append messages at the **TOP** messagesContainer.prepend(msgDiv); }); </script>

🔥 Fixes & Improvements

New messages now appear at the top while old messages move downward
Firebase messages are now ordered properly using orderByChild("timestamp")
prepend() ensures that the latest message is inserted at the top
Enter key & Send button work as expected
Clickable links supported

🚀 Try this now, and let me know if it's perfect! 🎉

Post a Comment

0 Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!