-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcontentScript.js
More file actions
1365 lines (1178 loc) · 47 KB
/
contentScript.js
File metadata and controls
1365 lines (1178 loc) · 47 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
// contentScript.js - Translate page text in-place using Chrome Translator API, preserving layout
(() => {
// Check if this script has already been loaded to prevent multiple instances
if (window.translatorContentScriptLoaded) {
console.log('Translator content script already loaded, skipping...');
return;
}
window.translatorContentScriptLoaded = true;
// State for page translation
let enabled = false;
let translator = null;
let currentTargetLang = 'zh-Hans';
const originalText = new Map(); // Text node -> original string (Map so we can iterate/restore)
let observer = null;
// State for selection translation
let selectionTranslator = null;
let selectionSourceLang = null;
let selectionTargetLang = 'zh-Hans';
let translationTooltip = null;
let selectionTimeout = null;
let isTranslatingSelection = false;
let lastTranslatedText = null; // Track last translated text to avoid duplicates
let isInitialized = false; // Prevent multiple initializations
let selectionTranslateEnabled = false; // Control whether selection translation is enabled
// State for floating button
let floatingButton = null;
let floatingButtonEnabled = false;
let isDragging = false;
let dragOffset = { x: 0, y: 0 };
// Simple inline overlay for status/progress
let overlayEl = null;
function showOverlay(msg) {
if (!overlayEl) {
overlayEl = document.createElement('div');
overlayEl.style.cssText = [
'position:fixed',
'right:12px',
'bottom:12px',
'max-width:40vw',
'z-index:2147483647',
'background:#111827',
'color:#fff',
'padding:8px 10px',
'border-radius:8px',
'font:12px/1.4 -apple-system,system-ui,Segoe UI,Roboto,sans-serif',
'box-shadow:0 6px 20px rgba(0,0,0,.25)',
'opacity:.95',
'pointer-events:none',
].join(';');
document.documentElement.appendChild(overlayEl);
}
overlayEl.textContent = String(msg || '');
}
function hideOverlay() {
if (overlayEl) overlayEl.remove();
overlayEl = null;
}
// Translation tooltip for selected text
function createTranslationTooltip() {
const tooltip = document.createElement('div');
tooltip.style.cssText = [
'position:absolute',
'z-index:2147483647',
'background:#1f2937',
'color:#fff',
'padding:8px 12px',
'border-radius:8px',
'font:13px/1.4 -apple-system,system-ui,Segoe UI,Roboto,sans-serif',
'box-shadow:0 4px 12px rgba(0,0,0,0.3)',
'max-width:300px',
'word-wrap:break-word',
'opacity:0',
'transform:translateY(4px)',
'transition:opacity 0.2s ease, transform 0.2s ease',
'pointer-events:auto',
'border:1px solid rgba(255,255,255,0.1)',
'display:flex',
'flex-direction:column',
'gap:6px'
].join(';');
// Translation text container
const textContainer = document.createElement('div');
textContainer.style.cssText = [
'flex:1',
'word-wrap:break-word'
].join(';');
// Copy button
const copyButton = document.createElement('button');
copyButton.textContent = '复制';
copyButton.style.cssText = [
'background:#374151',
'color:#fff',
'border:1px solid rgba(255,255,255,0.2)',
'border-radius:4px',
'padding:4px 8px',
'font-size:11px',
'cursor:pointer',
'transition:background 0.2s ease',
'align-self:flex-end'
].join(';');
// Copy button hover effect
copyButton.addEventListener('mouseenter', () => {
copyButton.style.background = '#4b5563';
});
copyButton.addEventListener('mouseleave', () => {
copyButton.style.background = '#374151';
});
// Copy functionality
copyButton.addEventListener('click', async (e) => {
e.stopPropagation();
const textToCopy = textContainer.textContent;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(textToCopy);
} else {
// Fallback for older browsers
const textArea = document.createElement('textarea');
textArea.value = textToCopy;
textArea.style.position = 'fixed';
textArea.style.opacity = '0';
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
// Visual feedback
const originalText = copyButton.textContent;
copyButton.textContent = '已复制';
copyButton.style.background = '#10b981';
setTimeout(() => {
copyButton.textContent = originalText;
copyButton.style.background = '#374151';
}, 1000);
} catch (err) {
console.warn('复制失败:', err);
copyButton.textContent = '复制失败';
copyButton.style.background = '#ef4444';
setTimeout(() => {
copyButton.textContent = '复制';
copyButton.style.background = '#374151';
}, 1000);
}
});
tooltip.appendChild(textContainer);
tooltip.appendChild(copyButton);
// Add arrow pointing down
const arrow = document.createElement('div');
arrow.style.cssText = [
'position:absolute',
'bottom:-6px',
'left:50%',
'transform:translateX(-50%)',
'width:0',
'height:0',
'border-left:6px solid transparent',
'border-right:6px solid transparent',
'border-top:6px solid #1f2937'
].join(';');
tooltip.appendChild(arrow);
// Store references for easy access
tooltip._textContainer = textContainer;
tooltip._copyButton = copyButton;
return tooltip;
}
function showTranslationTooltip(text, x, y) {
hideTranslationTooltip();
const tooltip = createTranslationTooltip();
tooltip._textContainer.textContent = text;
document.body.appendChild(tooltip);
// Position tooltip above the selection
const rect = tooltip.getBoundingClientRect();
const finalX = Math.max(10, Math.min(x - rect.width / 2, window.innerWidth - rect.width - 10));
const finalY = Math.max(10, y - rect.height - 10);
tooltip.style.left = finalX + 'px';
tooltip.style.top = finalY + 'px';
// Set global reference after positioning
translationTooltip = tooltip;
// Animate in
requestAnimationFrame(() => {
if (tooltip && tooltip.parentNode) {
tooltip.style.opacity = '1';
tooltip.style.transform = 'translateY(0)';
}
});
}
function showLoadingTooltip(x, y) {
hideTranslationTooltip();
const tooltip = createTranslationTooltip();
tooltip._textContainer.textContent = '翻译中...';
tooltip.style.background = '#374151';
tooltip._copyButton.style.display = 'none'; // Hide copy button during loading
document.body.appendChild(tooltip);
// Position tooltip
const rect = tooltip.getBoundingClientRect();
const finalX = Math.max(10, Math.min(x - rect.width / 2, window.innerWidth - rect.width - 10));
const finalY = Math.max(10, y - rect.height - 10);
tooltip.style.left = finalX + 'px';
tooltip.style.top = finalY + 'px';
// Set global reference after positioning
translationTooltip = tooltip;
// Animate in
requestAnimationFrame(() => {
if (tooltip && tooltip.parentNode) {
tooltip.style.opacity = '1';
tooltip.style.transform = 'translateY(0)';
}
});
}
function showErrorTooltip(message, x, y) {
hideTranslationTooltip();
const tooltip = createTranslationTooltip();
tooltip._textContainer.textContent = message;
tooltip.style.background = '#dc2626'; // Red background for errors
tooltip._copyButton.style.display = 'none'; // Hide copy button for errors
document.body.appendChild(tooltip);
// Position tooltip
const rect = tooltip.getBoundingClientRect();
const finalX = Math.max(10, Math.min(x - rect.width / 2, window.innerWidth - rect.width - 10));
const finalY = Math.max(10, y - rect.height - 10);
tooltip.style.left = finalX + 'px';
tooltip.style.top = finalY + 'px';
// Set global reference after positioning
translationTooltip = tooltip;
// Animate in
requestAnimationFrame(() => {
if (tooltip && tooltip.parentNode) {
tooltip.style.opacity = '1';
tooltip.style.transform = 'translateY(0)';
}
});
}
function hideTranslationTooltip() {
if (translationTooltip) {
try {
if (translationTooltip.parentNode) {
translationTooltip.remove();
}
} catch (e) {
console.warn('Error removing translation tooltip:', e);
}
translationTooltip = null;
}
}
const EXCLUDED = new Set(['SCRIPT','STYLE','NOSCRIPT','IFRAME','CANVAS','SVG','CODE','PRE','TEXTAREA','INPUT','BUTTON','SELECT']);
function* walkTextNodes(root) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
if (!node) return NodeFilter.FILTER_REJECT;
if (!node.parentElement) return NodeFilter.FILTER_REJECT;
const pe = node.parentElement;
// 排除基本标签
if (EXCLUDED.has(pe.tagName)) return NodeFilter.FILTER_REJECT;
// 排除漂浮翻译按钮及其子元素
let element = pe;
while (element) {
if (element.id === 'translator-floating-button') {
return NodeFilter.FILTER_REJECT;
}
element = element.parentElement;
}
// 排除翻译提示框和可能的其他翻译工具元素
element = pe;
while (element) {
if (element.id && (
element.id.includes('translator') ||
element.id.includes('translation') ||
element.classList?.contains('translator-overlay') ||
element.classList?.contains('translation-tooltip')
)) {
return NodeFilter.FILTER_REJECT;
}
element = element.parentElement;
}
const txt = node.nodeValue || '';
if (!txt.trim()) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
}
});
let cur;
while ((cur = walker.nextNode())) {
yield cur;
}
}
function samplePageText(maxLen = 2000) {
let acc = '';
for (const tn of walkTextNodes(document.body || document.documentElement)) {
const t = (tn.nodeValue || '').trim();
if (!t) continue;
if (acc.length + t.length + 1 > maxLen) break;
acc += (acc ? '\n' : '') + t;
if (acc.length >= maxLen) break;
}
return acc;
}
function normalizeLang(code) {
if (!code) return code;
if (code === 'zh') return 'zh-Hans';
return code;
}
// Get next target language when source and target are the same
function getNextTargetLanguage(currentLang) {
const languages = ['zh-Hans', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru', 'it', 'pt', 'zh-Hant'];
const currentIndex = languages.indexOf(currentLang);
if (currentIndex === -1) {
return 'zh-Hans'; // Default fallback
}
// Return next language in the list, wrap around to beginning if at end
return languages[(currentIndex + 1) % languages.length];
}
async function detectSourceLanguage() {
try {
if (typeof window.LanguageDetector === 'undefined') return null;
const text = samplePageText();
if (!text) return null;
const detector = await window.LanguageDetector.create({ expectedInputLanguages: ['en','zh-Hans','zh-Hant','ja','ko','fr','de','es','ru','it','pt'] });
const results = await detector.detect(text);
detector.destroy?.();
if (Array.isArray(results) && results.length > 0) {
return results[0].detectedLanguage || null;
}
} catch (e) {
// ignore
}
return null;
}
// Detect language for selected text
async function detectTextLanguage(text) {
try {
if (!isTranslatorAPIAvailable()) return null;
if (!text || text.trim().length < 2) return null;
const detector = await window.LanguageDetector.create({
expectedInputLanguages: ['en','zh-Hans','zh-Hant','ja','ko','fr','de','es','ru','it','pt']
});
const results = await detector.detect(text);
detector.destroy?.();
if (Array.isArray(results) && results.length > 0) {
return results[0].detectedLanguage || null;
}
} catch (e) {
console.warn('Language detection failed:', e);
}
return null;
}
async function ensureTranslator(sourceLang, targetLang) {
if (translator && currentTargetLang === targetLang) return translator;
if (typeof window.Translator === 'undefined') {
throw new Error('此页面上下文不支持 Translator API(需要 Chrome 138+ 且安全上下文)。');
}
const src = normalizeLang(sourceLang || 'en');
const tgt = normalizeLang(targetLang || 'zh-Hans');
if (translator) {
try { translator.destroy?.(); } catch {}
}
translator = await window.Translator.create({ sourceLanguage: src, targetLanguage: tgt });
currentTargetLang = tgt;
return translator;
}
// Check if Translator API is available
function isTranslatorAPIAvailable() {
return typeof window.Translator !== 'undefined' &&
typeof window.LanguageDetector !== 'undefined' &&
window.isSecureContext;
}
// Ensure translator for selection translation
async function ensureSelectionTranslator(sourceLang, targetLang) {
const src = normalizeLang(sourceLang || 'en');
const tgt = normalizeLang(targetLang || 'en');
// Check if we can reuse the existing translator
if (selectionTranslator && selectionSourceLang === src && selectionTargetLang === tgt) {
return selectionTranslator;
}
if (!isTranslatorAPIAvailable()) {
throw new Error('TRANSLATOR_API_NOT_AVAILABLE');
}
// Destroy existing translator if any
if (selectionTranslator) {
try { selectionTranslator.destroy?.(); } catch {}
}
console.log(`Creating new translator: ${src} -> ${tgt}`);
selectionTranslator = await window.Translator.create({ sourceLanguage: src, targetLanguage: tgt });
selectionSourceLang = src;
selectionTargetLang = tgt;
return selectionTranslator;
}
// Translate selected text with automatic fallback for unsupported language pairs
async function translateSelectedText(text, sourceLang, targetLang, maxRetries = 3) {
let currentTargetLang = targetLang;
let retryCount = 0;
while (retryCount < maxRetries) {
try {
// Skip if source and target are the same
if (sourceLang === currentTargetLang) {
currentTargetLang = getNextTargetLanguage(currentTargetLang);
console.log(`Source equals target (${sourceLang}), switching to ${currentTargetLang}`);
continue;
}
const translator = await ensureSelectionTranslator(sourceLang, currentTargetLang);
const translation = await translator.translate(text);
// If we had to switch languages, log it
if (currentTargetLang !== targetLang) {
console.log(`Successfully translated using fallback language: ${sourceLang} -> ${currentTargetLang}`);
}
return translation;
} catch (e) {
console.warn(`Translation failed (${sourceLang} -> ${currentTargetLang}):`, e);
// Handle specific error types
if (e.message === 'TRANSLATOR_API_NOT_AVAILABLE') {
throw new Error('API_NOT_AVAILABLE');
}
// Check if it's an unsupported language pair error
const isUnsupportedPair = e.message?.includes('language pair is unsupported') ||
e.message?.includes('Unable to create translator') ||
e.name === 'NotSupportedError';
if (isUnsupportedPair && retryCount < maxRetries - 1) {
// Try next target language
const nextLang = getNextTargetLanguage(currentTargetLang);
console.log(`Language pair ${sourceLang}->${currentTargetLang} unsupported, trying ${sourceLang}->${nextLang}`);
currentTargetLang = nextLang;
retryCount++;
// Clear the failed translator
if (selectionTranslator) {
try { selectionTranslator.destroy?.(); } catch {}
selectionTranslator = null;
selectionSourceLang = null;
selectionTargetLang = null;
}
continue;
}
// Handle other DOMException and API errors
if (e instanceof DOMException || e.name === 'DOMException') {
throw new Error('API_ERROR');
}
// If we've exhausted retries or it's not a language pair issue, throw the error
throw e;
}
}
// If we get here, all retries failed
throw new Error(`Failed to translate after ${maxRetries} attempts with different target languages`);
}
async function translateTextNodes(targetLang) {
enabled = true;
showOverlay('正在准备页面翻译...');
let sourceLang = await detectSourceLanguage();
if (!sourceLang) sourceLang = 'en';
await ensureTranslator(sourceLang, targetLang);
const nodes = Array.from(walkTextNodes(document.body || document.documentElement));
const total = nodes.length;
let done = 0;
showOverlay(`正在翻译页面 (${done}/${total})...`);
for (const tn of nodes) {
if (!enabled) break; // interrupted
const orig = tn.nodeValue || '';
if (!orig.trim()) { done++; continue; }
if (!originalText.has(tn)) originalText.set(tn, orig);
try {
const translated = await translator.translate(orig);
// only replace if unchanged to reduce race effects
if (enabled && (tn.nodeValue === orig || !tn.nodeValue)) {
tn.nodeValue = translated;
}
} catch (e) {
// Skip on error
} finally {
done++;
if (done % 20 === 0 || done === total) {
showOverlay(`正在翻译页面 (${done}/${total})...`);
}
}
}
showOverlay('页面翻译完成');
setTimeout(hideOverlay, 1200);
// 更新漂浮按钮状态
console.log('translateTextNodes: Updating floating button state, enabled now:', enabled);
if (floatingButton && floatingButtonEnabled) {
console.log('translateTextNodes: Setting button text to "恢复"');
floatingButton.innerHTML = '恢复';
floatingButton.title = '点击恢复原始网页';
} else {
console.log('translateTextNodes: Button not updated - floatingButton:', !!floatingButton, 'floatingButtonEnabled:', floatingButtonEnabled);
}
// Observe dynamic changes
setupObserver();
}
function setupObserver() {
cleanupObserver();
observer = new MutationObserver(async (mutations) => {
if (!enabled || !translator) return;
const newTextNodes = [];
for (const m of mutations) {
for (const node of m.addedNodes || []) {
if (node.nodeType === Node.TEXT_NODE) {
newTextNodes.push(node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
for (const tn of walkTextNodes(node)) newTextNodes.push(tn);
}
}
}
if (newTextNodes.length === 0) return;
for (const tn of newTextNodes) {
const orig = tn.nodeValue || '';
if (!orig.trim()) continue;
if (!originalText.has(tn)) originalText.set(tn, orig);
try {
const translated = await translator.translate(orig);
if (enabled && (tn.nodeValue === orig || !tn.nodeValue)) tn.nodeValue = translated;
} catch {}
}
});
observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
}
function cleanupObserver() {
observer?.disconnect();
observer = null;
}
function restorePage() {
console.log('restorePage: Starting page restoration, current enabled:', enabled);
enabled = false;
cleanupObserver();
hideOverlay();
for (const [tn, orig] of originalText.entries()) {
try {
if (tn && tn.nodeType === Node.TEXT_NODE) tn.nodeValue = orig;
} catch {}
}
originalText.clear();
try { translator?.destroy?.(); } catch {}
translator = null;
// 更新漂浮按钮状态
console.log('restorePage: Updating floating button state, enabled now:', enabled);
if (floatingButton && floatingButtonEnabled) {
console.log('restorePage: Setting button text to "翻译"');
floatingButton.innerHTML = '翻译';
floatingButton.title = '点击翻译当前网页';
} else {
console.log('restorePage: Button not updated - floatingButton:', !!floatingButton, 'floatingButtonEnabled:', floatingButtonEnabled);
}
console.log('restorePage: Page restoration completed');
}
// Handle text selection for translation
async function handleTextSelection() {
const timestamp = Date.now();
// Check if selection translation is enabled
if (!selectionTranslateEnabled) {
hideTranslationTooltip();
return;
}
if (isTranslatingSelection) {
console.log(`[${timestamp}] Translation already in progress, skipping...`);
return;
}
// Check if API is available first
if (!isTranslatorAPIAvailable()) {
return; // Silently skip if API is not available
}
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
hideTranslationTooltip();
lastTranslatedText = null;
return;
}
const selectedText = selection.toString().trim();
if (!selectedText || selectedText.length < 2) {
hideTranslationTooltip();
lastTranslatedText = null;
return;
}
// Skip if this is the same text we just translated
if (selectedText === lastTranslatedText) {
console.log(`[${timestamp}] Same text as last translation, skipping...`);
return;
}
// Skip if text is too long (avoid translating entire paragraphs accidentally)
if (selectedText.length > 500) {
hideTranslationTooltip();
return;
}
// Skip if text contains mostly numbers or special characters
if (!/[a-zA-Z\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/.test(selectedText)) {
hideTranslationTooltip();
return;
}
// Global lock to prevent multiple instances from translating simultaneously
if (window.translatorGlobalLock) {
console.log(`[${timestamp}] Global translation lock active, skipping...`);
return;
}
window.translatorGlobalLock = true;
// Get selection position for tooltip placement
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const topY = rect.top + window.scrollY; // Add scroll offset for correct positioning
isTranslatingSelection = true;
try {
// Show loading indicator
showLoadingTooltip(centerX, topY);
// Get target language from storage or use default
let targetLang = 'en'; // Default to English instead of Chinese
try {
const result = await chrome.storage.sync.get(['autoTranslateTargetLang']);
if (result.autoTranslateTargetLang) {
targetLang = result.autoTranslateTargetLang;
}
} catch (e) {
// Use default if storage access fails
console.warn('Failed to get target language from storage, using default:', e);
}
// Detect source language
const detectedLang = await detectTextLanguage(selectedText);
const sourceLang = detectedLang || 'en';
console.log(`[${timestamp}] Translating: "${selectedText}" (${sourceLang} -> ${targetLang})`);
// Translate the text (with automatic fallback for unsupported language pairs)
const translation = await translateSelectedText(selectedText, sourceLang, targetLang);
if (translation && translation !== selectedText) {
// Store the translated text to avoid duplicates
lastTranslatedText = selectedText;
// Show translation tooltip
showTranslationTooltip(translation, centerX, topY);
// Make sure copy button is visible
if (translationTooltip && translationTooltip._copyButton) {
translationTooltip._copyButton.style.display = 'block';
translationTooltip.style.background = '#1f2937'; // Reset background color
}
console.log(`[${timestamp}] Translation completed: "${selectedText}" -> "${translation}"`);
} else {
hideTranslationTooltip();
lastTranslatedText = null;
}
} catch (e) {
console.warn(`[${timestamp}] Selection translation failed:`, e);
// Show user-friendly error message for unsupported language pairs
if (e.message?.includes('Failed to translate after') ||
e.message?.includes('language pair is unsupported')) {
showErrorTooltip('该语言对不支持翻译', centerX, topY);
setTimeout(hideTranslationTooltip, 3000); // Auto-hide after 3 seconds
} else {
hideTranslationTooltip();
}
lastTranslatedText = null;
} finally {
isTranslatingSelection = false;
window.translatorGlobalLock = false; // Release global lock
}
}
// Debounced selection handler
function onSelectionChange() {
if (selectionTimeout) {
clearTimeout(selectionTimeout);
}
selectionTimeout = setTimeout(() => {
handleTextSelection();
}, 500); // Increased debounce to 500ms to reduce duplicate triggers
}
// Initialize selection translation
async function initSelectionTranslation() {
// Prevent multiple initializations
if (isInitialized) {
console.log('Selection translation already initialized, skipping...');
return;
}
// Check if we should enable selection translation
if (!isTranslatorAPIAvailable()) {
console.info('Translator API not available on this page. Selection translation disabled.');
return;
}
// Load selection translation setting from storage
try {
const result = await chrome.storage.sync.get(['selectionTranslateEnabled']);
selectionTranslateEnabled = !!result.selectionTranslateEnabled;
console.info(`Selection translation ${selectionTranslateEnabled ? 'enabled' : 'disabled'} from storage.`);
} catch (e) {
console.warn('Failed to load selection translation setting, using defaults:', e);
selectionTranslateEnabled = false;
}
console.info('Translator API available. Selection translation initialized.');
// Listen for selection changes
document.addEventListener('selectionchange', onSelectionChange);
// Hide tooltip when clicking elsewhere
document.addEventListener('click', () => {
// Small delay to allow new selection to be processed
setTimeout(() => {
const selection = window.getSelection();
if (!selection || !selection.toString().trim()) {
hideTranslationTooltip();
lastTranslatedText = null; // Reset when clearing selection
}
}, 100);
});
// Hide tooltip on scroll
document.addEventListener('scroll', () => {
hideTranslationTooltip();
lastTranslatedText = null; // Reset when scrolling
}, { passive: true });
// Hide tooltip on window resize
window.addEventListener('resize', () => {
hideTranslationTooltip();
lastTranslatedText = null; // Reset when resizing
});
isInitialized = true;
console.log('Selection translation initialized successfully');
}
// Initialize floating button (independent of API availability)
async function initFloatingButton() {
console.log('initFloatingButton: Starting initialization...');
// Check if document.body is available
if (!document.body) {
console.warn('initFloatingButton: document.body not available, will retry after DOM load');
// Wait for body to be available
const observer = new MutationObserver(() => {
if (document.body) {
observer.disconnect();
console.log('initFloatingButton: document.body now available, retrying...');
initFloatingButton();
}
});
observer.observe(document.documentElement, { childList: true, subtree: true });
return;
}
try {
console.log('initFloatingButton: Loading settings from storage...');
const result = await chrome.storage.sync.get(['floatingButtonEnabled']);
floatingButtonEnabled = !!result.floatingButtonEnabled;
console.info(`Floating button ${floatingButtonEnabled ? 'enabled' : 'disabled'} from storage.`);
// Show floating button if enabled
if (floatingButtonEnabled) {
console.log('initFloatingButton: Showing floating button...');
showFloatingButton();
} else {
console.log('initFloatingButton: Floating button disabled, not showing');
}
} catch (e) {
console.warn('Failed to load floating button setting, using defaults:', e);
floatingButtonEnabled = false;
}
console.log('initFloatingButton: Initialization completed');
}
// Cleanup selection translation
function cleanupSelectionTranslation() {
document.removeEventListener('selectionchange', onSelectionChange);
hideTranslationTooltip();
if (selectionTimeout) {
clearTimeout(selectionTimeout);
selectionTimeout = null;
}
try { selectionTranslator?.destroy?.(); } catch {}
selectionTranslator = null;
selectionSourceLang = null;
selectionTargetLang = null;
lastTranslatedText = null;
isInitialized = false;
window.translatorGlobalLock = false; // Release global lock
console.log('Selection translation cleaned up');
}
// Floating button functions
function createFloatingButton() {
console.log('createFloatingButton: Called, existing button:', !!floatingButton);
if (floatingButton) {
console.log('createFloatingButton: Returning existing button');
return floatingButton;
}
console.log('createFloatingButton: Creating new button...');
const button = document.createElement('div');
button.id = 'translator-floating-button';
button.innerHTML = '翻译'; // 显示"翻译"文字
button.title = '点击翻译当前网页';
console.log('createFloatingButton: Applying styles...');
// Apply styles - 长方形按钮样式
button.style.cssText = [
'position: fixed',
'top: 50%', // 垂直居中
'right: 20px', // 右侧位置
'transform: translateY(-50%)', // 精确垂直居中
'width: 60px', // 长方形宽度
'height: 32px', // 长方形高度
'background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%)',
'color: white',
'border: none',
'border-radius: 16px', // 圆角长方形
'font-size: 14px',
'font-weight: 500',
'text-align: center',
'line-height: 32px',
'cursor: move',
'z-index: 2147483647',
'box-shadow: 0 4px 16px rgba(74, 144, 226, 0.4), 0 2px 8px rgba(0,0,0,0.2)',
'user-select: none',
'backdrop-filter: blur(10px)',
'border: 2px solid rgba(255,255,255,0.2)',
'display: flex',
'align-items: center',
'justify-content: center',
'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
].join(';');
console.log('createFloatingButton: Adding event listeners...');
// Helper function to get current base transform (position-related)
function getBaseTransform() {
const currentTransform = button.style.transform;
if (currentTransform.includes('translateY(-50%)')) {
return 'translateY(-50%)';
} else {
return 'none';
}
}
// Hover effects - 适配长方形按钮
button.addEventListener('mouseenter', () => {
if (!isDragging) {
button.style.transition = 'all 0.2s ease'; // 为悬停效果添加过渡
const baseTransform = getBaseTransform();
if (baseTransform === 'translateY(-50%)') {
button.style.transform = 'translateY(-50%) scale(1.05)';
} else {
button.style.transform = 'scale(1.05)';
}
button.style.background = 'linear-gradient(135deg, #5aa6ff 0%, #4a90e2 100%)';
button.style.boxShadow = '0 6px 24px rgba(74, 144, 226, 0.6), 0 4px 12px rgba(0,0,0,0.3)';
}
});
button.addEventListener('mouseleave', () => {
if (!isDragging) {
button.style.transition = 'all 0.2s ease'; // 为悬停效果添加过渡
const baseTransform = getBaseTransform();
if (baseTransform === 'translateY(-50%)') {
button.style.transform = 'translateY(-50%) scale(1)';
} else {
button.style.transform = 'scale(1)';
}
button.style.background = 'linear-gradient(135deg, #4a90e2 0%, #357abd 100%)';
button.style.boxShadow = '0 4px 16px rgba(74, 144, 226, 0.4), 0 2px 8px rgba(0,0,0,0.2)';
// 悬停效果结束后移除 transition,防止影响位置设置
setTimeout(() => {
button.style.transition = '';
}, 200);
}
});
// Make it draggable
let startX, startY, initialX, initialY;
function startDrag(e) {
isDragging = true;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
startX = clientX;
startY = clientY;
initialX = button.offsetLeft;
initialY = button.offsetTop;
button.style.cursor = 'grabbing';
// 保持垂直居中的同时缩小
const baseTransform = getBaseTransform();
if (baseTransform === 'translateY(-50%)') {
button.style.transform = 'translateY(-50%) scale(0.95)';
} else {
button.style.transform = 'scale(0.95)';
}
e.preventDefault();
}
function drag(e) {
if (!isDragging) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const deltaX = clientX - startX;
const deltaY = clientY - startY;
let newX = initialX + deltaX;
let newY = initialY + deltaY;