-
Notifications
You must be signed in to change notification settings - Fork 0
/
background-script.js
64 lines (57 loc) · 1.87 KB
/
background-script.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
// background-script.js
// 创建右键菜单项
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "translateChineseText",
title: "Translate Replace Input",
contexts: ["editable"],
});
});
// 处理右键菜单项点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "translateChineseText") {
chrome.tabs.sendMessage(tab.id, { action: "translateSelectedText" });
}
});
chrome.commands.onCommand.addListener((command, tab) => {
if (command === "translateSelectedText") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tab.id, {
action: "translateSelectedText",
});
});
}
});
// 监听content-script发来的翻译请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "translate") {
const chineseText = request.text;
translateTextUsingOpenAI(chineseText, sendResponse);
return true; // 表示异步回调
}
});
// 调用OpenAI API进行翻译
async function translateTextUsingOpenAI(chineseText, sendResponse) {
const apiKey = "sk-xxx"; // 替换为您的OpenAI API密钥
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content:
"你是一个翻译引擎,请翻译给到的句子,只需要翻译不需要解释。将句子翻译成英文。",
},
{ role: "user", content: chineseText },
],
}),
});
const jsonResponse = await response.json();
const translatedText = jsonResponse.choices[0].message.content;
sendResponse({ translatedText });
}