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.
<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>
<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>and voila. siap!
function addMessage() {
const name = document.getElementById("name").value.trim();
const website = document.getElementById("website").value.trim();
const message = document.getElementById("message").value.trim();
if (!name || !message) {
alert("name and message required");
return;
}
const time = new Date().toLocaleString();
const newMsg = { name, website, message, time };
let messages = JSON.parse(localStorage.getItem("chatMessages")) || [];
messages.unshift(newMsg); // newest on top
localStorage.setItem("chatMessages", JSON.stringify(messages));
displayMessages();
document.getElementById("name").value = "";
document.getElementById("website").value = "";
document.getElementById("message").value = "";
}
window.onload = displayMessages;
</script>
Lama tak nampak orang share tutorial pasal blog ni
ReplyDeleteSejak blogger dah tak ramai macam dulu kan
Bila laa blog nak hype balik.
Rakyat malaysia ni tak suka membaca ke? Hahaha
omg kan?! bila teringat zaman blogging dulu, rindu pulak rasa. ramai aktif and share pasal tutorials dengan freebies. paling suka tu freebies sebab rasa macam tengah shopping xD sekarang bila dah tak ramai buat tutorial ni, agak terkial-kial nak hias blog. tapi dapat belajar ilmu baru! so promi pun share je, mana tahu era blogging ni bakal naik semula kan? hehehe
DeleteThx for sharing. Nanti bole try utk blog saya.
ReplyDeletesama-sama kak aynora ( ˶ˆᗜˆ˵ ) !
DeleteLamanya takde nampak tutorial kat blog.
ReplyDeletekann. sebab tu yang kita buat, mana tahu ada juga bagi apa-apa manfaat hehe. thank you kak sudi komen 𖹭
DeleteDah lama tak jumpa entry tutorial dalam blog, mungkin sebab blogger dulu dah tak ramai yang aktif
ReplyDeleteitula. dulu rajin blogger yang lain share tutorial kan. pastu ada jugak yang bagi template blogskin free dan siap ada tutorial juga xD sekarang blogskin tu pun dah takde huhu. itu yang kita try buat tutorial mana tahu ada yang boleh membantuu
Delete