-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
88 lines (87 loc) · 2.81 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
82
83
84
85
86
87
88
const apiKey = 'YOUR_OPENAI_API_KEY';
chrome.tabs.onActivated.addListener((tab) => {
console.log("background.js installed in new tab");
if (tab.url?.startsWith("chrome://")) return undefined;
chrome.scripting.executeScript({
target: { tabId: tab.tabId },
files: ["content.js"],
});
// Context Menu Creation
chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({
title: "Professionalize",
id: "Professionalize",
contexts: ["selection"],
});
chrome.contextMenus.create({
title: "Grammar Fix",
id: "GrammarFix",
contexts: ["selection"],
});
chrome.contextMenus.create({
title: "Enhance Language",
id: "Enhance",
contexts: ["selection"],
});
});
});
chrome.contextMenus.onClicked.addListener(function (info, tab) {
console.log("tab id hai bhai yeh" + tab.id);
var prompt = "";
if (info.menuItemId === "Professionalize") {
prompt = `Professionalize this text:${info.selectionText}`;
} else if (info.menuItemId === "GrammarFix") {
prompt = `Fix grammer: ${info.selectionText}`;
} else if (info.menuItemId === "Enhance") {
prompt = `Enhance the language of this text:${info.selectionText}`;
}
const apiUrl = "https://api.openai.com/v1/completions"; // Updated engine endpoint
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-002", // Specify the engine here, not "model" text-davinci-002
prompt: prompt,
max_tokens: 150, // Adjust max tokens based on your needs
}),
})
.then((response) => response.json())
.then((data) => {
if (data.error) {
// Handle API error response
console.error("OpenAI API Error:", data.error.message);
} else if (
data.choices &&
data.choices.length > 0 &&
data.choices[0].text
) {
const replacementtext = data.choices[0].text.trim();
// Route to content.js to replace text
if (info.menuItemId === "Professionalize") {
chrome.tabs.sendMessage(tab.id, {
action: "replaceText",
replacement: replacementtext,
});
} else if (info.menuItemId === "GrammarFix") {
chrome.tabs.sendMessage(tab.id, {
action: "replaceText",
replacement: replacementtext,
});
} else if (info.menuItemId === "Enhance") {
chrome.tabs.sendMessage(tab.id, {
action: "replaceText",
replacement: replacementtext,
});
}
} else {
console.error("Invalid API response format:", data);
}
})
.catch((error) => {
// Handle other errors (e.g., network issues)
console.error("Error:", error);
});
});