-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbackground.js
More file actions
708 lines (619 loc) · 21.3 KB
/
background.js
File metadata and controls
708 lines (619 loc) · 21.3 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
// 初始化快捷键信息到存储
saveCurrentShortcut();
// 创建右键菜单
createContextMenu();
});
// 保存当前快捷键到存储
async function saveCurrentShortcut() {
try {
const commands = await chrome.commands.getAll();
const translateCommand = commands.find(command => command.name === 'translate-selection');
const shortcut = translateCommand && translateCommand.shortcut ? translateCommand.shortcut : '';
// 保存到本地存储
chrome.storage.local.set({ 'saved_shortcut': shortcut }, () => {
console.log('当前快捷键已保存到存储:', shortcut);
});
} catch (error) {
console.error('保存快捷键信息失败:', error);
}
}
// 监听扩展安装或更新事件,创建右键菜单
chrome.runtime.onStartup.addListener(() => {
// 创建右键菜单
createContextMenu();
});
// 监听快捷键变化事件(Chrome 92+支持)
if (chrome.commands && chrome.commands.onChanged) {
chrome.commands.onChanged.addListener((command) => {
if (command === 'translate-selection') {
console.log('快捷键已变更,正在保存和更新');
saveCurrentShortcut();
createContextMenu();
}
});
}
// 简化的创建菜单函数
function createContextMenu() {
try {
// 先移除现有菜单
chrome.contextMenus.removeAll(() => {
// 从存储中获取快捷键
chrome.storage.local.get('saved_shortcut', (data) => {
const shortcut = data.saved_shortcut ? ` (${data.saved_shortcut})` : '';
// 创建新菜单,包含快捷键提示
chrome.contextMenus.create({
id: "translateSelection",
title: `翻译成人话${shortcut}`,
contexts: ["selection"]
}, () => {
// 检查是否创建成功
if (chrome.runtime.lastError) {
console.error('创建菜单出错:', chrome.runtime.lastError);
} else {
console.log('右键菜单已创建,使用存储的快捷键:', shortcut);
}
});
});
});
} catch (error) {
console.error('创建右键菜单时出错:', error);
// 出错时创建不带快捷键的菜单作为备用
chrome.contextMenus.create({
id: "translateSelection",
title: "翻译成人话",
contexts: ["selection"]
});
}
}
// 在浏览器外部修改快捷键后,重新加载扩展时更新右键菜单
// 这是为了处理在chrome://extensions/shortcuts页面修改快捷键的情况
chrome.management.onEnabled.addListener((extensionInfo) => {
if (extensionInfo.id === chrome.runtime.id) {
// 重新保存当前快捷键并更新菜单
setTimeout(() => {
saveCurrentShortcut();
createContextMenu();
}, 500);
}
});
// 添加一个 Map 来跟踪每个标签页的请求状态
const activeRequests = new Map();
// 默认设置
const defaultSettings = {
baseUrl: 'https://api.deepseek.com/v1/chat/completions',
model: 'deepseek-reasoner',
temperature: 0.7,
promptTemplate: '用通俗易懂的中文解释以下内容:\n\n{text}' // 添加默认提示词模板
};
// 获取设置,优先从云端获取,失败时从本地获取
async function getSettings() {
try {
// 尝试从云端获取设置
const syncSettings = await chrome.storage.sync.get(['apiKey', 'baseUrl', 'model', 'temperature', 'promptTemplate']);
// 如果成功获取到云端设置,同时保存到本地作为备份
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', 'promptTemplate']);
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', 'promptTemplate']);
if (Object.keys(localSettings).length > 0) {
console.log('使用本地存储的设置');
return localSettings;
}
} catch (localError) {
console.error('获取本地设置也失败:', localError);
}
// 如果都失败了,返回默认设置
console.log('使用默认设置');
return { ...defaultSettings };
}
}
// 在顶部声明常量
const MAX_HISTORY_ITEMS = 100;
// 修改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');
}
// 使用提示词模板
const promptTemplate = config.promptTemplate || defaultSettings.promptTemplate;
const prompt = promptTemplate.replace('{text}', text);
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: prompt // 使用处理后的提示词
}],
temperature: config.temperature || defaultSettings.temperature,
stream: true
}),
signal: controller.signal
});
if (!response.ok) {
throw new Error(`API 请求失败: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
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);
// 增强调试,记录实际响应格式
// 检查delta内容是否存在
if (parsed.choices &&
parsed.choices.length > 0 &&
parsed.choices[0].delta &&
parsed.choices[0].delta.content !== undefined) {
const content = parsed.choices[0].delta.content;
// 处理空内容和表情符号
if (content !== null && content !== undefined) {
currentChunk += content;
}
// 添加解析的思维链内容(如果有)
const hasReasoning = parsed.choices[0].delta.reasoning_content !== undefined;
if (hasReasoning) {
const reasoning = parsed.choices[0].delta.reasoning_content;
if (reasoning !== null && reasoning !== undefined) {
currentReasoningChunk += reasoning;
}
}
}
} catch (e) {
console.error('解析错误:', e, '原始数据:', line);
}
}
}
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 已关闭');
}
});
}
// 在成功翻译完成后,保存翻译历史
if (result) {
try {
await saveTranslationHistory(text, result, reasoningContent);
} catch (error) {
console.error('保存翻译历史失败:', error);
}
}
// 清理已完成的请求
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);
}
}
// 添加保存翻译历史的函数
async function saveTranslationHistory(original, translated, reasoning) {
try {
// 获取现有历史
const data = await chrome.storage.local.get('translationHistory');
const history = data.translationHistory || [];
// 检查是否已存在相同的原文,避免重复
const existingIndex = history.findIndex(item => item.original === original);
// 创建新的历史项
const newItem = {
original,
translated,
reasoning,
timestamp: Date.now(),
hasReasoning: reasoning && reasoning.length > 0
};
if (existingIndex >= 0) {
// 更新现有项
history[existingIndex] = newItem;
} else {
// 添加新项到开头
history.unshift(newItem);
}
// 限制历史记录数量
const limitedHistory = history.slice(0, MAX_HISTORY_ITEMS);
// 保存更新后的历史
await chrome.storage.local.set({ translationHistory: limitedHistory });
console.log('翻译历史已保存');
} catch (error) {
console.error('保存翻译历史出错:', error);
}
}
// 添加获取翻译历史的函数
async function getTranslationHistory() {
try {
const data = await chrome.storage.local.get('translationHistory');
return data.translationHistory || [];
} catch (error) {
console.error('获取翻译历史出错:', error);
return [];
}
}
// 修改 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) => {
// 处理options页面发来的快捷键更改消息
if (request.action === 'shortcutChanged') {
console.log(`快捷键已从"${request.oldShortcut}"变更为"${request.newShortcut}"`);
// 保存新快捷键到存储
chrome.storage.local.set({ 'saved_shortcut': request.newShortcut }, () => {
console.log('新快捷键已保存到存储:', request.newShortcut);
// 更新右键菜单
createContextMenu();
// 返回成功响应
sendResponse({ success: true });
});
return true; // 保持消息通道开放以支持异步响应
}
if (request.action === 'getHistory') {
getTranslationHistory()
.then(history => sendResponse({ success: true, history }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
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; // 保持消息通道开放以支持异步响应
}
if (request.action === 'deleteHistoryItem') {
(async () => {
try {
const data = await chrome.storage.local.get('translationHistory');
const history = data.translationHistory || [];
const newHistory = history.filter(item => item.original !== request.original);
await chrome.storage.local.set({ translationHistory: newHistory });
sendResponse({ success: true });
} catch (error) {
console.error('删除历史记录项失败:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
if (request.action === 'clearHistory') {
(async () => {
try {
await chrome.storage.local.set({ translationHistory: [] });
sendResponse({ success: true });
} catch (error) {
console.error('清空历史记录失败:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
if (request.action === 'importHistory') {
(async () => {
try {
const data = await chrome.storage.local.get('translationHistory');
const currentHistory = data.translationHistory || [];
// 合并历史并去重
const mergedHistory = [...request.history];
// 保存到本地
await chrome.storage.local.set({
translationHistory: mergedHistory.slice(0, MAX_HISTORY_ITEMS)
});
sendResponse({ success: true });
} catch (error) {
console.error('导入历史记录失败:', error);
sendResponse({ success: false, error: error.message });
}
})();
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);
});
// 监听快捷键命令
chrome.commands.onCommand.addListener((command) => {
if (command === "translate-selection") {
console.log('快捷键命令被触发:', command);
executeTranslation();
}
});
// 快捷键翻译功能执行函数
async function executeTranslation() {
try {
// 获取当前活动标签页
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) {
console.error('找不到活动标签页');
return;
}
// 检查URL是否支持
if (!tab.url || !tab.url.startsWith('http')) {
console.error('不支持在此协议页面使用快捷键翻译功能');
return;
}
console.log('正在获取选中文本...');
// 获取页面上的选中文本
let selectedText = '';
try {
const [result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => window.getSelection().toString().trim()
});
selectedText = result.result;
} catch (error) {
console.error('获取选中文本失败:', error);
return;
}
if (!selectedText) {
console.log('没有选中文本');
return;
}
console.log('选中文本:', selectedText.substring(0, 50) + (selectedText.length > 50 ? '...' : ''));
// 尝试发送消息给content script显示翻译弹窗
try {
console.log('尝试发送翻译请求到content script...');
await chrome.tabs.sendMessage(tab.id, {
action: 'showTranslationPopup',
text: selectedText
});
} catch (error) {
console.log('第一次发送失败,尝试注入content script:', error);
// 如果消息发送失败,可能是因为content script还未注入,尝试注入
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content/content.js']
});
// 注入后等待短暂时间确保脚本加载
await new Promise(resolve => setTimeout(resolve, 300));
// 重试发送消息
console.log('注入成功,重试发送消息...');
await chrome.tabs.sendMessage(tab.id, {
action: 'showTranslationPopup',
text: selectedText
});
} catch (injectionError) {
console.error('注入content script失败:', injectionError);
}
}
} catch (error) {
console.error('快捷键翻译执行错误:', error);
}
}