25 April 2026

tutorial: buat chatbox sendiri

 

salam rakan-rakan bloggers sekalian! korang nampak tak chatbox dekat sidebar tepi ni? korang pernah tak rasa macam cbox korang boring sebab tak boleh customize? dulu, cbox boleh customize and dia punya design pun simple je. so, korang nak tak buat chatbox sendiri yang korang boleh customize mengikut kehendak korang sendiri? kalau nak, meh saya ajarkan!

korang kena set database untuk simpan mesej-mesej tersebut. kalau tak, nanti korang tak boleh baca mesej orang lain. this is a CRUCIAL step, okay? so, macam mana nak buat? 

pergi ke firebase dan buat account korang.

nanti, dekat firebase tu, korang scroll ke bawah sampai jumpa 'all firebase products'. korang pilih firestore.

 
then nanti, dia akan keluar macam cloud firestore apa tu. korang tekan je get started. then nanti akan keluar macam kat bawah ni
 
 
bila dah keluar macam kat atas, tekan 'create a new firebase project'. korang bagi la nama untuk project korang. also, keep in mind untuk turn off google analytics tu. 
 
dah siap nanti, akan keluar macam gambar di bawah. tekan 'create database'. 

 

now, untuk edition korang select standard. database ID & location tu korang tetapkan lah mana-mana korang nak. for me, promi pilih nam5 (US) yang dia dah pilih secara default. untuk configure, pilih test mode ya. then, create!
 
pastu, pergi ke project overview. dia akan keluar macam di page bawah. then, tekan add apps dan ambil 
</> (web).
 
 
 

register korang punya app tu. letak la nama apa pun. macam ni:
 
 

untuk add firebase sdk, pilih <script> tag. kalau korang perasan, bawah tu dia ada bagi code. copy code tu, simpan dalam notepad dulu. nanti nak guna. yang lain-lain tu, tekan je next sampai la continue to console.
 
code yang akan dapat kalau pilih <script> tag (yang di highlight tu yang penting):
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/12.12.1/firebase-app.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "UR API",
    authDomain: "UR AUTHDOMAIN",
    projectId: "UR ID",
    storageBucket: "UR STORAGEBUCKET",
    messagingSenderId: "UR SENDERID",
    appId: "UR APPID"
  };


  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
</script> 
 
pergi ke blogger -> layout -> add widget -> html/javascript. copy and paste code di bawah dan isikan maklumat yang di highlight tu dengan maklumat yang korang simpan dari code firebase tadi. then, save.
 
<div class="chatbox">

  <!-- FORM -->
  <div class="chat-form">

    <div class="form-row top">
      <input type="text" id="name" placeholder="name" required />
      <input type="text" id="website" placeholder="link (optional)" />
    </div>

    <div class="form-row bottom">
      <textarea id="message" placeholder="message" required></textarea>
      <button onclick="addMessage()">send</button>
    </div>

  </div>

  <!-- MESSAGES -->
  <div id="messages" class="messages"></div>

</div>

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.0/firebase-app.js";
  import { 
    getFirestore, collection, addDoc, query, orderBy, onSnapshot, serverTimestamp 
  } from "https://www.gstatic.com/firebasejs/10.12.0/firebase-firestore.js";

  const firebaseConfig = {
    apiKey: "UR API",
    authDomain: "UR AUTHDOMAIN",
    projectId: "UR ID",
    storageBucket: "UR STORAGEBUCKET",
    messagingSenderId: "UR SENDERID",
    appId: "UR APPID"
  };


  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);

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

  // REAL-TIME LISTENER
  const q = query(collection(db, "messages"), orderBy("time"));

  onSnapshot(q, (snapshot) => {
    messagesDiv.innerHTML = "";

    snapshot.forEach(doc => {
  const data = doc.data();

  const name = data.name || "anon";
  const text = data.text || "";
  const website = data.website || "";

  let time = "";

if (data.time && data.time.toDate) {
  const date = data.time.toDate();

  const datePart = date.toLocaleDateString();
  const timePart = date.toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
    hour12: false
  });

  time = `${datePart} ${timePart}`;
}

  messagesDiv.innerHTML += `
    <div class="message">
      <div class="message-name">
        ${website ? `<a href="${website}" target="_blank">${name}</a>` : name}
      </div>

      <div class="message-text">${text}</div>

      <div class="message-time">${time}</div>
    </div>
  `;
});


    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  });

  // SEND MESSAGE
  window.addMessage = async function () {
    const name = document.getElementById("name").value.trim();
    const website = document.getElementById("website").value.trim();
    const message = document.getElementById("message").value.trim();

    if (!name || !message) return;

    await addDoc(collection(db, "messages"), {
      name,
      website,
      text: message,
      time: serverTimestamp()
    });

    document.getElementById("message").value = "";
  };
