-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
81 lines (76 loc) · 2.77 KB
/
background.js
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
70
71
72
73
74
75
76
77
78
79
80
81
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'chatgpt',
title: 'Ask ChatGPT',
contexts: ['selection'],
});
console.log("test");
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'logToBackground') {
console.log.apply(null, request.data);
}
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'chatgpt') {
const selectedText = info.selectionText;
console.log(selectedText);
// Get the saved prompt format and settings
chrome.storage.local.get(['promptFormat', 'chatID', 'focusExistingTab'], (data) => {
const promptFormat = data.promptFormat || 'Explain <prompt>';
const chatID = data.chatID || '';
const formattedPrompt = promptFormat.replace('<prompt>', selectedText);
const chatURL = `https://chatgpt.com/chat/${chatID}`;
if (data.focusExistingTab) {
chrome.tabs.query({ url: ["https://chatgpt.com/c/*", "https://chatgpt.com/g/*", "https://chatgpt.com/*"] }, (tabs) => {
if (tabs.length > 0) {
// Focus on the existing tab
const existingTab = tabs[0];
chrome.tabs.update(existingTab.id, { active: true }, () => {
chrome.scripting.executeScript(
{
target: { tabId: existingTab.id },
files: ['content.js'],
},
() => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
chrome.tabs.sendMessage(existingTab.id, { action: 'sendToChatGPT', prompt: formattedPrompt });
}
);
});
} else {
createNewTab(chatURL, formattedPrompt);
}
});
} else {
createNewTab(chatURL, formattedPrompt);
}
});
}
});
function createNewTab(chatURL, formattedPrompt) {
chrome.tabs.create({ url: chatURL }, (newTab) => {
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (info.status === 'complete' && tabId === newTab.id) {
console.log(newTab.id);
chrome.scripting.executeScript(
{
target: { tabId: tabId },
files: ['content.js'],
},
() => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
chrome.tabs.sendMessage(tabId, { action: 'sendToChatGPT', prompt: formattedPrompt });
}
);
chrome.tabs.onUpdated.removeListener(listener);
}
});
});
}