-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
1820 lines (1615 loc) · 63.2 KB
/
Copy pathbackground.js
File metadata and controls
1820 lines (1615 loc) · 63.2 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
// ===== 模塊系統核心 =====
self.addEventListener('unhandledrejection', (event) => {
console.warn('Background: Unhandled rejection:', event.reason?.message || event.reason)
event.preventDefault()
})
self.addEventListener('error', (event) => {
console.error('Background: Uncaught error:', event.message || event.error)
event.preventDefault()
})
importScripts(
'core/event-bus.js',
'core/module-loader.js',
'modules/translator-google.js',
'modules/translator-microsoft.js',
'modules/translator-glm.js',
'modules/translator-custom.js',
'modules/mode-quick-panel.js',
'modules/mode-float-panel.js',
'modules/service-history.js',
'modules/service-words.js',
'modules/processor-sanitizer.js',
'modules/processor-code-protector.js',
'modules/service-cache.js',
'modules/mode-inline-translate.js'
)
// ===== 模塊系統初始化 =====
const eventBus = new EventBus()
const moduleLoader = new ModuleLoader(eventBus, chrome.storage.local)
moduleLoader.register(GoogleTranslatorModule)
moduleLoader.register(MicrosoftTranslatorModule)
moduleLoader.register(GLMTranslatorModule)
moduleLoader.register(CustomLLMModule)
moduleLoader.register(QuickPanelMode)
moduleLoader.register(FloatPanelMode)
moduleLoader.register(HistoryService)
moduleLoader.register(WordsService)
moduleLoader.register(SanitizerProcessor)
moduleLoader.register(CodeProtectorProcessor)
moduleLoader.register(TranslationCacheService)
moduleLoader.register(InlineTranslateMode)
// 截圖翻譯器後台服務
console.log('Background script loading...');
// 立即启动服务(在 class 定义之后)
class ScreenshotTranslator {
constructor() {
console.log('ScreenshotTranslator constructor called');
this.isProcessing = false;
this.MAX_HISTORY = 500; // 历史记录和生词本最大条数
this.setupMessageListeners();
this.setupInstallListener();
this.setupContextMenuHandler();
// 检查是否是首次启动(开发者模式下 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);
// 建立右键菜单
this.createContextMenu()
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);
} else if (details.reason === 'update') {
// 更新时重建右键菜单
chrome.contextMenus.removeAll(() => this.createContextMenu())
}
});
}
// ===== 右键菜单 =====
createContextMenu() {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: 'qt-translate-selection',
title: 'QuickTranslate 翻譯「%s」',
contexts: ['selection']
})
chrome.contextMenus.create({
id: 'qt-translate-selection-multi',
title: 'QuickTranslate 多引擎翻譯「%s」',
contexts: ['selection']
})
console.log('Context menu created')
})
}
setupContextMenuHandler() {
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (!info.selectionText || !tab?.id) return
const text = info.selectionText.trim()
if (!text) return
if (info.menuItemId === 'qt-translate-selection') {
this._handleContextTranslate(text, tab.id, false)
} else if (info.menuItemId === 'qt-translate-selection-multi') {
this._handleContextTranslate(text, tab.id, true)
}
})
}
async _handleContextTranslate(text, tabId, multiEngine) {
try {
const settings = await this.getUserSettings()
const targetLang = settings.targetLanguage || 'zh-TW'
// 先发 loading 状态
chrome.tabs.sendMessage(tabId, {
action: 'showContextTranslation',
status: 'loading',
text
}).catch(() => {})
// 单引擎翻译
const result = await new Promise((resolve, reject) => {
this.translateText(text, 'auto', targetLang, (response) => {
if (response?.success) resolve(response.translatedText)
else reject(new Error(response?.error || '翻译失败'))
})
})
chrome.tabs.sendMessage(tabId, {
action: 'showContextTranslation',
status: 'done',
text,
result,
targetLang
}).catch(() => {})
} catch (error) {
console.error('Context menu translate error:', error)
chrome.tabs.sendMessage(tabId, {
action: 'showContextTranslation',
status: 'error',
text,
error: error.message
}).catch(() => {})
}
}
// 根据浏览器语言设置默认 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 });
}
// ==================== 历史记录和生词本 ====================
_routeViaEventBus(requestName, responseName, payload, sendResponse, timeout = 5000) {
const requestId = 'eb_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6)
const timer = setTimeout(() => {
if (typeof sendResponse === 'function') {
unsub()
sendResponse({ success: false, error: 'timeout' })
}
}, timeout)
const unsub = eventBus.on(responseName, (data) => {
if (data.requestId === requestId) {
clearTimeout(timer)
unsub()
if (typeof sendResponse === 'function') {
sendResponse({ success: true, ...data })
}
}
})
eventBus.emit(requestName, { ...payload, requestId })
}
async getTranslationHistory(sendResponse) { this._routeViaEventBus('history:get', 'history:data', {}, sendResponse) }
async addToHistory(item, sendResponse) { this._routeViaEventBus('history:add', 'history:added', { item }, sendResponse) }
async clearHistory(sendResponse) { this._routeViaEventBus('history:clear', 'history:cleared', {}, sendResponse) }
async getSavedWords(sendResponse) { this._routeViaEventBus('words:get', 'words:data', {}, sendResponse) }
async addToSavedWords(item, sendResponse) { this._routeViaEventBus('words:add', 'words:added', { item }, sendResponse) }
async removeFromSavedWords(id, sendResponse) { this._routeViaEventBus('words:remove', 'words:removed', { id }, sendResponse) }
async exportData(sendResponse) { this._routeViaEventBus('data:export', 'data:exported', {}, sendResponse) }
async importData(data, sendResponse) { this._routeViaEventBus('data:import', 'data:imported', { data }, sendResponse) }
async toggleModule(moduleId, enable, sendResponse) {
try {
const result = await moduleLoader.toggleModule(moduleId, enable)
sendResponse({ success: true, active: result.success })
} catch (error) {
sendResponse({ success: false, error: error.message })
}
}
async installModule(moduleId, code, manifest, sendResponse) {
try {
await moduleLoader.installModule(moduleId, code, manifest)
// 嘗試通過沙箱即時激活
const activationResult = await moduleLoader.activateFromStorage(moduleId)
sendResponse({ success: true, activated: activationResult.success })
} catch (error) {
sendResponse({ success: false, error: error.message })
}
}
async uninstallModule(moduleId, sendResponse) {
try {
await moduleLoader.uninstallModule(moduleId)
sendResponse({ success: true })
} catch (error) {
sendResponse({ success: false, error: error.message })
}
}
async getModulesList(sendResponse) {
try {
const modules = await moduleLoader.getCombinedModuleList()
const statsResult = await chrome.storage.local.get('moduleStats')
sendResponse({ success: true, modules, stats: statsResult.moduleStats || {} })
} catch (error) {
sendResponse({ success: false, error: error.message })
}
}
async getModuleStats(sendResponse) {
try {
const result = await chrome.storage.local.get('moduleStats')
sendResponse({ success: true, stats: result.moduleStats || {} })
} catch (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');
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon16.png',
title: 'QuickTranslate',
message: '无法在此页面使用快捷键,请切换到普通网页'
});
return;
}
// 先尝试注入 float-panel.js(如果尚未注入)
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['float-panel.js']
});
console.log('Float panel script injected');
} catch (injectError) {
console.log('Float panel script may already be injected:', injectError.message);
}
// 发送消息给 content script
try {
chrome.tabs.sendMessage(tab.id, { action: 'openFloatPanel' });
console.log('Float panel open message sent');
} catch (msgError) {
console.error('Failed to open float panel:', msgError);
// 稍等片刻再重试一次
setTimeout(async () => {
try {
chrome.tabs.sendMessage(tab.id, { action: 'openFloatPanel' });
console.log('Float panel retry successful');
} catch (retryError) {
console.error('Float panel retry failed:', retryError);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon16.png',
title: 'QuickTranslate',
message: '快捷面板打开失败,请刷新页面后重试'
});
}
}, 300);
}
} 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;
case 'toggleModule':
this.toggleModule(request.moduleId, request.enable, sendResponse);
break;
case 'installModule':
this.installModule(request.moduleId, request.code, request.manifest, sendResponse);
break;
case 'uninstallModule':
this.uninstallModule(request.moduleId, sendResponse);
break;
case 'evaluateModule':
// 此請求由 offscreen document 處理,這裡只做轉發
sendResponse({ success: false, error: 'not handled by background' });
break;
case 'hostReady':
console.log('Background: Module host ready:', request.hostId);
sendResponse({ success: true });
break;
case 'getModules':
this.getModulesList(sendResponse);
break;
case 'getModuleStats':
this.getModuleStats(sendResponse);
break;
case 'emitEvent':
eventBus.emit(request.event, request.data);
sendResponse({ success: true });
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',
'inlineTranslateEnabled',
'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,
inlineTranslateEnabled: result.inlineTranslateEnabled || 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
});
}
}
_providerToModuleId(provider) {
const map = { google: 'engine-google', microsoft: 'engine-microsoft', glm: 'engine-glm', custom: 'engine-custom' }
return map[provider] || null
}
_translateViaEventBus(text, from, to, moduleId) {
return new Promise((resolve, reject) => {
const requestId = 'req_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6)
const timeout = setTimeout(() => {
unsubResult()
unsubError()
reject(new Error('Translation timeout'))
}, 30000)
const unsubResult = eventBus.on('translate:result', (data) => {
if (data.id === requestId) {
clearTimeout(timeout)
unsubResult()
unsubError()
resolve(data.result)
}
})
const unsubError = eventBus.on('translate:error', (data) => {
if (data.id === requestId) {
clearTimeout(timeout)
unsubResult()
unsubError()
reject(new Error(data.error))
}
})
eventBus.emit('translate:text', { text, from, to, id: requestId, target: moduleId })
})
}
async _isModuleEnabled(moduleId) {
const data = await chrome.storage.local.get('moduleToggles')
const toggles = data.moduleToggles || {}
// 默認為啟用(如果沒有 toggle 記錄)
return toggles[moduleId] !== false
}
// ===== 文本預處理管道(淨化 → 代碼保護) =====
async _preprocessText(text) {
let current = text
// 1. 淨化
try {
const result = await this._emitAndWait('preprocess:sanitize', 'preprocess:sanitized', { text: current })
if (result && result.text) current = result.text
} catch { /* 如果模塊未激活或出錯,跳過 */ }
// 2. 代碼保護
try {
const result = await this._emitAndWait('preprocess:protect', 'preprocess:protected', { text: current })
if (result && result.text) {
current = result.text
this._codePlaceholders = result.placeholders || {}
}
} catch { /* 沒有代碼保護模塊,跳過 */ }
return current
}
// ===== 文本後處理管道(恢復代碼) =====
async _postprocessText(text) {
if (!this._codePlaceholders || Object.keys(this._codePlaceholders).length === 0) {
return text
}
try {
const result = await this._emitAndWait('postprocess:restore', 'postprocess:restored', {
text,
placeholders: this._codePlaceholders
})
if (result && result.text) {
this._codePlaceholders = null
return result.text
}
} catch { /* 跳過 */ }
this._codePlaceholders = null
return text
}
// ===== 緩存查詢 =====
async _checkCache(text, from, to, engine) {
try {
const result = await this._emitAndWait('cache:get', 'cache:got', { text, from, to, engine })
if (result && result.hit) return result.result
} catch { /* 跳過 */ }
return null
}
// ===== 緩存寫入 =====
async _setCache(text, from, to, result, engine) {
try {
await this._emitAndWait('cache:set', 'cache:setted', { text, from, to, result, engine })
} catch { /* 跳過 */ }
}
// ===== EventBus 請求/響應輔助 =====
async _emitAndWait(requestEvent, responseEvent, payload, timeout = 5000) {
return new Promise((resolve, reject) => {
const requestId = 'pp_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6)
const timer = setTimeout(() => {
unsub()
reject(new Error('timeout'))
}, timeout)
const unsub = eventBus.on(responseEvent, (data) => {
if (data.requestId === requestId) {
clearTimeout(timer)
unsub()
resolve(data)
}
})
eventBus.emit(requestEvent, { ...payload, requestId })
})
}
async translateText(text, sourceLang, targetLang, sendResponse) {
let processedText = text
try {
console.log(`Background: Translating "${text}" from ${sourceLang} to ${targetLang}`);
// ===== Step 1: 預處理文本(淨化 + 代碼保護) =====
processedText = await this._preprocessText(text)
// 获取用户设置的 API Provider(需在緩存檢查之前)
const settings = await this.getUserSettings();
let apiProvider = settings.apiProvider || 'google';
// ===== Step 2: 檢查緩存 =====
const cached = await this._checkCache(processedText, sourceLang, targetLang, apiProvider)
if (cached !== null) {
console.log('Background: Cache hit, returning cached result')
sendResponse({
success: true,
translatedText: cached,
sourceLang,
targetLang,
fromCache: true
})
return
}
console.log('Background: Using API provider:', apiProvider);
// 檢查翻譯引擎狀態
const allToggles = await chrome.storage.local.get('moduleToggles')
const toggles = allToggles.moduleToggles || {}
// 如果選中的引擎已關閉,自動切換到第一個可用的
const modId = this._providerToModuleId(apiProvider)
if (modId && !(await this._isModuleEnabled(modId))) {
const fallbackOrder = ['google', 'microsoft', 'glm', 'custom']
let switched = false
for (const fb of fallbackOrder) {
if (toggles['engine-' + fb] !== false) {
apiProvider = fb
await chrome.storage.local.set({ apiProvider: fb })
console.log('Background: Auto-switched to available engine:', apiProvider)
switched = true