Захватывать разговор с помощью сценария содержимого.
Сохранить разговор в chrome.storage.local.
Загрузите сохраненный разговор в поле ввода при запуске нового чата.
Однако расширение не работает должным образом. Когда я нажимаю «Сохранить текущий контекст», появляется сообщение «Не удалось записать разговор».
Вот мой код:
manifest.json:< /strong>
Код: Выделить всё
{
"manifest_version": 3,
"name": "AI Context Manager",
"version": "1.0",
"description": "Seamlessly manage conversation context across AI assistant sessions.",
"permissions": ["storage", "activeTab", "scripting"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
Код: Выделить всё
function captureConversation() {
return new Promise((resolve) => {
const selectors = [
'.group\\/conversation .text-message',
'.message',
'.text-base',
'div[role="dialog"]',
'div > div > p',
];
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
for (const selector of selectors) {
const conversationElements = document.querySelectorAll(selector);
if (conversationElements.length > 0) {
const conversation = Array.from(conversationElements).map(el => el.innerText).join('\n');
console.log('Captured conversation using selector:', selector, conversation); // Debugging
observer.disconnect(); // Stop observing once the conversation is captured
resolve(conversation);
return;
}
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
});
}
// Listen for messages from the popup or background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'captureConversation') {
captureConversation().then((conversation) => {
sendResponse({ conversation });
});
return true; // Indicates that the response will be sent asynchronously
}
});
Код: Выделить всё
document.getElementById('save-context').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
// Send a message to the content script to capture the conversation
chrome.tabs.sendMessage(tabs[0].id, { action: 'captureConversation' }, (response) => {
if (response && response.conversation) {
const conversation = response.conversation;
console.log('Conversation to save:', conversation); // Debugging
// Save the conversation to chrome.storage.local
chrome.storage.local.set({ conversation }, () => {
console.log('Conversation saved to chrome.storage.local'); // Debugging
alert('Context saved!');
});
} else {
console.log('No conversation captured.'); // Debugging
alert('Failed to capture conversation.');
}
});
});
});
document.getElementById('load-context').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.storage.local.get(['conversation'], (result) => {
if (result.conversation) {
console.log('Loading conversation:', result.conversation); // Debugging
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: (conversation) => {
// Try multiple selectors to find the input field
const selectors = [
'#prompt-textarea', // Common ID for input field
'textarea', // Generic textarea
'[role="textbox"]', // Common role for input fields
];
for (const selector of selectors) {
const inputField = document.querySelector(selector);
if (inputField) {
console.log('Input field found using selector:', selector); // Debugging
inputField.value = `Previous Context:\n${conversation}\n\n`;
return;
}
}
console.log('No input field found using any selector.'); // Debugging
},
args: [result.conversation]
});
} else {
console.log('No conversation found in storage.'); // Debugging
alert('No saved context found.');
}
});
});
});
chrome.runtime.onInstalled.addListener(() => {
console.log('AI Context Manager installed.');
});
< /code>
Что я пробовал: < /p>
Обновленные селекторы в content.js, чтобы соответствовать структуре DOM Chatgpt.
Добавлено MutationObserver для обработки асинхронного Загрузка сообщений о разговоре.
подтвердило, что разрешение на хранение включено в manifest.json. Ошибка в консоли:
не удалось захватить разговор.
Вопросы:
< ol>
[*] Являются ли селекторы в content.js правильными для текущей структуры Dom's Catchpt? < /p>
< /li>
Есть ли есть Лучший способ обработки асинхронной загрузки сообщений о разговоре? />
Подробнее здесь: https://stackoverflow.com/questions/793 ... om-chatgpt
Мобильная версия