</script> 


 pergi ke firebase -> firestore -> rules.

 

 

nanti keluar macam dekat bawah ni. 

 

 

delete code tu dan replace dengan code di bawah:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /messages/{doc} {
      allow read, write: if true;
    }
  }
}

 pastu, pergi ke customize template, add css. copy and paste code di bawah dan adjust ikut korang suka.

.chatbox {
  border: 2px double #5f7a2f;
  padding: 8px;
  font-family: 'RainyHearts';
  font-size: 12px;
  width: 84%;
  height: 100px; /* FIXED HEIGHT */
  display: flex;
  flex-direction: column;
}

.chat-form {
  flex-shrink: 0;
  order: 2;
}

.chat-form input,
.chat-form textarea {
  padding: 2px;
  border: 1px solid #5f7a2f;
  font-family: 'RainyHearts';
  font-size: 12px;
  background: transparent;
}

.chat-form textarea {
  height: 20px;
  resize: none;
}

.chat-form button {
  padding: 5px 5px;
  border: 1px solid #5f7a2f;
  background: transparent;
  cursor: pointer;
font-size: 8px;
}

/* message box */
.messages {
  margin-top: 2px;
  flex-grow: 1;
  overflow-y: auto;
  padding-top: 2px;
  order: 1;
height: auto;

}

/* each message */
.message {
  margin-bottom: 5px;
  border-bottom: 1px dotted #5f7a2f;
  padding-bottom: 2px;
}

.message-name {
  font-weight: bold;
}

.message-time {
  font-size: 10px;
  opacity: 0.7;
}
.form-row {
  display: flex;
  gap: 4px;
margin-bottom: 2px;
}

/* name + link */
.form-row.top input {
  width: 45%;
}

/* message + button */
.form-row.bottom textarea {
  flex-grow: 1;
  height: 20px;
width: 10px
}

.form-row.bottom button {
  width: 30px;
  font-size: 8px;

 ctrl+f dekat kotak code korang then cari </head>. copy and paste code di bawah atas </head>:

   <script>
function addMessage() {
  const name = document.getElementById(&quot;name&quot;).value.trim();
  const website = document.getElementById(&quot;website&quot;).value.trim();
  const message = document.getElementById(&quot;message&quot;).value.trim();

  if (!name || !message) {
    alert(&quot;name and message required&quot;);
    return;
  }

  const time = new Date().toLocaleString();

  const newMsg = { name, website, message, time };

  let messages = JSON.parse(localStorage.getItem(&quot;chatMessages&quot;)) || [];
  messages.unshift(newMsg); // newest on top
  localStorage.setItem(&quot;chatMessages&quot;, JSON.stringify(messages));

  displayMessages();

  document.getElementById(&quot;name&quot;).value = &quot;&quot;;
  document.getElementById(&quot;website&quot;).value = &quot;&quot;;
  document.getElementById(&quot;message&quot;).value = &quot;&quot;;
}

window.onload = displayMessages;
</script> 

and voila. siap!
 

 

No comments:

Post a Comment

say something nice!