-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1362 lines (1191 loc) · 45.8 KB
/
background.js
File metadata and controls
1362 lines (1191 loc) · 45.8 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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 截圖翻譯器後台服務
console.log('Background script loading...');
class ScreenshotTranslator {
constructor() {
console.log('ScreenshotTranslator constructor called');
this.isProcessing = false;
this.MAX_HISTORY = 500; // 历史记录和生词本最大条数
this.setupMessageListeners();
this.setupInstallListener();
// 检查是否是首次启动(开发者模式下 onInstalled 不会触发)
this.checkFirstRun();
console.log('ScreenshotTranslator initialized');
}
// 获取通知文本(根据浏览器语言)
getNotificationText() {
const lang = navigator.language || 'en';
const langMap = {
'zh': { title: 'QuickTranslate 安装完成', msg: 'QuickTranslate已安装!请点击插件图标开始使用。温馨提示:请把插件固定在快捷工具栏方便使用。' },
'zh-CN': { title: 'QuickTranslate 安装完成', msg: 'QuickTranslate已安装!请点击插件图标开始使用。温馨提示:请把插件固定在快捷工具栏方便使用。' },
'zh-TW': { title: 'QuickTranslate 安裝完成', msg: 'QuickTranslate已安裝!請點擊插件圖標開始使用。溫馨提示:請把插件固定在快捷工具欄方便使用。' },
'zh-HK': { title: 'QuickTranslate 安裝完成', msg: 'QuickTranslate已安裝!請點擊插件圖標開始使用。溫馨提示:請把插件固定在快捷工具欄方便使用。' },
'ja': { title: 'QuickTranslate インストール完了', msg: 'QuickTranslateがインストールされました!アイコンをクリックして開始してください。ヒント:ツールバーに固定すると便利です。' },
'ko': { title: 'QuickTranslate 설치 완료', msg: 'QuickTranslate이 설치되었습니다! 아이콘을 클릭하여 시작하세요. 팁:도구 모음에 고정하면 편리합니다.' },
'en':
{ title: 'QuickTranslate Installed', msg: 'QuickTranslate installed! Click the icon to start. Tip: Pin to toolbar for easy access.' }
};
// 尝试精确匹配
if (langMap[lang]) return langMap[lang];
// 尝试语言前缀匹配
const prefix = lang.split('-')[0];
for (const key in langMap) {
if (key.startsWith(prefix)) return langMap[key];
}
// 默认英文
return langMap['en'];
}
// 检查是否是首次运行
checkFirstRun() {
chrome.storage.local.get(['hasRunBefore'], (result) => {
console.log('Storage check - hasRunBefore:', result.hasRunBefore);
if (!result.hasRunBefore) {
console.log('First run! Setting up...');
// 首次运行,设置标记
chrome.storage.local.set({
shouldShowWelcome: true,
hasRunBefore: true
}, () => {
console.log('Storage set, now showing notification...');
// 设置默认 UI 语言
this.setDefaultUILanguage();
// 获取对应语言的通知文本
const notifText = this.getNotificationText();
// 显示安装通知
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon16.png',
title: notifText.title,
message: notifText.msg,
requireInteraction: false,
silent: false
}, (notificationId) => {
console.log('Notification created, ID:', notificationId);
if (chrome.runtime.lastError) {
console.error('Notification error:', chrome.runtime.lastError);
}
});
// 5秒后关闭通知
setTimeout(() => {
chrome.notifications.getAll((notifications) => {
console.log('Current notifications:', notifications);
Object.keys(notifications).forEach(id => {
chrome.notifications.clear(id);
});
});
}, 5000);
});
} else {
console.log('Not first run, skipping notification');
}
});
}
setupInstallListener() {
chrome.runtime.onInstalled.addListener((details) => {
console.log('Extension installed or updated:', details);
if (details.reason === 'install') {
// 使用 storage 存储安装标记,popup 打开时会检查
chrome.storage.local.set({ shouldShowWelcome: true });
// 根据浏览器语言设置默认的 UI 语言
this.setDefaultUILanguage();
// 获取对应语言的通知文本
const notifText = this.getNotificationText();
// 安装完成后立即显示欢迎通知,持续5秒
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon16.png',
title: notifText.title,
message: notifText.msg,
requireInteraction: false,
silent: false
});
// 5秒后自动关闭通知
setTimeout(() => {
chrome.notifications.getAll((notifications) => {
Object.keys(notifications).forEach(id => {
chrome.notifications.clear(id);
});
});
}, 5000);
}
});
}
// 根据浏览器语言设置默认 UI 语言
async setDefaultUILanguage() {
// 支持的语言
const supportedLangs = ['zh-CN', 'zh-TW', 'en', 'ja', 'ko'];
const langMap = {
'zh': 'zh-CN',
'zh-CN': 'zh-CN',
'zh-TW': 'zh-TW',
'zh-HK': 'zh-TW',
'zh-SG': 'zh-CN',
'en': 'en',
'en-US': 'en',
'en-GB': 'en',
'en-AU': 'en',
'en-CA': 'en',
'ja': 'ja',
'ja-JP': 'ja',
'ko': 'ko',
'ko-KR': 'ko'
};
// 获取浏览器语言
const browserLang = chrome.runtime.getManifest().default_locale || 'en';
console.log('Background: Browser default locale:', browserLang);
// 尝试匹配
let uiLang = langMap[browserLang];
if (!uiLang) {
const langPrefix = browserLang.split('-')[0].toLowerCase();
uiLang = langMap[langPrefix];
}
// 如果不匹配支持的语言,默认英文
if (!uiLang || !supportedLangs.includes(uiLang)) {
uiLang = 'en';
}
console.log('Background: Setting default UI language to:', uiLang);
// 保存到 storage
await chrome.storage.local.set({ uiLanguage: uiLang });
}
// ==================== 历史记录和生词本 ====================
async getTranslationHistory(sendResponse) {
try {
const result = await chrome.storage.local.get(['translationHistory']);
const history = result.translationHistory || [];
sendResponse({ success: true, data: history });
} catch (error) {
console.error('Failed to get translation history:', error);
sendResponse({ success: false, error: error.message });
}
}
async addToHistory(item, sendResponse) {
try {
const result = await chrome.storage.local.get(['translationHistory']);
let history = result.translationHistory || [];
// 生成唯一ID
const newItem = {
id: Date.now(),
original: item.original,
translation: item.translation,
sourceLang: item.sourceLang || 'auto',
targetLang: item.targetLang || 'zh-CN',
timestamp: Date.now()
};
// 添加到开头
history.unshift(newItem);
// 限制条数
if (history.length > this.MAX_HISTORY) {
history = history.slice(0, this.MAX_HISTORY);
}
await chrome.storage.local.set({ translationHistory: history });
sendResponse({ success: true, data: newItem });
} catch (error) {
console.error('Failed to add to history:', error);
sendResponse({ success: false, error: error.message });
}
}
async clearHistory(sendResponse) {
try {
await chrome.storage.local.set({ translationHistory: [] });
sendResponse({ success: true });
} catch (error) {
console.error('Failed to clear history:', error);
sendResponse({ success: false, error: error.message });
}
}
async getSavedWords(sendResponse) {
try {
const result = await chrome.storage.local.get(['savedWords']);
const words = result.savedWords || [];
sendResponse({ success: true, data: words });
} catch (error) {
console.error('Failed to get saved words:', error);
sendResponse({ success: false, error: error.message });
}
}
async addToSavedWords(item, sendResponse) {
try {
const result = await chrome.storage.local.get(['savedWords']);
let words = result.savedWords || [];
// 检查是否已存在
const exists = words.some(w => w.original === item.original && w.translation === item.translation);
if (exists) {
sendResponse({ success: false, error: '已存在' });
return;
}
const newItem = {
id: Date.now(),
original: item.original,
translation: item.translation,
sourceLang: item.sourceLang || 'auto',
targetLang: item.targetLang || 'zh-CN',
timestamp: Date.now()
};
words.unshift(newItem);
if (words.length > this.MAX_HISTORY) {
words = words.slice(0, this.MAX_HISTORY);
}
await chrome.storage.local.set({ savedWords: words });
sendResponse({ success: true, data: newItem });
} catch (error) {
console.error('Failed to add to saved words:', error);
sendResponse({ success: false, error: error.message });
}
}
async removeFromSavedWords(id, sendResponse) {
try {
const result = await chrome.storage.local.get(['savedWords']);
let words = result.savedWords || [];
words = words.filter(w => w.id !== id);
await chrome.storage.local.set({ savedWords: words });
sendResponse({ success: true });
} catch (error) {
console.error('Failed to remove from saved words:', error);
sendResponse({ success: false, error: error.message });
}
}
async exportData(sendResponse) {
try {
const result = await chrome.storage.local.get(['translationHistory', 'savedWords']);
const data = {
translationHistory: result.translationHistory || [],
savedWords: result.savedWords || [],
exportTime: new Date().toISOString(),
version: '2.5.0'
};
sendResponse({ success: true, data: data });
} catch (error) {
console.error('Failed to export data:', error);
sendResponse({ success: false, error: error.message });
}
}
async importData(data, sendResponse) {
try {
if (!data || !data.version) {
sendResponse({ success: false, error: 'Invalid data format' });
return;
}
if (data.translationHistory) {
await chrome.storage.local.set({ translationHistory: data.translationHistory });
}
if (data.savedWords) {
await chrome.storage.local.set({ savedWords: data.savedWords });
}
sendResponse({ success: true });
} catch (error) {
console.error('Failed to import data:', error);
sendResponse({ success: false, error: error.message });
}
}
setupMessageListeners() {
console.log('Setting up message listeners...');
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('Message received:', request.action);
this.handleMessage(request, sender, sendResponse);
return true;
});
// 設置快捷鍵監聽
chrome.commands.onCommand.addListener((command) => {
console.log('Command received:', command);
if (command === 'smart-translate') {
this.handleSmartTranslate();
} else if (command === 'open-float-panel') {
this.handleOpenFloatPanel();
} else {
console.log('Unknown command:', command);
}
});
console.log('Message listeners and commands set up successfully');
}
async handleSmartTranslate() {
try {
console.log('Smart translate triggered');
// 获取当前活动标签
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tabs[0]) {
throw new Error('No active tab found');
}
const tab = tabs[0];
console.log('Active tab for smart translate:', tab.url);
// 检查是否是受限制的页面
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('edge://')) {
console.error('Cannot use shortcut on restricted pages');
// 显示通知提醒用户
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon16.png',
title: '截图翻译器',
message: '无法在此页面使用快捷键,请切换到普通网页'
});
return;
}
// 获取用户设置的目标语言
const userSettings = await this.getUserSettings();
console.log('Using user target language:', userSettings.targetLanguage);
// 注入 content script(如果尚未注入)
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
console.log('Content script injected via shortcut');
} catch (injectError) {
console.log('Content script may already be injected:', injectError.message);
}
// 发送智能翻译初始化消息
try {
const message = {
action: 'initCapture',
smartMode: true,
userSettings: userSettings
};
await chrome.tabs.sendMessage(tab.id, message);
console.log('Smart translate initiated successfully');
} catch (msgError) {
console.error('Failed to send smart translate message:', msgError);
// 如果失败,稍等片刻重试一次
setTimeout(async () => {
try {
const retryMessage = {
action: 'initCapture',
smartMode: true,
userSettings: userSettings
};
await chrome.tabs.sendMessage(tab.id, retryMessage);
console.log('Smart translate retry successful');
} catch (retryError) {
console.error('Smart translate retry failed:', retryError);
}
}, 200);
}
} catch (error) {
console.error('Smart translate failed:', error);
}
}
async handleOpenFloatPanel() {
try {
console.log('Opening float panel...');
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tabs[0]) {
console.error('No active tab found');
return;
}
const tab = tabs[0];
// 检查是否是受限页面
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('edge://')) {
console.error('Cannot use on restricted pages');
return;
}
// 发送消息给 content script,如果失败就忽略
try {
chrome.tabs.sendMessage(tab.id, { action: 'openFloatPanel' });
} catch (msgError) {
console.log('Content script not ready, will retry on next shortcut press');
}
} catch (error) {
console.error('Failed to open float panel:', error);
}
}
async getUserSettings() {
try {
const result = await chrome.storage.local.get([
'targetLanguage',
'ocrLanguage',
'apiProvider',
'autoCopy',
'apiKeys',
'llmConfig'
]);
return {
targetLanguage: result.targetLanguage || 'zh-TW',
ocrLanguage: result.ocrLanguage || 'auto',
apiProvider: result.apiProvider || 'google',
autoCopy: result.autoCopy || false,
apiKeys: result.apiKeys || {},
llmConfig: result.llmConfig || { baseUrl: '', model: '' }
};
} catch (error) {
console.error('Failed to get user settings:', error);
return {
targetLanguage: 'zh-TW',
ocrLanguage: 'auto',
apiProvider: 'google',
autoCopy: false,
apiKeys: {},
llmConfig: { baseUrl: '', model: '' }
};
}
}
async handleMessage(request, sender, sendResponse) {
console.log('Handling message:', request.action);
try {
switch (request.action) {
case 'ping':
console.log('Ping received');
sendResponse({ success: true, message: 'pong', timestamp: Date.now() });
break;
case 'startCapture':
console.log('Starting capture...');
this.startCapture(sendResponse);
break;
case 'captureVisibleTab':
console.log('Capturing visible tab...');
this.captureVisibleTab(request.rect, sendResponse);
break;
case 'getSettings':
console.log('Getting settings...');
this.getSettings(sendResponse);
break;
case 'saveSettings':
console.log('Saving settings...');
this.saveSettings(request.settings, sendResponse);
break;
case 'translateText':
console.log('Translating text...');
this.translateText(request.text, request.sourceLang, request.targetLang, sendResponse);
break;
case 'translate':
console.log('Quick panel translate request...');
this.handleQuickPanelTranslate(request, sendResponse);
break;
case 'translateMultiEngine':
console.log('Multi-engine translate request...');
this.translateMultiEngine(request.text, request.sourceLang, request.targetLang, request.includeLLM, sendResponse);
break;
case 'getModels':
console.log('Getting available models...');
this.getAvailableModels(request.apiKey, request.baseUrl, sendResponse);
break;
case 'getTranslationHistory':
this.getTranslationHistory(sendResponse);
break;
case 'addToHistory':
this.addToHistory(request.item, sendResponse);
break;
case 'clearHistory':
this.clearHistory(sendResponse);
break;
case 'getSavedWords':
this.getSavedWords(sendResponse);
break;
case 'addToSavedWords':
this.addToSavedWords(request.item, sendResponse);
break;
case 'removeFromSavedWords':
this.removeFromSavedWords(request.id, sendResponse);
break;
case 'exportData':
this.exportData(sendResponse);
break;
case 'importData':
this.importData(request.data, sendResponse);
break;
default:
console.warn('Unknown action:', request.action);
sendResponse({ error: 'Unknown action' });
}
} catch (error) {
console.error('Error handling message:', error);
sendResponse({ error: error.message });
}
}
async startCapture(sendResponse) {
try {
console.log('Starting capture process...');
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tabs[0]) {
throw new Error('No active tab found');
}
const tab = tabs[0];
console.log('Active tab:', tab.url);
// 檢查是否是受限制的頁面
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('edge://')) {
throw new Error('無法在此頁面使用截圖功能');
}
// 注入 content script(如果尚未注入)
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
console.log('Content script injected');
} catch (injectError) {
console.log('Content script may already be injected:', injectError.message);
}
// 等待一下再發送消息
setTimeout(async () => {
try {
await chrome.tabs.sendMessage(tab.id, { action: 'initCapture' });
console.log('Init capture message sent');
} catch (msgError) {
console.error('Failed to send init message:', msgError);
sendResponse({ error: '無法初始化截圖功能: ' + msgError.message });
}
}, 100);
sendResponse({ success: true });
} catch (error) {
console.error('Failed to start capture:', error);
sendResponse({ error: error.message });
}
}
async getSettings(sendResponse) {
try {
const result = await chrome.storage.local.get([
'targetLanguage',
'ocrLanguage',
'apiProvider',
'autoCopy',
'quickPanelEnabled',
'hoverTranslationEnabled',
'multiEngineEnabled',
'minSelectionLength',
'apiKeys',
'llmConfig',
'uiLanguage'
]);
const settings = {
targetLanguage: result.targetLanguage || 'zh-TW',
ocrLanguage: result.ocrLanguage || 'eng',
apiProvider: result.apiProvider || 'google',
autoCopy: result.autoCopy || false,
quickPanelEnabled: result.quickPanelEnabled !== false,
hoverTranslationEnabled: result.hoverTranslationEnabled || false,
multiEngineEnabled: result.multiEngineEnabled || false,
minSelectionLength: result.minSelectionLength || 2,
apiKeys: result.apiKeys || {},
llmConfig: result.llmConfig || { baseUrl: '', model: '' },
uiLanguage: result.uiLanguage || 'en'
};
sendResponse({ success: true, settings });
} catch (error) {
console.error('Failed to get settings:', error);
sendResponse({ error: error.message });
}
}
async saveSettings(settings, sendResponse) {
try {
await chrome.storage.local.set(settings);
sendResponse({ success: true });
} catch (error) {
console.error('Failed to save settings:', error);
sendResponse({ error: error.message });
}
}
async getAvailableModels(apiKey, baseUrl, sendResponse) {
try {
// 构建 API URL
let url = baseUrl.trim();
if (url.endsWith('/')) {
url = url.slice(0, -1);
}
// 尝试 OpenAI 兼容的 models 端点
const modelsUrl = `${url}/models`;
console.log('Background: Fetching models from:', modelsUrl);
const response = await fetch(modelsUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error('Background: Failed to fetch models:', errorText);
throw new Error(`Failed to fetch models: ${response.status}`);
}
const data = await response.json();
// 解析 OpenAI 格式的响应
let models = [];
if (data.data && Array.isArray(data.data)) {
models = data.data.map(model => model.id);
} else if (Array.isArray(data)) {
models = data.map(model => typeof model === 'string' ? model : model.id);
}
console.log('Background: Found models:', models);
sendResponse({ success: true, models: models });
} catch (error) {
console.error('Background: Error fetching models:', error);
sendResponse({ success: false, error: error.message });
}
}
async captureVisibleTab(rect, sendResponse) {
try {
console.log('Capturing visible tab with rect:', rect);
// 獲取當前活動標籤
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tabs[0]) {
throw new Error('No active tab found');
}
const tab = tabs[0];
// 檢查權限
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('edge://')) {
throw new Error('無法在此頁面進行截圖');
}
// 使用 Chrome 的截圖 API
const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
format: 'png',
quality: 100
});
console.log('Screenshot captured successfully');
sendResponse({
success: true,
dataUrl: dataUrl,
rect: rect
});
} catch (error) {
console.error('Failed to capture screenshot:', error);
sendResponse({
success: false,
error: error.message
});
}
}
async translateText(text, sourceLang, targetLang, sendResponse) {
try {
console.log(`Background: Translating "${text}" from ${sourceLang} to ${targetLang}`);
// 获取用户设置的 API Provider
const settings = await this.getUserSettings();
const apiProvider = settings.apiProvider || 'google';
console.log('Background: Using API provider:', apiProvider);
let result;
// 根据 API Provider 选择翻译方法
switch (apiProvider) {
case 'glm':
// 使用 GLM 大模型翻译
const glmApiKey = settings.apiKeys?.glm;
if (!glmApiKey) {
throw new Error('GLM API Key 未设置,请在设置中配置');
}
result = await this.callGLMTranslate(text, sourceLang, targetLang, glmApiKey);
break;
case 'microsoft':
// 使用 Microsoft Translator(免费)
result = await this.callMicrosoftTranslate(text, sourceLang, targetLang);
break;
case 'custom':
// 使用通用 LLM(OpenAI 兼容格式)
const customApiKey = settings.apiKeys?.custom;
const llmConfig = settings.llmConfig || {};
console.log('Background: Custom LLM config:', {
hasApiKey: !!customApiKey,
baseUrl: llmConfig.baseUrl || 'not set',
model: llmConfig.model || 'not set'
});
if (!customApiKey || !llmConfig.baseUrl || !llmConfig.model) {
throw new Error('LLM 自定义配置不完整,请检查 API Key、Base URL 和模型名称');
}
console.log('Background: Calling Custom LLM with model:', llmConfig.model);
result = await this.callCustomLLMTranslate(text, sourceLang, targetLang, customApiKey, llmConfig);
break;
case 'google':
default:
// 默认使用 Google 翻译(免费)
result = await this.callGoogleTranslate(text, sourceLang, targetLang);
break;
}
sendResponse({
success: true,
translatedText: result,
sourceLang: sourceLang,
targetLang: targetLang
});
} catch (error) {
console.error('Background: Translation error:', error);
// 尝试备用翻译服务
try {
console.log('Background: Trying backup translation service...');
const backupResult = await this.callBackupTranslateService(text, sourceLang, targetLang);
if (backupResult && backupResult.text && backupResult.text !== text) {
console.log('Background: Backup translation successful via', backupResult.service, ':', backupResult.text);
sendResponse({
success: true,
translatedText: backupResult.text,
sourceLang: sourceLang,
targetLang: targetLang,
isBackup: true,
backupService: backupResult.service
});
} else {
throw new Error('Backup translation also failed');
}
} catch (backupError) {
console.error('Background: Backup translation failed:', backupError);
sendResponse({
success: false,
error: `Translation failed: ${error.message}. Backup also failed: ${backupError.message}`
});
}
}
}
// 格式化中文翻译结果,在词之间添加空格
formatChineseResult(text, translatedText, sourceLang) {
// 检查是否应该添加词间空格
// 如果原文是英文单词列表(由多个空格分隔的短词组成)且翻译目标是中文
const isChineseTarget = translatedText.match(/[\u4e00-\u9fff]/) !== null;
const isEnglishSource = sourceLang === 'en';
const isWordList = text && text.split(/\s+/).length > 1 && text.split(/\s+/).every(word => word.length <= 15);
if (isChineseTarget && isEnglishSource && isWordList) {
// 在每个中文字符之间添加空格(保留标点符号)
return translatedText.replace(/([\u4e00-\u9fff])([\u4e00-\u9fff])/g, '$1 $2');
}
return translatedText;
}
// Google 翻译(免费)
async callGoogleTranslate(text, sourceLang, targetLang) {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&ie=UTF-8&oe=UTF-8&q=${encodeURIComponent(text)}`;
console.log('Background: Google Translate URL:', url);
const response = await fetch(url, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
});
console.log('Background: Google Translate response status:', response.status);
if (!response.ok) {
throw new Error(`Google Translate HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Background: Google Translate response data:', data);
// 解析Google翻譯的響應格式
if (data && data[0] && Array.isArray(data[0])) {
let translatedText = '';
for (const segment of data[0]) {
if (segment && segment[0]) {
translatedText += segment[0];
}
}
let result = translatedText.trim();
// 格式化中文结果,添加词间空格
result = this.formatChineseResult(text, result, sourceLang);
console.log('Background: Google Translate result:', result);
if (result && result !== text) {
console.log('Background: Google translation successful');
return result;
}
}
throw new Error('Google translation failed - invalid response format');
}
// Microsoft Translator(需要 API Key)
async callMicrosoftTranslate(text, sourceLang, targetLang, apiKey) {
try {
console.log(`Background: Calling Microsoft Translator - ${sourceLang} -> ${targetLang}`);
// Microsoft Translator API 端点
const endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0';
// 语言代码映射
const langMap = {
'zh': 'zh-Hans',
'zh-cn': 'zh-Hans',
'zh-CN': 'zh-Hans',
'zh-TW': 'zh-Hant',
'en': 'en',
'ja': 'ja',
'ko': 'ko',
'fr': 'fr',
'de': 'de',
'es': 'es'
};
const fromLang = langMap[sourceLang] || sourceLang;
const toLang = langMap[targetLang] || targetLang;
const url = `${endpoint}&from=${fromLang}&to=${toLang}`;
console.log('Background: Microsoft Translator URL:', url);
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': apiKey
},
body: JSON.stringify([{ text: text }])
});
console.log('Background: Microsoft Translator response status:', response.status);
if (!response.ok) {
const errorText = await response.text();
console.error('Background: Microsoft Translator error:', errorText);
throw new Error(`Microsoft Translator error: ${response.status}`);
}
const data = await response.json();
console.log('Background: Microsoft Translator response:', data);
if (data && data[0] && data[0].translations && data[0].translations[0]) {
let result = data[0].translations[0].text;
// 格式化中文结果,添加词间空格
result = this.formatChineseResult(text, result, sourceLang);
console.log('Background: Microsoft translation result:', result);
return result;
}
throw new Error('Microsoft translation failed - invalid response format');
} catch (error) {
console.error('Background: Microsoft translation error:', error);
throw error;
}
}
// GLM 大模型翻译
async callGLMTranslate(text, sourceLang, targetLang, apiKey) {
try {
console.log(`Background: Calling GLM API - ${sourceLang} -> ${targetLang}`);
// 语言代码映射到 GLM 友好的语言描述
const langMap = {
'zh': '中文',
'zh-cn': '简体中文',
'zh-TW': '繁体中文',
'en': '英文',
'ja': '日文',
'ko': '韩文',
'fr': '法文',
'de': '德文',
'es': '西班牙文',
'auto': '自动检测'
};
const sourceLangName = langMap[sourceLang] || '源语言';
const targetLangName = langMap[targetLang] || '目标语言';
const prompt = `你是一个专业的翻译引擎。请将以下${sourceLangName}文本翻译成${targetLangName},只返回翻译结果,不要添加任何解释、备注或格式:
${text}`;
// 设置 60 秒超时
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 60000);
const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'glm-4-flash',
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.1,
stream: false
}),
signal: controller.signal
});
clearTimeout(timeoutId);
console.log('Background: GLM API response status:', response.status);
if (!response.ok) {
const errorData = await response.text();
console.error('Background: GLM API error:', errorData);
// 尝试解析错误消息
let errorMessage = `GLM API 错误: ${response.status}`;
try {
const errorJson = JSON.parse(errorData);
if (errorJson.error) {
if (typeof errorJson.error === 'string') {
errorMessage = errorJson.error;