function createNotification(title, message) {
chrome.notifications.create({
type: "basic",
iconUrl: chrome.runtime.getURL("icon.png"),
title: title,
message: message
});
}
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "findInChatGPT",
title: "Найти в ChatGPT",
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "findInChatGPT") {
if (!tab || !tab.id) {
console.error("Tab information is missing.");
createNotification("Ошибка", "Не удалось получить информацию о вкладке.");
return;
}
if (tab.url && (tab.url.startsWith('http://') || tab.url.startsWith('https://'))) {
try {
const injectionResults = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => window.getSelection().toString()
});
const selectedText = injectionResults && injectionResults[0] && injectionResults[0].result;
if (!selectedText || selectedText.trim() === "") {
createNotification("Внимание", "Не выделен текст.");
return;
}
try {
const response = await fetchChatGPTResponse(selectedText);
createNotification("Ответ от ChatGPT", response);
} catch (error) {
console.error("Ошибка при запросе к ChatGPT:", error);
createNotification("Ошибка", error.message || "Произошла ошибка при запросе к ChatGPT.");
}
} catch (error) {
console.error("Injection error:", error);
createNotification("Ошибка", "Не удалось получить выделенный текст: " + error.message);
}
} else {
createNotification("Внимание", "Действие доступно только на веб-страницах (http:// или https://).");
console.log("Context menu clicked on a non-web page:", tab?.url);
}
}
});
async function fetchChatGPTResponse(text) {
try {
const data = await chrome.storage.sync.get('apiKey');
const apiKey = data.apiKey;
if (!apiKey) {
throw new Error("API ключ не найден. Пожалуйста, введите ключ в настройках расширения.");
}
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: text }]
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData?.error?.message || `HTTP error ${response.status}`);
}
const responseData = await response.json();
if (!responseData?.choices?.length) {
throw new Error("Неожиданный формат ответа от ChatGPT");
}
return responseData.choices[0].message.content.trim();
} catch (error) {
console.error("Ошибка в fetchChatGPTResponse:", error);
throw error;
}
}