const SESSION_PRESET_KEY = 'enhancedChat_preResetHistory';
const SESSION_POSTSET_KEY = 'enhancedChat_postResetHistory';
// Initialize message histories
let preResetHistory = JSON.parse(sessionStorage.getItem(SESSION_PRESET_KEY)) || [];
let postResetHistory = JSON.parse(sessionStorage.getItem(SESSION_POSTSET_KEY)) || [];
const messageWrapSelector = '.bubble-wrap.svelte-1e1jlin'; // Adjust as needed based on the chat's structure
const inputBoxSelector = 'textarea[data-testid="textbox"]'; // Ensure this reflects the correct input field
// Initialize the MutationObserver
initializeObservers();
function initializeObservers() {
const messageWrap = document.querySelector(messageWrapSelector);
if (!messageWrap) {
console.error("Message wrap not found. Please verify the selector.");
return; // Exit if the chat message wrapper is not found.
}
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1 && node.classList.contains('message-row')) {
handleNewMessage(node.innerText.trim());
}
});
});
});
observer.observe(messageWrap, { childList: true, subtree: true });
// Set up listener for user command input
const inputBox = document.querySelector(inputBoxSelector);
if (inputBox) {
inputBox.addEventListener('keydown', handleUserCommand);
} else {
console.error("Input box not found. Please verify the selector.");
}
}
function handleNewMessage(messageText) {
console.log('New message detected:', messageText);
postResetHistory.push(messageText); // Store new messages in post-reset history
storeChatHistory(); // Update session storage with new data
}
function handleUserCommand(event) {
const inputBox = document.querySelector(inputBoxSelector);
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault(); // Prevent new lines from being added to the chat
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve') {
saveChatHistory(); // Call to save histories
inputBox.value = ''; // Clear input after saving
} else if (command === 'svr') {
copyChatHistoryToClipboard(); // Call to copy chat history
inputBox.value = ''; // Clear input after copying
}
}
}
function storeChatHistory() {
sessionStorage.setItem(SESSION_PRESET_KEY, JSON.stringify(preResetHistory));
sessionStorage.setItem(SESSION_POSTSET_KEY, JSON.stringify(postResetHistory));
console.log('Chat histories saved in session storage:', { preResetHistory, postResetHistory });
}
function saveChatHistory() {
console.log("Saving chat history...");
const zip = new JSZip();
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Save both histories into the zip file
zip.file('pre_reset_history.txt', preResetHistory.join('\n'));
zip.file('post_reset_history.txt', postResetHistory.join('\n'));
// Generate the zip file and trigger download
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_histories_${timestamp}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
console.log('Chat histories saved successfully.');
});
}
function copyChatHistoryToClipboard() {
console.log("Copying chat history to clipboard...");
const chatContent = postResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Post-reset chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
// Optionally load previous state on script load
window.addEventListener('load', () => {
console.log('Chat monitor script loaded and initialized.');
});
})();
The provided code is a userscript designed to enhance a chat application by enabling the storage, retrieval, and management of chat histories. It specifically focuses on two types of histories: 'pre-reset' and 'post-reset' histories. Below is a breakdown of the script functionality:
Key Features:
Chat History Management:
The script stores incoming messages into postResetHistory each time a new message is detected in the chat interface.
A separate history, preResetHistory, is initialized but not actively populated in the provided script; this could be used for storing messages prior to a specific event or reset.
MutationObserver:
The script uses a MutationObserver to monitor the chat window for new messages. When messages are added, they are processed and stored.
User Commands:
The input box listens for specific commands:
sve: Saves chat history to a ZIP file.
svr: Copies the post-reset history to the clipboard.
File Handling:
When saving history, it creates a ZIP file that includes two text files: one for preResetHistory and another for postResetHistory.
Session Storage:
The script utilizes sessionStorage to keep track of chat histories across page reloads.
Detailed Breakdown of Code Sections:
Initialization:
The script begins by setting keys for session storage and initializing message histories.
Selectors:
It defines selectors for the message wrapper and input box. These may need adjustments based on the actual HTML structure of the chat app.
MutationObserver Setup:
javascript
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
// Processing new messages
});
});
Observes the specified message wrapper for any added nodes (new messages).
Handling New Messages:
javascript
function handleNewMessage(messageText) {
postResetHistory.push(messageText);
storeChatHistory();
}
New messages are processed and stored.
Command Handling:
javascript
function handleUserCommand(event) {
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve') {
saveChatHistory();
} else if (command === 'svr') {
copyChatHistoryToClipboard();
}
}
Listens for specific key events and matches them against predefined commands.
File Saving and Clipboard Copying:
Using the JSZip library, the script generates a ZIP file containing the chat histories for download.
It also uses the Clipboard API to copy chat histories to the clipboard.
Usage
To use the script:
Ensure you have a compatible userscript manager like Tampermonkey or Greasemonkey installed in your web browser.
Add the script to your userscript manager.
Navigate to the chat application as specified in the @match section.
Use the defined commands in the input box to save or copy chat histories.
Considerations
Verify all selectors to ensure they match the actual elements in the chat application's DOM.
The use of session storage may limit the histories to the browser session; consider implementing persistent storage if longer retention is necessary.
Be aware of potential limitations with the Clipboard API regarding user interaction and permissions.
Ensure that the ZIP file generation with JSZip does not impact performance, especially with large chat histories.
Overall, the script enhances the functionality of the chat application significantly by allowing users to manage their chat histories effectively.
const SESSION_PRESET_KEY = 'enhancedChat_preResetHistory';
const SESSION_POSTSET_KEY = 'enhancedChat_postResetHistory';
// Initialize message histories
let preResetHistory = JSON.parse(sessionStorage.getItem(SESSION_PRESET_KEY)) || [];
let postResetHistory = JSON.parse(sessionStorage.getItem(SESSION_POSTSET_KEY)) || [];
const messageWrapSelector = '.bubble-wrap.svelte-1e1jlin'; // Adjust as needed based on the chat's structure
const inputBoxSelector = 'textarea[data-testid="textbox"]'; // Ensure this reflects the correct input field
// Initialize the MutationObserver
initializeObservers();
function initializeObservers() {
const messageWrap = document.querySelector(messageWrapSelector);
if (!messageWrap) {
console.error("Message wrap not found. Please verify the selector.");
return; // Exit if the chat message wrapper is not found.
}
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1 && node.classList.contains('message-row')) {
handleNewMessage(node.innerText.trim());
}
});
});
});
observer.observe(messageWrap, { childList: true, subtree: true });
// Set up listener for user command input
const inputBox = document.querySelector(inputBoxSelector);
if (inputBox) {
inputBox.addEventListener('keydown', handleUserCommand);
} else {
console.error("Input box not found. Please verify the selector.");
}
}
function handleNewMessage(messageText) {
console.log('New message detected:', messageText);
postResetHistory.push(messageText); // Store new messages in post-reset history
storeChatHistory(); // Update session storage with new data
}
function handleUserCommand(event) {
const inputBox = document.querySelector(inputBoxSelector);
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault(); // Prevent new lines from being added to the chat
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve') {
saveChatHistory(); // Call to save histories
inputBox.value = ''; // Clear input after saving
} else if (command === 'svr') {
copyChatHistoryToClipboard(); // Call to copy chat history
inputBox.value = ''; // Clear input after copying
}
}
}
function storeChatHistory() {
sessionStorage.setItem(SESSION_PRESET_KEY, JSON.stringify(preResetHistory));
sessionStorage.setItem(SESSION_POSTSET_KEY, JSON.stringify(postResetHistory));
console.log('Chat histories saved in session storage:', { preResetHistory, postResetHistory });
}
function saveChatHistory() {
console.log("Saving chat history...");
const zip = new JSZip();
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Save both histories into the zip file
zip.file('pre_reset_history.txt', preResetHistory.join('\n'));
zip.file('post_reset_history.txt', postResetHistory.join('\n'));
// Generate the zip file and trigger download
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_histories_${timestamp}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
console.log('Chat histories saved successfully.');
});
}
function copyChatHistoryToClipboard() {
console.log("Copying chat history to clipboard...");
const chatContent = postResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Post-reset chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
// Optionally load previous state on script load
window.addEventListener('load', () => {
console.log('Chat monitor script loaded and initialized.');
});
})();
This userscript, titled EnhancedChatality, is designed to enhance the functionality of a chat application hosted at https://yuntian-deng-chatgpt.hf.space/. Below is an overview of its functionality, followed by a refinement of the code.
Key Features of the Script
Message Monitoring: It tracks newly added messages in the chat and saves them to a history stored in the browser's session storage.
User Commands:
Save Command (sve): This command allows users to save their chat history to a .zip file containing both pre-reset and post-reset histories.
Copy Command (svr): This command lets users copy their post-reset chat history to the clipboard.
Data Storage: The script utilizes the sessionStorage API to persist chat histories temporarily for the duration of the browser session.
ZIP File Generation: Using the JSZip library, it packages the chat histories into a downloadable ZIP file.
Code Refinement
The following is a refined version of the code with added clarity, comments, and slight optimizations:
javascript
// ==UserScript==
// @name EnhancedChatality
// @version 9000.1
// @description Handles Unhandlablaments
// @match *://yuntian-deng-chatgpt.hf.space/*
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
/* global JSZip */
(function () {
'use strict';
// Keys for session storage
const SESSION_PRESET_KEY = 'enhancedChat_preResetHistory';
const SESSION_POSTSET_KEY = 'enhancedChat_postResetHistory';
// Initialize message histories from session storage
let preResetHistory = JSON.parse(sessionStorage.getItem(SESSION_PRESET_KEY)) || [];
let postResetHistory = JSON.parse(sessionStorage.getItem(SESSION_POSTSET_KEY)) || [];
// DOM selectors (make sure these match the application's structure)
const messageWrapSelector = '.bubble-wrap.svelte-1e1jlin';
const inputBoxSelector = 'textarea[data-testid="textbox"]';
// Initialize the MutationObserver
initializeObservers();
function initializeObservers() {
const messageWrap = document.querySelector(messageWrapSelector);
if (!messageWrap) {
console.error("Message wrap not found. Please verify the selector.");
return;
}
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
// Check if the added node is a new chat message
if (node.nodeType === 1 && node.classList.contains('message-row')) {
handleNewMessage(node.innerText.trim());
}
});
});
});
observer.observe(messageWrap, { childList: true, subtree: true });
// Set up listener for user command input
const inputBox = document.querySelector(inputBoxSelector);
if (inputBox) {
inputBox.addEventListener('keydown', handleUserCommand);
} else {
console.error("Input box not found. Please verify the selector.");
}
}
function handleNewMessage(messageText) {
console.log('New message detected:', messageText);
postResetHistory.push(messageText);
storeChatHistory(); // Update session storage with new data
}
function handleUserCommand(event) {
const inputBox = document.querySelector(inputBoxSelector);
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault(); // Prevent new line on Enter key press
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve') {
saveChatHistory(); // Save the chat history to a file
inputBox.value = ''; // Clear input after saving
} else if (command === 'svr') {
copyChatHistoryToClipboard(); // Copy post-reset history to clipboard
inputBox.value = ''; // Clear input after copying
}
}
}
function storeChatHistory() {
sessionStorage.setItem(SESSION_PRESET_KEY, JSON.stringify(preResetHistory));
sessionStorage.setItem(SESSION_POSTSET_KEY, JSON.stringify(postResetHistory));
console.log('Chat histories saved in session storage:', {
preResetHistory,
postResetHistory
});
}
function saveChatHistory() {
console.log("Saving chat history...");
const zip = new JSZip();
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Save both histories into the zip file
zip.file('pre_reset_history.txt', preResetHistory.join('\n'));
zip.file('post_reset_history.txt', postResetHistory.join('\n'));
// Generate the zip file and trigger download
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_histories_${timestamp}.zip`;
document.body.appendChild(a);
a.click(); // Trigger download
document.body.removeChild(a); // Clean up
console.log('Chat histories saved successfully.');
});
}
function copyChatHistoryToClipboard() {
console.log("Copying chat history to clipboard...");
const chatContent = postResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Post-reset chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
// Log initialization
window.addEventListener('load', () => {
console.log('Chat monitor script loaded and initialized.');
});
})();
Improvements and Considerations
Comments and Clarity: Added comments throughout the script improve its readability and maintainability.
Selector Verification: It is crucial to verify that the CSS selectors (messageWrapSelector and inputBoxSelector) match the actual DOM elements of the chat application.
Error Management: Basic error messages help troubleshoot issues with DOM element queries.
Use of Console: Extensive use of console.log statements assists in debugging and provides feedback during execution.
This refined script provides a comprehensive chat management tool while maintaining clarity and functionality. Adjust it as needed based on any structural changes in the chat application.