From 8a1728f0833c9263daa8ab63cb0649268a6799e5 Mon Sep 17 00:00:00 2001 From: cdez Date: Fri, 28 Mar 2025 18:29:23 -0700 Subject: [PATCH] Add new features to the webclient, and allow for message history to be displayed in the webclient. --- chatserver/templates/index.html | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/chatserver/templates/index.html b/chatserver/templates/index.html index 0c23526..81fd396 100644 --- a/chatserver/templates/index.html +++ b/chatserver/templates/index.html @@ -159,6 +159,25 @@ console.log('Joining chat room:', { username: username, chat_room: chatRoom }); socket.emit('join', { username: username, chat_room: chatRoom }); + // Fetch message history for the initial chat room + fetch(`/get_history?chat_room=${chatRoom}`) + .then(response => response.json()) + .then(data => { + if (data.messages) { + data.messages.forEach(message => { + const messageElement = document.createElement('div'); + messageElement.textContent = message; + chatDiv.appendChild(messageElement); + }); + chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom + } else { + console.log("No message history found for this chat room."); + } + }) + .catch(error => { + console.error("Error fetching message history:", error); + }); + // Log connection status socket.on('connect', () => { console.log('Connected to WebSocket server'); @@ -214,6 +233,25 @@ console.log(`Switched to chat room: ${chatRoom}`); socket.emit('join', { username: username, chat_room: chatRoom }); chatDiv.innerHTML = ""; // Clear the chat history + + // Fetch message history for the new chat room + fetch(`/get_history?chat_room=${chatRoom}`) + .then(response => response.json()) + .then(data => { + if (data.messages) { + data.messages.forEach(message => { + const messageElement = document.createElement('div'); + messageElement.textContent = message; + chatDiv.appendChild(messageElement); + }); + chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom + } else { + console.log("No message history found for this chat room."); + } + }) + .catch(error => { + console.error("Error fetching message history:", error); + }); } } @@ -249,6 +287,17 @@ } } + // Reconnect to the server + function reconnectServer() { + if (!socket.connected) { + console.log("Reconnecting to the server..."); + socket.connect(); + alert("Reconnected to the server."); + } else { + alert("You are already connected to the server."); + } + } + // Toggle between light mode and dark mode function toggleTheme() { const body = document.body;