-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
72 lines (48 loc) · 1.96 KB
/
Copy pathscript.js
File metadata and controls
72 lines (48 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const chatBox = document.getElementById("chat-box"); // Chat container
const userInput = document.getElementById("user-input"); // Input field
const sendBtn = document.getElementById("send-btn"); // Send button
function addMessage(message, className){
const messageDiv = document.createElement('div')
messageDiv.classList.add("message", className);
messageDiv.textContent = message;
chatBox.appendChild(messageDiv);
chatBox.scrollTop = chatBox.scrollHeight
} // Function to add message to chat box
function showTyping(){
const typingDiv = document.createElement('div')
typingDiv.classList.add("message", "bot-message");
typingDiv.textContent = "Gemini is typing...";
chatBox.appendChild(typingDiv);
chatBox.scrollTop = chatBox.scrollHeight
return typingDiv;
} // Function to show typing indicator
async function getBotReply(userMessage){
const backendURL = "http://localhost:3001/api/v1/chat";
console.log(userMessage)
const reply = JSON.stringify({message: userMessage})
console.log(reply);
const response = await fetch(backendURL, {
method: "POST",
headers: {"Content-Type" : "application/json"},
body: JSON.stringify({message: userMessage})
})
return response;
} // Function to get bot reply from backend
sendBtn.onclick = async () =>{
const message = userInput.value.trim();
if(message === "") return;
addMessage(message, "user-message");
userInput.value = "";
const typingDiv = showTyping();
const botReply = await getBotReply(message);
typingDiv.remove();
addMessage(botReply, 'bot-message');
localStorage.setItem("chatHistory", chatBox.innerHTML)
} // Send button click event
userInput.addEventListener('keypress', (e)=>{
if(e.key === "Enter") sendBtn.click();
})
window.addEventListener('load', ()=>{
const savedChat = localStorage.getItem("chatHistory");
if(savedChat) chatBox.innerHTML = savedChat;
}) // Load chat history on page load