-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbackground.js
383 lines (345 loc) · 11.5 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "translateSelection",
title: "翻译成人话",
contexts: ["selection"]
});
});
// 添加一个 Map 来跟踪每个标签页的请求状态
const activeRequests = new Map();
// 默认设置
const defaultSettings = {
baseUrl: 'https://api.deepseek.com/v1/chat/completions',
model: 'deepseek-reasoner',
temperature: 0.7
};
// 获取设置,优先从云端获取,失败时从本地获取
async function getSettings() {
try {
// 尝试从云端获取设置
const syncSettings = await chrome.storage.sync.get(['apiKey', 'baseUrl', 'model', 'temperature']);
// 如果成功获取到云端设置,同时保存到本地作为备份
if (Object.keys(syncSettings).length > 0) {
try {
await chrome.storage.local.set(syncSettings);
console.log('设置已同步到本地存储');
} catch (error) {
console.error('保存设置到本地存储失败:', error);
}
return syncSettings;
}
// 如果云端没有设置,尝试从本地获取
console.log('云端没有设置,尝试从本地获取');
const localSettings = await chrome.storage.local.get(['apiKey', 'baseUrl', 'model', 'temperature']);
if (Object.keys(localSettings).length > 0) {
console.log('使用本地存储的设置');
return localSettings;
}
// 如果本地也没有,返回默认设置
console.log('使用默认设置');
return { ...defaultSettings };
} catch (error) {
console.error('获取云端设置失败,尝试从本地获取:', error);
try {
// 尝试从本地获取设置
const localSettings = await chrome.storage.local.get(['apiKey', 'baseUrl', 'model', 'temperature']);
if (Object.keys(localSettings).length > 0) {
console.log('使用本地存储的设置');
return localSettings;
}
} catch (localError) {
console.error('获取本地设置也失败:', localError);
}
// 如果都失败了,返回默认设置
console.log('使用默认设置');
return { ...defaultSettings };
}
}
// 修改 translateText 函数
async function translateText(text, tabId) {
// 如果存在旧的请求,则中止它
if (activeRequests.has(tabId)) {
const oldController = activeRequests.get(tabId);
oldController.abort();
activeRequests.delete(tabId);
}
// 创建新的 AbortController
const controller = new AbortController();
activeRequests.set(tabId, controller);
// 获取设置,优先从云端获取,失败时从本地获取
const config = await getSettings();
if (!config.apiKey) {
throw new Error('请先在设置中配置 API Key');
}
try {
const response = await fetch(config.baseUrl || defaultSettings.baseUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.apiKey}`
},
body: JSON.stringify({
model: config.model || defaultSettings.model,
messages: [{
role: 'user',
content: `用通俗易懂的中文解释以下内容:\n\n${text}`
}],
temperature: config.temperature || defaultSettings.temperature,
stream: true
}),
signal: controller.signal // 添加 signal 以支持中止请求
});
if (!response.ok) {
throw new Error(`API 请求失败: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let result = '';
let reasoningContent = ''; // 添加思维链内容的变量
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let currentChunk = '';
let currentReasoningChunk = ''; // 添加当前思维链内容块
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices[0].delta.content;
const hasReasoning = 'reasoning_content' in parsed.choices[0].delta;
const reasoning = hasReasoning ? parsed.choices[0].delta.reasoning_content : null;
if (content) {
currentChunk += content;
}
if (reasoning) {
currentReasoningChunk += reasoning;
}
} catch (e) {
console.error('解析错误:', e);
}
}
}
if (currentChunk || currentReasoningChunk) {
result += currentChunk;
reasoningContent += currentReasoningChunk;
if (tabId) {
// 右键菜单翻译使用 safeSendMessage
await safeSendMessage(tabId, {
action: 'updateTranslation',
content: result,
hasReasoning: reasoningContent.length > 0,
reasoningContent: reasoningContent,
done: false
});
} else {
// popup 翻译直接使用 runtime.sendMessage
let popupClosed = false;
chrome.runtime.sendMessage({
action: 'updateTranslation',
content: result,
hasReasoning: reasoningContent.length > 0,
reasoningContent: reasoningContent,
done: false
}, () => {
if (chrome.runtime.lastError) {
popupClosed = true;
}
});
// 如果 popup 已关闭,中止翻译
if (popupClosed) {
controller.abort();
return;
}
}
}
}
// 发送完成信号
if (tabId) {
await safeSendMessage(tabId, {
action: 'updateTranslation',
content: result,
hasReasoning: reasoningContent.length > 0,
reasoningContent: reasoningContent,
done: true
});
} else {
// popup 翻译的完成信号
chrome.runtime.sendMessage({
action: 'updateTranslation',
content: result,
hasReasoning: reasoningContent.length > 0,
reasoningContent: reasoningContent,
done: true
}, () => {
if (chrome.runtime.lastError) {
console.log('popup 已关闭');
}
});
}
// 清理已完成的请求
activeRequests.delete(tabId);
return result;
} catch (error) {
// 区分错误类型
if (error.name === 'AbortError') {
console.log('翻译请求已中止');
return;
}
if (error.message.includes('Receiving end does not exist')) {
console.log('连接已断开,可能是页面已关闭');
return;
}
// 只有真正需要用户知道的错误才抛出
if (error.message.includes('API Key') ||
error.message.includes('API 请求失败') ||
error.message.includes('rate limit')) {
throw error;
}
// 其他错误只记录不抛出
console.error('翻译过程中出现错误:', error);
}
}
// 修改 safeSendMessage 函数
async function safeSendMessage(tabId, message) {
try {
// popup 请求不需要使用 tabs.sendMessage
if (!tabId) {
return; // popup 的消息已经在调用处直接使用 runtime.sendMessage 发送
}
// 检查标签页是否存在
const tab = await chrome.tabs.get(tabId).catch(() => null);
if (!tab) {
console.log('标签页不存在');
return;
}
// 发送消息到指定标签页
chrome.tabs.sendMessage(tabId, message, () => {
if (chrome.runtime.lastError) {
// 连接断开或页面关闭时静默处理
if (chrome.runtime.lastError.message.includes('Receiving end does not exist')) {
console.log('目标页面可能已关闭');
return;
}
// 其他错误才记录
console.error('消息发送失败:', chrome.runtime.lastError);
}
});
} catch (error) {
// 静默处理连接相关错误
if (error.message.includes('Receiving end does not exist')) {
console.log('目标页面可能已关闭');
return;
}
console.error('消息发送失败:', error);
}
}
// 修改右键菜单点击处理
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "translateSelection" && tab?.id) {
try {
if (!tab.url.startsWith('http')) {
alert('不支持在此协议页面使用翻译功能');
return;
}
// 发送显示弹窗的消息
try {
await chrome.tabs.sendMessage(tab.id, {
action: 'showTranslationPopup',
text: info.selectionText
});
} catch (error) {
// 如果消息发送失败,可能是因为content script还未注入
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content/content.js']
});
// 重试发送消息
await chrome.tabs.sendMessage(tab.id, {
action: 'showTranslationPopup',
text: info.selectionText
});
}
} catch (error) {
console.error('处理右键菜单点击失败:', error);
}
}
});
// 修改消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'translate') {
const tabId = request.source === 'popup' ? null : sender.tab.id;
(async () => {
try {
const result = await translateText(request.text, tabId);
if (result) {
if (request.source === 'popup') {
chrome.runtime.sendMessage({
action: 'updateTranslation',
content: result,
done: true
}, () => {
if (chrome.runtime.lastError) {
console.log('popup 已关闭');
}
});
}
sendResponse({ success: true });
}
} catch (error) {
// 只有重要错误才发送给用户
if (error.message.includes('API Key') ||
error.message.includes('API 请求失败') ||
error.message.includes('rate limit')) {
if (request.source === 'popup') {
chrome.runtime.sendMessage({
action: 'updateTranslation',
error: error.message,
done: true
});
} else {
await safeSendMessage(tabId, {
action: 'updateTranslation',
error: error.message,
done: true
});
}
sendResponse({ success: false, error: error.message });
} else {
// 其他错误静默处理
console.error('非关键错误:', error);
sendResponse({ success: false });
}
}
})();
return true;
}
if (request.action === 'cleanup') {
const tabId = sender.tab?.id || null; // popup 请求时 tabId 为 null
cleanupRequest(tabId).then(() => {
sendResponse({ success: true });
});
return true; // 保持消息通道开放以支持异步响应
}
return false;
});
// 修改清理函数
async function cleanupRequest(tabId) {
if (activeRequests.has(tabId)) {
const controller = activeRequests.get(tabId);
controller.abort();
activeRequests.delete(tabId);
// 添加小延迟确保清理完成
await new Promise(resolve => setTimeout(resolve, 100));
}
}
// 监听标签页关闭事件
chrome.tabs.onRemoved.addListener((tabId) => {
cleanupRequest(tabId);
});