我使用 JS 和前端创建了 firebase 网站。
一切正常,期待这一件事。我的聊天内容未按日期正确排序。我希望它们按时间顺序排序,因此较旧的消息位于顶部。
我的 JSON 片段
"messages": {
"-O70WTtDPs8et5-zRVV4": {
"message": "Hello!",
"senderId": "UJA4AVrSSdZGOJc0bXYbxOcLOB22",
"timestamp": 1726602407195
},
"-O70WW1AMJk4mJHBZuaY": {
"message": "Hey",
"senderId": "nKHb1krQokcFdo5VcDusaaj9TLl1",
"timestamp": 1726602415953
},
"-O70WYXD2x6cNmQJAg2n": {
"message": "How are you?",
"senderId": "UJA4AVrSSdZGOJc0bXYbxOcLOB22",
"timestamp": 1726602426203
},
"-O70WbhflR-FBuYtvcNn": {
"message": "Good, thanks !",
"senderId": "nKHb1krQokcFdo5VcDusaaj9TLl1",
"timestamp": 1726602443313
},
"-O70X0TNMogcRrGyKYiJ": {
"message": "Can I exchange X",
"senderId": "UJA4AVrSSdZGOJc0bXYbxOcLOB22",
"timestamp": 1726602548834
},
"-O70X2GLfa2aKc1KOV-C": {
"message": "Yep",
"senderId": "nKHb1krQokcFdo5VcDusaaj9TLl1",
"timestamp": 1726602556185
},
"-O70hzi8OgVY6eRybn3D": {
"message": "Hallo",
"senderId": "UJA4AVrSSdZGOJc0bXYbxOcLOB22",
"timestamp": 1726605687282
}
}
这就是我现在看到的:
我想看的:
因此,即使 User2 在以 User1 身份登录时首先发短信,我也会先看到 mt 消息,然后才看到 User2 消息
我的代码
document.addEventListener("DOMContentLoaded", () => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
const chatId = new URLSearchParams(window.location.search).get("chatId");
if (!chatId) {
console.error("Invalid or missing chatId in URL.");
return;
}
// Retrieve messages ordered by timestamp
const messagesRefForDisplay = firebase
.database()
.ref(`chats/${chatId}/messages`)
.orderByChild("timestamp");
// Use a regular reference for sending messages
const messagesRefForSending = firebase
.database()
.ref(`chats/${chatId}/messages`);
// Function to get username from user ID
function getUsername(userId, callback) {
const userRef = firebase.database().ref(`users/${userId}`);
userRef.once("value", (snapshot) => {
const userData = snapshot.val();
callback(userData.username);
});
}
function formatTimestamp(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString(); // Customize the format if needed
}
// Load messages ordered by timestamp
messagesRefForDisplay.on("child_added", (snapshot) => {
const message = snapshot.val();
getUsername(message.senderId, (username) => {
const messageElement = document.createElement("div");
messageElement.classList.add("message");
const formattedTimestamp = formatTimestamp(message.timestamp);
messageElement.innerHTML = `<span class="sender">${username}:</span> ${message.message} <span class="timestamp">(${formattedTimestamp})</span>`;
document.getElementById("messages").appendChild(messageElement);
// Auto scroll to the bottom after a new message is added
document.getElementById("messages").scrollTop =
document.getElementById("messages").scrollHeight;
});
});
// Send message
document.getElementById("sendMessage").addEventListener("click", () => {
const messageInput = document.getElementById("messageInput");
const messageText = messageInput.value.trim();
if (messageText) {
// Use the unfiltered messagesRef for sending
messagesRefForSending
.push({
message: messageText,
senderId: user.uid, // Use user.uid here
timestamp: Date.now(),
})
.then(() => {
console.log("Message sent successfully");
})
.catch((error) => {
console.error("Error sending message:", error);
});
messageInput.value = ""; // Clear the input
}
});
} else {
console.log("User is not logged in.");
}
});
});
我认为您可能会由于加载用户名而遇到竞争状况。一个简单的修复方法是在开始加载用户名之前立即将元素添加到 HTML:
// Load messages ordered by timestamp
messagesRefForDisplay.on("child_added", (snapshot) => {
const message = snapshot.val();
const messageElement = document.createElement("div");
messageElement.classList.add("message");
document.getElementById("messages").appendChild(messageElement);
getUsername(message.senderId, (username) => {
const formattedTimestamp = formatTimestamp(message.timestamp);
messageElement.innerHTML = `<span class="sender">${username}:</span> ${message.message} <span class="timestamp">(${formattedTimestamp})</span>`;
// Auto scroll to the bottom after a new message is added
document.getElementById("messages").scrollTop =
document.getElementById("messages").scrollHeight;
});
});