Blogger Chat CODE_02

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 Firebase → https://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)



<!-- 💬 Chat Box with Firebase -->

<style>

  /* Chat icon and label styling */

  #chat-icon {

    position: fixed;

    right: 20px;

    top: 50%;

    transform: translateY(-50%);

    background: #28a745;

    color: white;

    padding: 15px;

    border-radius: 50%;

    cursor: pointer;

    z-index: 1000;

    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    display: flex;

    align-items: center;

    gap: 10px;

  }


  #chat-icon:hover {

    background: #218838;

  }


  #chat-icon span {

    font-size: 16px;

    font-weight: bold;

  }


  /* Chat box styling (existing) */

  #chat-box {

    width: 100%;

    max-width: 400px;

    margin: auto;

    background: #f9f9f9;

    padding: 10px;

    border-radius: 10px;

    border: 1px solid #ddd;

    font-family: Arial;

    position: fixed;

    bottom: 20px;

    right: 20px;

    display: none; /* Hidden by default */

    z-index: 1000;

    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

  }

</style>


<!-- Chat Icon with Label -->

<div id="chat-icon">

  <span>💬</span>

  <span>Open Chat</span>

</div>


<!-- Chat Box -->

<div id="chat-box">

  <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);

  });


  // Toggle chat box visibility

  document.getElementById("chat-icon").addEventListener("click", function () {

    const chatBox = document.getElementById("chat-box");

    chatBox.style.display = chatBox.style.display === "none" ? "block" : "none";

  });

</script>




📌 Step 5:To implement an Admin-Only Chat Page in Blogger

Authenticate using a password or Firebase Authentication.


Fetch and Display All Messages from Firebase in chronological order.


Edit and Delete Messages directly from the Firebase Realtime Database.


Here’s the step-by-step implementation:


Step 1: Create a Hidden Page in Blogger

🔹Go to Blogger Dashboard > Pages > New Page.


🔹Title the Page (e.g., "Admin Chat Log").


🔹Switch to HTML View and paste the following code:



📌👇👇👇CODE👇👇👇📌


<!DOCTYPE html>

<html>

<head>

  <title>Admin Chat Log</title>

  <style>

    body {

      font-family: Arial, sans-serif;

      background: #f9f9f9;

      padding: 20px;

    }

    h1 {

      text-align: center;

      color: #333;

    }

    #login-section {

      max-width: 400px;

      margin: 0 auto;

      padding: 20px;

      background: white;

      border-radius: 10px;

      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    }

    #chat-log {

      max-width: 800px;

      margin: 20px auto;

      background: white;

      padding: 20px;

      border-radius: 10px;

      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    }

    .message {

      padding: 10px;

      border-bottom: 1px solid #ddd;

      display: flex;

      justify-content: space-between;

      align-items: center;

    }

    .message:last-child {

      border-bottom: none;

    }

    .message-actions {

      display: flex;

      gap: 10px;

    }

    .message-actions button {

      padding: 5px 10px;

      border: none;

      border-radius: 5px;

      cursor: pointer;

    }

    .message-actions .edit-btn {

      background: #28a745;

      color: white;

    }

    .message-actions .delete-btn {

      background: #dc3545;

      color: white;

    }

  </style>

</head>

<body>

  <h1>Admin Chat Log</h1>


  <!-- Login Section -->

  <div id="login-section">

    <h2>Admin Login</h2>

    <input type="password" id="admin-password" placeholder="Enter Admin Password" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 5px;" />

    <button id="login-btn" style="width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer;">Login</button>

  </div>


  <!-- Chat Log Section -->

  <div id="chat-log" style="display: none;">

    <h2>Chat Messages</h2>

    <div id="messages"></div>

  </div>


  <!-- Firebase SDK -->

  <script type="module">

    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";

    import { getDatabase, ref, onChildAdded, onChildChanged, onChildRemoved, update, remove } 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 = ref(db, "messages");


    // Admin Password (Replace with a secure password)

    const ADMIN_PASSWORD = "admin123"; // Change this to a strong password


    // Login Functionality

    document.getElementById("login-btn").addEventListener("click", function () {

      const password = document.getElementById("admin-password").value.trim();

      if (password === ADMIN_PASSWORD) {

        document.getElementById("login-section").style.display = "none";

        document.getElementById("chat-log").style.display = "block";

        loadMessages();

      } else {

        alert("Incorrect password. Please try again.");

      }

    });


    // Load Messages

    function loadMessages() {

      onChildAdded(messagesRef, (snapshot) => {

        const message = snapshot.val();

        addMessageToLog(snapshot.key, message);

      });


      onChildChanged(messagesRef, (snapshot) => {

        const message = snapshot.val();

        updateMessageInLog(snapshot.key, message);

      });


      onChildRemoved(messagesRef, (snapshot) => {

        removeMessageFromLog(snapshot.key);

      });

    }


    // Add Message to Log (New Messages at the Top)

    function addMessageToLog(key, message) {

      const messagesContainer = document.getElementById("messages");


      const messageDiv = document.createElement("div");

      messageDiv.className = "message";

      messageDiv.id = `message-${key}`;

      messageDiv.innerHTML = `

        <div>

          <strong>${message.name}:</strong> ${message.text}

        </div>

        <div class="message-actions">

          <button class="edit-btn" onclick="editMessage('${key}', '${message.text.replace(/'/g, "\\'")}')">Edit</button>

          <button class="delete-btn" onclick="deleteMessage('${key}')">Delete</button>

        </div>

      `;


      // Add new message at the top

      messagesContainer.insertBefore(messageDiv, messagesContainer.firstChild);

    }


    // Update Message in Log

    function updateMessageInLog(key, message) {

      const messageDiv = document.getElementById(`message-${key}`);

      if (messageDiv) {

        messageDiv.innerHTML = `

          <div>

            <strong>${message.name}:</strong> ${message.text}

          </div>

          <div class="message-actions">

            <button class="edit-btn" onclick="editMessage('${key}', '${message.text.replace(/'/g, "\\'")}')">Edit</button>

            <button class="delete-btn" onclick="deleteMessage('${key}')">Delete</button>

          </div>

        `;

      }

    }


    // Remove Message from Log

    function removeMessageFromLog(key) {

      const messageDiv = document.getElementById(`message-${key}`);

      if (messageDiv) {

        messageDiv.remove();

      }

    }


    // Edit Message (Pre-Fill with Existing Message)

    window.editMessage = function (key, currentText) {

      const newText = prompt("Edit the message:", currentText);

      if (newText) {

        update(ref(db, `messages/${key}`), { text: newText });

      }

    };


    // Delete Message

    window.deleteMessage = function (key) {

      if (confirm("Are you sure you want to delete this message?")) {

        remove(ref(db, `messages/${key}`));

      }

    };

  </script>

</body>

</html>





📌 Step 6:Key Features of the Admin Chat Log Page

🔹Admin Authentication:


🔹The admin must enter a password to access the chat log.


🔹// Admin Password (Replace with a secure password)

    const ADMIN_PASSWORD = "admin123"; // Change this to a strong password

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!