//Проверяет есть ли в local storag история сообщений function isChatHistoryExists(key) {…
- User
//Проверяет есть ли в local storag история сообщений function isChatHistoryExists(key) { // Проверяем наличие данных по ключу 'chatHistory' в local storage return localStorage.getItem(
chatHistory_${key}) !== null; }//Сохраняет историю чата в local storage (метка chatHistory_key) function saveChatHistory(mss, key) { let dialog = { id:
dialog_${key}, title: "Диалог с Саппортом", messages: mss }; localStorage.setItem(chatHistory_${key}, JSON.stringify(dialog)); }//Считывает историю чата из local storage (метка chatHistory_key) function loadChatHistory(key) { const stored = localStorage.getItem(
chatHistory_${key}); const x = stored ? JSON.parse(stored) : []; console.log(x.messages); return x.messages; }// Инициализация чата. function initializeChatHistory() { // Загружаем существующую историю, если она есть let mss;
code// Проверяем наличие данных в local storage по ключу 'chatHistory_1' if (isChatHistoryExists(1)) { // Если история существует, загружаем её в массив mss mss = loadChatHistory(1); console.log('История сообщений загружена из local storage.'); // Проверяем, пустой ли загруженный массив if (mss.length === 0) { console.log('Загруженная история пуста.'); } else { console.log(`Загруженная история содержит ${mss.length} сообщений.`); //Вывод переписки на экран showmessages(mss); //Прокрутка страницы до конца var block = document.getElementById("parent"); block.scrollTop = block.scrollHeight; //Фокус на поле ввода document.getElementById("prompt").focus(); } } else { // Если история не существует, инициализируем пустой массив mss = []; // Используем функцию для сохранения пустого массива saveChatHistory(mss, 1); console.log('История сообщений не найдена. Создана и сохранена новая, пустая история.'); } // В этом месте mss будет содержать либо загруженные данные, либо пустой массив return mss;}
- Assistant
Your JavaScript code is designed to manage and initialize chat history using the browser's local storage. Here’s a breakdown of the main components and how they function:
-
Checking if Chat History Exists: The
isChatHistoryExistsfunction verifies whether there is an existing chat history saved under a specific key in local storage. It returnstrueif data is found; otherwise, it returnsfalse.javascriptfunction isChatHistoryExists(key) { return localStorage.getItem(`chatHistory_${key}`) !== null; } -
Saving Chat History: The
saveChatHistoryfunction saves a given chat history, represented as a list of messages (mss), to local storage. It stores this data under a key that includeschatHistory_followed by a unique key (e.g.,chatHistory_1).javascriptfunction saveChatHistory(mss, key) { let dialog = { id: `dialog_${key}`, title: "Диалог с Саппортом", messages: mss }; localStorage.setItem(`chatHistory_${key}`, JSON.stringify(dialog)); } -
Loading Chat History: The
loadChatHistoryfunction retrieves and parses the chat history associated with a specified key from local storage. If no data is found, it returns an empty array.javascriptfunction loadChatHistory(key) { const stored = localStorage.getItem(`chatHistory_${key}`); const x = stored ? JSON.parse(stored) : []; console.log(x.messages); return x.messages; } -
Initializing Chat History: The
initializeChatHistoryfunction orchestrates the process of checking, loading, and displaying chat history. If a history is found, it will load and display it; otherwise, it creates a new history record and saves an empty array.javascriptfunction initializeChatHistory() { let mss; // Check for existing chat history if (isChatHistoryExists(1)) { mss = loadChatHistory(1); console.log('История сообщений загружена из local storage.'); if (mss.length === 0) { console.log('Загруженная история пуста.'); } else { console.log(`Загруженная история содержит ${mss.length} сообщений.`); showmessages(mss); var block = document.getElementById("parent"); block.scrollTop = block.scrollHeight; document.getElementById("prompt").focus(); } } else { mss = []; saveChatHistory(mss, 1); console.log('История сообщений не найдена. Создана и сохранена новая, пустая история.'); } return mss; } -
Supporting Functions:
showmessages(mss)is presumably a function that displays messages on the screen.- Scrolling functionality ensures the chat interface is always scrolled to the newest messages.
- The focus is set to the input field to facilitate user interaction.
This code provides a basic framework for chat history management but relies on external functions like
showmessagesfor message rendering. Amendments might be necessary to adapt this code snippet to different environments or to accommodate more complex requirements. -