-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtranslator.user.js
3620 lines (3210 loc) · 128 KB
/
translator.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
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
// ==UserScript==
// @name 网页中英双显互译
// @name:en Translation between Chinese and English
// @namespace http://yeyu1024.xyz
// @version 1.8.4
// @description 中-英-外互转,双语显示。支持谷歌,微软等API,为用户提供了快速准确的中英文翻译服务。无论是在工作中处理文件、学习外语、还是在日常生活中与国际友人交流,这个脚本都能够帮助用户轻松应对语言障碍。通过简单的操作,用户只需点击就会立即把网页翻译,节省了用户手动查词或使用在线翻译工具的时间,提高工作效率。
// @description:en Web pages translated into Chinese, English and foreign languages
// @description:de Webseite in Chinesisch, Englisch, Fremdsprachen
// @description:ru Перевод страницы на китайский, английский и иностранные языки
// @description:ar صفحة الإنترنت الصينية و الإنجليزية و اللغات الأجنبية
// @description:ja ホームページ中国語、英語、外国語の翻訳
// @description:ko WEB 중국어, 영어, 외국어 상호 번역
// @description:fr Traduction de pages Web en chinois, anglais, langues étrangères vers et depuis
// @description:pt Tradução de páginas da Web para chinês, inglês e língua estrangeira
// @author 夜雨
// @match *://*/*
// @exclude *://*.baidu.com/*
// @exclude *://localhost:*/*
// @exclude *://127.0.0.1:*/*
// @exclude *://*.bilibili.com/*
// @exclude *://*.jd.com/*
// @exclude *://*.taobao.com/*
// @exclude *://*.iqiyi.com/*
// @exclude *://*.360.cn/*
// @exclude *://*.gov.cn/*
// @exclude *://*.12306.cn/*
// @exclude *://*.ctrip.com/*
// @exclude *://*.hao123.com/*
// @exclude *://*.youku.com/*
// @exclude *://*.aliyun.com/*
// @exclude *://*.shushubuyue.net/*
// @exclude *://*.shushubuyue.com/*
// @exclude *://onfix.cn/*
// @exclude *://yeyu2048.xyz/*
// @run-at document-end
// @icon https://www.google.com/s2/favicons?sz=64&domain=translate.google.com
// @require https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js
// @require https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// @resource toastCss https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.css
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @grant GM_setClipboard
// @grant GM_registerMenuCommand
// @grant GM_getResourceText
// @grant unsafeWindow
// @connect api-edge.cognitive.microsofttranslator.com
// @connect edge.microsoft.com
// @connect fanyi-api.baidu.com
// @connect translate.googleapis.com
// @connect fanyi.sogou.com
// @connect ifanyi.iciba.com
// @connect dict.hjenglish.com
// @connect openapi.youdao.com
// @connect caiyunai.com
// @connect caiyunapp.com
// @connect transmart.qq.com
// @connect translate.alibaba.com
// @connect papago.naver.com
// @connect m.youdao.com
// @connect worldlingo.com
// @connect deepl.com
// @connect fanyi.baidu.com
// @connect flitto.com.cn
// @connect translate.yandex.com
// @connect yandex.net
// @connect fanyi.pdf365.cn
// @connect dict.cnki.net
// @connect itrans.xf-yun.com
// @connect kuaiyi.wps.cn
// @website https://greasyfork.org/zh-CN/scripts/469073
// @license MIT
// @downloadURL https://update.greasyfork.org/scripts/469073/%E7%BD%91%E9%A1%B5%E4%B8%AD%E8%8B%B1%E5%8F%8C%E6%98%BE%E4%BA%92%E8%AF%91.user.js
// @updateURL https://update.greasyfork.org/scripts/469073/%E7%BD%91%E9%A1%B5%E4%B8%AD%E8%8B%B1%E5%8F%8C%E6%98%BE%E4%BA%92%E8%AF%91.meta.js
// ==/UserScript==
(async function () {
'use strict';
//检测网页类型
try {
if(document.contentType ==='application/xml') return;
}catch (ex){console.error(ex)}
let authCode;//微软
let secretCode;//搜狗
let sogou_uuid;//搜狗uuid
const APIConst = {
Baidu: 'baidu',
BaiduMobileWeb: 'baiduMobileWeb',//百度手机版web
Microsoft: 'microsoft',
Google: 'google',
SogouWeb: 'sogouWeb',
ICIBAWeb: 'icibaWeb',//金山词霸
HujiangWeb: 'hujiangWeb',//沪江小D
Youdao: 'youdao',//有道api
CaiyunWeb: 'caiyunWeb',//彩云小译
TransmartWeb: 'transmartWeb',//腾讯交互式翻译 https://transmart.qq.com/zh-CN/index
AlibabaWeb: 'alibabaWeb',//阿里翻译
PapagoWeb: 'papagoWeb',//Papago
YoudaoMobileWeb: 'youdaoMobileWeb',//有道手机版
Worldlingo: 'worldlingo',//worldlingo https://fy.httpcn.com/fanyi/
DeepLWeb: 'deepLWeb',//DeepL
FlittoWeb: 'flittoWeb',//易翻通
YandexWeb: 'yandexWeb',//Yandex
FuxiWeb: 'fuxiWeb',//福昕翻译 https://fanyi.pdf365.cn/
CNKIWeb: 'CNKIWeb',//cnki
Xunfei: 'xunfei',//讯飞 API
WPSKuaiyiWeb: 'WPSKuaiyiWeb',//WSP 金山快译 web
BaiduAPI: {
name: "baidu",
ChineseLang: 'zh',
EnglishLang: 'en',
//appid 百度API有月额度(100w字符/月)限制,建议申请自己的秘钥,详见:https://fanyi-api.baidu.com/
appid: '20230622001720783', //appid 申请可见 这里需要修改成自己的appid
secret: 'dQVha4zSH26nMDLpfoVC'// secret 申请可见 这里需要修改成自己的secret
},
BaiduMobileWebAPI: {
name: "baiduMobileWeb",
ChineseLang: 'zh',
EnglishLang: 'en',
},
MicrosoftAPI: {
name: "microsoft",
ChineseLang: 'zh-Hans',
EnglishLang: 'en'
},
//google需要科学上网
GoogleAPI: {
name: "google",
ChineseLang: 'zh-CN',
EnglishLang: 'en'
},
SogouWebAPI: {
name: "sogouWeb",
ChineseLang: 'zh-CHS',
EnglishLang: 'en'
},
ICIBAWebAPI: {
name: "icibaWeb",
ChineseLang: 'zh',
EnglishLang: 'en'
},
HujiangWebAPI: {
name: 'hujiangWeb',
ChineseLang: 'cn',
EnglishLang: 'en'
},
YoudaoAPI: {
name: 'youdao',
ChineseLang: 'zh-CHS',
EnglishLang: 'en',
//有道翻译key配置,建议申请自己的秘钥 进行修改,详见:https://ai.youdao.com/console/#/service-singleton/text-translation
appId: '0625d97d20b47865', //填写自己的应用id
appKey: 'xxxxxxxxxxxxxxxxxxxx', //填写自己的应用秘钥
},
CaiyunWebAPI: {
name: 'caiyunWeb',
ChineseLang: 'zh',
EnglishLang: 'en'
},
TransmartWebAPI: {
name: 'transmartWeb',
ChineseLang: 'zh',
EnglishLang: 'en'
},
AlibabaWebAPI: {
name: 'alibabaWeb',
ChineseLang: 'zh',
EnglishLang: 'en'
},
PapagoWebAPI: {
name: 'papagoWeb',
ChineseLang: 'zh-CN',
EnglishLang: 'en'
},
YoudaoMobileWebAPI: {
name: 'youdaoMobileWeb',
ChineseLang: 'ZH_CN',
EnglishLang: 'EN'
},
WorldlingoAPI: {
name: 'worldlingo',
ChineseLang: 'zh_cn',
EnglishLang: 'en'
},
DeepLWebAPI: {
name: 'deepLWeb',
ChineseLang: 'ZH',
EnglishLang: 'EN'
},
FlittoWebAPI: {
name: 'flittoWeb',
ChineseLang: 11,
EnglishLang: 17
},
YandexWebAPI: {
name: 'yandexWeb',
ChineseLang: "zh",
EnglishLang: "en"
},
FuxiWebAPI: {
name: 'fuxiWeb',
ChineseLang: "zh-CN",
EnglishLang: "en"
},
CNKIWebAPI: {
name: 'CNKIWeb',
ChineseLang: "1",
EnglishLang: "0"
},
XunfeiAPI: {
name: 'xunfei',
ChineseLang: "cn",
EnglishLang: "en",
APPID: '535ee726',//讯飞翻译 appid 修改成自己的 详见https://console.xfyun.cn/services/its
APISecret: 'xxx',//讯飞翻译 APISecret 修改成自己的 详见https://console.xfyun.cn/services/its
APIKey: 'xxx'//讯飞翻译 APIKey 修改成自己的 详见https://console.xfyun.cn/services/its
},
WPSKuaiyiWebAPI: {
name: 'WPSKuaiyiWeb',
ChineseLang: "zh",
EnglishLang: "en"
}
}
let TRANSMART_CLIENT_KEY = '';
let currentAPI = APIConst.MicrosoftAPI //默认微软
let isDoubleShow = true //是否双显 true/false
let isHighlight = true //是否译文高亮 true/false
let englishAutoTranslate = false //英文自动翻译 true/false
let highlightColor = '#d8551f' //高亮颜色
let selectTolang = currentAPI.ChineseLang // 选词翻译目标语言
let selectMode = false //右键选词模式开关 true/false 默认关
let leftSelectMode = false //左键选词模式开关 true/false 默认关
let excludeSites = ['www.qq.com', 'yeyu1024.xyz'] //排除不运行的网站 exclude web host
let noTranslateWords = ['SpringBoot', 'ChatGPT', 'YouTube', 'Twitter'] //仅当单个词不会被翻译,是组合或句子时失效
let scrollTranslate = !!localStorage.getItem("scrollTranslate"); //是否滚动翻译 true/false
let switchIndex = 0;
let enableCache = true; //是否启用缓存 true/false 默认启用
let maxCacheCount = 1500; //最大缓存数量
function isMobile() {
let userAgentInfo = navigator.userAgent.toLowerCase();
let mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod","Mobile"];
let mobile_flag = false;
//根据userAgent判断是否是手机
for (let v = 0; v < mobileAgents.length; v++) {
if (userAgentInfo.indexOf(mobileAgents[v].toLowerCase()) > -1) {
mobile_flag = true;
break;
}
}
return mobile_flag;
}
try {
highlightColor = await GM_getValue("highlightColor", highlightColor)
}catch (e) { }
function getCookieValue(cookies, cookieName) {
let name = cookieName + "=";
let cookieArray = cookies.split(';');
for (let i = 0; i < cookieArray.length; i++) {
let cookie = cookieArray[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(name) === 0) {
return cookie.substring(name.length, cookie.length);
}
}
return "";
}
setTimeout(() => {
if (location.href.includes('translate.yandex.com')) {
GM_setValue("yandexuid", getCookieValue(document.cookie, "yandexuid"))
GM_setValue("yandexspravka", getCookieValue(document.cookie, "spravka"))
Toast.success("yandexuid 获取成功:" + getCookieValue(document.cookie, "yandexuid"))
Toast.success("spravka 获取成功:" + getCookieValue(document.cookie, "spravka"))
}
if (location.href.includes('dict.cnki.net')) {
GM_setValue("CNKI_TOKEN", getCookieValue(document.cookie, "token"))
Toast.success("CNKI_TOKEN 获取成功:" + getCookieValue(document.cookie, "token"))
}
if (location.href.includes('kuaiyi.wps.cn')) {
GM_setValue("wps_xcsrftoken", getCookieValue(document.cookie, "_xsrf"))
Toast.success("wps_xcsrftoken 获取成功:" + getCookieValue(document.cookie, "_xsrf"))
}
})
function isEqual(obj1, obj2) {
if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
return obj1 === obj2;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (!isEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
function addToArray(arr, obj, maxLength) {
maxLength = maxLength || maxCacheCount;
if (arr.length >= maxLength) {
arr.shift();
}
let flag = true;
let start = 0;
let end = arr.length - 1;
if (start > end) flag = true;//fix 空直接添加
//O(length/2)
while (start <= end) {
if (isEqual(arr[start], obj) || isEqual(arr[end], obj)) {
flag = true;
break;
}
start++;
end--;
}
//O(length)
/*for (let i = 0; i < arr.length; i++) {
if (isEqual(arr[i], obj)) {
flag = false;
break;
}
}*/
if (flag) {
arr.push(obj);
}
return arr;
}
function combineArray(arr1, arr2) {
/*for (let i = 0; i < arr2.length; i++) {
addToArray(arr1, arr2[i])
}*/
let start = 0;
let end = arr2.length - 1;
if (start > end) return arr1;
while (start <= end) {
if (start === end) {
addToArray(arr1, arr2[start])
} else {
addToArray(arr1, arr2[start])
addToArray(arr1, arr2[end])
}
start++;
end--;
}
return arr1;
}
function jsonToObject(jsonStr) {
try {
const obj = JSON.parse(jsonStr);
return obj;
} catch (error) {
console.error('Invalid JSON string:', error);
return [];
}
}
function objectToJson(obj) {
try {
const jsonStr = JSON.stringify(obj);
return jsonStr;
} catch (error) {
console.error('Error converting object to JSON:', error);
return [];
}
}
let cacheChanged = true;
let tempCache;
function readCache(key) {
if (cacheChanged) {
const value = localStorage.getItem(key);
const ret = (value !== null ? jsonToObject(value) : [])
tempCache = ret;
return ret;
} else {
return tempCache || [];
}
}
function storeCache(key, store_arr) {
cacheChanged = true;
const old_cache = readCache(key)
const new_cache = combineArray(old_cache, store_arr)
localStorage.setItem(key, objectToJson(new_cache))
}
function translateFromCache(text, node, lang, key) {
//异步
return new Promise((resolve, reject) => {
if (!text) {
//console.error("no text:", text)
// return true;
resolve("no text:")
return
}
if (noTranslateWords.includes(text)) {
// return true;
resolve("do not TranslateWords")
return
}
let shouldBreak = false;
let rj = false;//reject
try {
const cache = readCache(key) //[{},{}...]
if (cache) {
//双指针找 >>>
let start = 0;
let end = cache.length - 1;
while (start <= end) {
if (lang === currentAPI.ChineseLang) {
//en to zh
if (cache[start].english === text || cache[end].english === text) {
setTimeout(() => {
renderPage({cacheResult: cache[start].english === text ? cache[start].chinese : cache[end].chinese},
text, node, lang)
})
console.warn("en to zh cache: ", text)
shouldBreak = true;
break;
//return true;
}
} else if (lang === currentAPI.EnglishLang) {
//zh to en
if (cache[start].chinese === text || cache[end].chinese === text) {
console.warn("zh to en cache: ", text)
setTimeout(() => {
renderPage({cacheResult: cache[start].chinese === text ? cache[start].english : cache[end].english},
text, node, lang)
})
shouldBreak = true;
break;
//return true;
}
} else {
//return false;
shouldBreak = true;
rj = true;
break;
}
start++;
end--;
}
//双指针 <<<<
}
} catch (e) {
console.error("translateFromCache ex", e)
//return false;
reject("translateFromCache ex")
return;
}
if (shouldBreak) {
if (rj) {
//中断被拒绝
reject('语言异常')
} else {
//中断未被拒绝
resolve('成功缓存')
}
} else {
//不中断
reject('无缓存')
}
// return false;
})
}
function addToastCss() {
try {
GM_addStyle(GM_getResourceText("toastCss"))
} catch (e) {
}
}
addToastCss()
function changeSelectLang() {
if (selectTolang === currentAPI.ChineseLang) {
selectTolang = currentAPI.EnglishLang;
console.log('当前目标语言为外语')
Toast.success('当前目标语言为外语')
GM_setValue("selectTolang","EnglishLang")
} else {
selectTolang = currentAPI.ChineseLang;
console.log('当前目标语言为中文')
Toast.success('当前目标语言为中文')
GM_setValue("selectTolang","ChineseLang")
}
}
function autoTranslateSwitch() {
if (englishAutoTranslate) {
englishAutoTranslate = false;
GM_setValue("englishAutoTranslate", false)
Toast.error('外语自动翻译已关闭! 请重新刷新页面.')
} else {
englishAutoTranslate = true;
GM_setValue("englishAutoTranslate", true)
Toast.success('外语自动翻译已打开! 请重新刷新页面.')
}
}
function rightSelectMode() {
if (selectMode) {
console.log('鼠标右击选词翻译已经关闭', selectMode)
selectMode = false;
//移除事件
document.removeEventListener('mousemove', handleMousemove);
document.removeEventListener('mouseout', handleMouseout);
document.removeEventListener('contextmenu', handleContextmenu);//右击事件
Toast.success('鼠标右击选词翻译已经关闭')
} else {
console.log('鼠标右击选词翻译已经开启', selectMode)
selectMode = true;
//增加事件
document.addEventListener('mousemove', handleMousemove);
document.addEventListener('mouseout', handleMouseout);
document.addEventListener('contextmenu', handleContextmenu);//右击事件
Toast.success('鼠标右击选词翻译已经开启')
}
}
//是否支持多语种的引擎
function isSupportMultiLang(){
return currentAPI.name === APIConst.TransmartWeb || currentAPI.name === APIConst.Microsoft || currentAPI.name === APIConst.Google
|| currentAPI.name === APIConst.BaiduMobileWeb || currentAPI.name === APIConst.AlibabaWeb
}
function colorSelectAndSettings(event) {
$("body").append(`<div class="MyColorSelector" style="z-index: 9999 !important;padding:16px;position: fixed;border-radius: 4px;border: 1px salmon solid;top: 10%;bottom: 10%;left: 50%;transform: translateX(-50%);background: white;box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 5px;overflow-y: scroll;" id="MyColorSelector">
<div>
<label for="redRange">红/Red:</label>
<input type="range" id="redRange" min="0" max="255" value="0" onchange="document.getElementById('redval').innerHTML = value">
<span style="color: red" id="redval">0</span>
</div>
<div>
<label for="greenRange">绿/Green:</label>
<input type="range" id="greenRange" min="0" max="255" value="0" onchange="document.getElementById('greenval').innerHTML = value">
<span style="color: green" id="greenval">0</span>
</div>
<div>
<label for="blueRange">蓝/Blue:</label>
<input type="range" id="blueRange" min="0" max="255" value="0" onchange="document.getElementById('blueval').innerHTML = value">
<span style="color: blue" id="blueval">0</span>
</div>
<div>
<div style=" width: 50px; height: 50px; margin-top: 10px;margin-bottom: 10px;margin-left: 20px" id="colorDisplay"></div>
<div style="font-size: 30px;" id="colorPreview">文字预览</div>
</div>
<button style="cursor: pointer;color: white;border: 6px;outline: none;background: #4caf50;padding: 8px 0;border-radius: 6px;font-size: 14px;margin: 0 auto;margin-top: 6px;width: 70px;" id="selectColorBtn">确定</button>
<button style="cursor: pointer;color: white;border: 6px;outline: none;background: #4caf50;padding: 8px 0;border-radius: 6px;font-size: 14px;margin: 0 auto;margin-top: 6px;width: 70px;" id="scrollBtn">滚动</button>
<button style="cursor: pointer;color: white;border: 6px;outline: none;background: #4caf50;padding: 8px 0;border-radius: 6px;font-size: 14px;margin: 0 auto;margin-top: 6px;width: 70px;" id="selectColorCancelBtn">退出</button>
<div><span style="margin-top: 10px">温馨提示:在输入框时,连续按三下空格键即可翻译输入框的内容.</span></div>
<div><span>翻译引擎:</span>
<select id="selectAPI">
<option value="999">微软[推荐]</option>
<option value="0">百度[需key]</option>
<option value="1">谷歌[推荐]</option>
<option value="2">搜狗</option>
<option value="3">词霸</option>
<option value="4">沪江小D</option>
<option value="5">有道[需key]</option>
<option value="6">彩云</option>
<option value="7">腾讯交互[推荐]</option>
<option value="8">Alibaba</option>
<option value="9">Papago</option>
<option value="10">有道手机[推荐]</option>
<option value="11">worldlinGO</option>
<option value="12">DeepL[限制]</option>
<option value="13">百度手机</option>
<option value="14">易翻通</option>
<option value="15">Yandex</option>
<option value="16">福昕</option>
<option value="17">CNKI</option>
<option value="18">讯飞[需key]</option>
<option value="19">金山快译</option>
</select>
<button style="cursor: pointer;color: white;border: 6px;outline: none;background: #4caf50;padding: 8px 0;border-radius: 6px;font-size: 14px;margin: 0 auto;margin-top: 6px;width: 70px;" id="selectAPIBtn">选择</button>
</div>
<div><span style="margin-top: 10px">注意:外语目前仅适用部分引擎,语言代码可能会存在差异,其他默认英语.</span></div>
<div><span>外语语言:</span>
<select id="selectForeign">
<option value="en">英语(en)</option>
<option value="ja">日语(ja)</option>
<option value="ko">韩语(ko)</option>
<option value="ru">俄语(ru)</option>
<option value="de">徳语(de)</option>
<option value="fr">法语(fr)</option>
<option value="th">泰语(th)</option>
<option value="hi">印地(hi)</option>
<option value="it">意大利(it)</option>
<option value="pt">葡萄牙(pt)</option>
<option value="ar">阿拉伯(ar)</option>
<option value="vi">越南语(vi)</option>
<option value="tr">土耳其(tr)</option>
<option value="id">印尼(id)</option>
<option value="zh">中文(zh)</option>
<option value="zh-Hans">中文(zh-Hans)</option>
<option value="zh-CN">中文(zh-CN)</option>
<option value="zh_cn">中文(zh_cn)</option>
<option value="zh-CHS">中文(zh-CHS)</option>
<option value="cn">中文(cn)</option>
<option value="zh-TW">中文繁体(zh-TW)</option>
</select>
<button style="cursor: pointer;color: white;border: 6px;outline: none;background: #4caf50;padding: 8px 0;border-radius: 6px;font-size: 14px;margin: 0 auto;margin-top: 6px;width: 70px;" id="selectForeignBtn">选择</button>
</div>
</div>
`);
const MyColorSelector = document.getElementById("MyColorSelector");
const redRange = document.getElementById("redRange");
const greenRange = document.getElementById("greenRange");
const blueRange = document.getElementById("blueRange");
const colorDisplay = document.getElementById("colorDisplay");
const colorPreview = document.getElementById("colorPreview");
const selectColorBtn = document.getElementById("selectColorBtn");
const selectColorCancelBtn = document.getElementById("selectColorCancelBtn");
const selectAPIBtn = document.getElementById("selectAPIBtn");
const scrollBtn = document.getElementById("scrollBtn");
const selectForeignBtn = document.getElementById("selectForeignBtn");
// 更新颜色显示区域的颜色
function updateColorDisplay() {
const redValue = redRange.value;
const greenValue = greenRange.value;
const blueValue = blueRange.value;
const selectedColor = `rgb(${redValue},${greenValue},${blueValue})`;
colorDisplay.style.backgroundColor = selectedColor;
colorPreview.style.color = selectedColor
}
// 添加滑块的 input 事件处理程序
redRange.addEventListener("input", updateColorDisplay);
greenRange.addEventListener("input", updateColorDisplay);
blueRange.addEventListener("input", updateColorDisplay);
selectColorBtn.addEventListener("click", (ev)=>{
const redValue = redRange.value;
const greenValue = greenRange.value;
const blueValue = blueRange.value;
const selectedColor = `rgb(${redValue},${greenValue},${blueValue})`;
GM_setValue("highlightColor", selectedColor)
Toast.success("请重新刷新页面生效!")
MyColorSelector.remove()
});
selectColorCancelBtn.addEventListener("click", (ev)=>{
MyColorSelector.remove()
});
//本站滚动
scrollBtn.addEventListener("click", (ev)=>{
if(scrollTranslate){
localStorage.removeItem("scrollTranslate")
scrollTranslate = false
Toast.error("本站滚动翻译已关!")
window.removeEventListener('scroll', handleScroll);
}else {
localStorage.setItem("scrollTranslate", "open")
scrollTranslate = true
Toast.info("本站滚动翻译已开,如需要切换语言请点侧边的语言按钮!")
window.addEventListener('scroll', handleScroll);
}
})
//选择引擎
selectAPIBtn.addEventListener('click', () => {
const selectEl = document.getElementById('selectAPI');
const selectedValue = selectEl.options[selectEl.selectedIndex].value;
switchIndex = selectedValue
switchAPI(true)
MyColorSelector.remove() //退出
});
//选择外语语种
selectForeignBtn.addEventListener('click', () => {
const selectEl = document.getElementById('selectForeign');
const selectedValue = selectEl.options[selectEl.selectedIndex].value;
if(isSupportMultiLang()){
Reflect.set(currentAPI,"EnglishLang",selectedValue)
Toast.success("设置成功!" + selectedValue)
localStorage.removeItem(`${currentAPI.name}wordCache`)//清空缓存
GM_setValue("selectForeignLang", selectedValue)
MyColorSelector.remove() //退出
}else{
Toast.error("暂时仅支持腾讯交互,谷歌,微软, 手机有道,阿里翻译。请切换引擎后设置")
}
});
// 初始化颜色显示
updateColorDisplay();
//加载预览色
colorDisplay.style.backgroundColor = highlightColor;
colorPreview.style.color = highlightColor
//提示当前引擎
try {
Toast.info(`当前API:${currentAPI.name}`)
} catch (e) {}
}
//注册菜单
setTimeout(() => {
GM_registerMenuCommand("更新脚本", function (event) {
if(isMobile()){
location.href = "https://greasyfork.org/zh-CN/scripts/469073"
}else {
GM_openInTab("https://greasyfork.org/zh-CN/scripts/469073")
}
}, "updateTranslateJS");
GM_registerMenuCommand("颜色/设置", colorSelectAndSettings, "HeightLightColor");
GM_registerMenuCommand("排除/放行该站", function (event) {
if (excludeSites.includes(location.host)) {
console.log('网站已经存在,现已经放行')
excludeSites = excludeSites.filter(function (element) {
return element !== location.host; // 返回不等于要删除元素的元素
});
console.log(excludeSites);
Toast.success('网站已经存在,现已经放行')
} else {
console.log('网站不存在, 现已经排除')
excludeSites.push(location.host)
Toast.success('网站不存在, 现已经排除')
}
GM_setValue("excludeSites", JSON.stringify(excludeSites))
console.log(excludeSites)
}, "excludeWeb");
// GM_registerMenuCommand("鼠标右击选词开关", rightSelectMode, "selectMode");
})
//载入配置
async function loadConfig() {
//载入腾讯
setTimeout(()=>{
if(location.host.includes("transmart.qq.com")){
GM_setValue("TRANSMART_CLIENT_KEY", unsafeWindow.TRANSMART_CLIENT_KEY)
Toast.info(`获取权信息${unsafeWindow.TRANSMART_CLIENT_KEY},请返回重新:`)
}
},3000)
TRANSMART_CLIENT_KEY = await GM_getValue("TRANSMART_CLIENT_KEY", `browser-chrome-122.0.6261-Windows_10-${uuidv4()}-${Date.now()}`)
isDoubleShow = await GM_getValue("isDoubleShow", true)
isHighlight = await GM_getValue("isHighlight", true)
englishAutoTranslate = await GM_getValue("englishAutoTranslate", false)
leftSelectMode = await GM_getValue("leftSelectMode", false)
let selectlang = await GM_getValue("selectTolang", "ChineseLang")
setTimeout(()=>{
if(leftSelectMode){
leftSelectMode = false;
leftSelect(true)
}
if(selectlang === 'ChineseLang'){
selectTolang = currentAPI.ChineseLang
}else{
selectTolang = currentAPI.EnglishLang
}
})
try {
switchIndex = await GM_getValue("switchIndex", 0) - 1
console.warn("switchIndex", switchIndex)
switchAPI(false)
} catch (ex) {
switchIndex = 0;
console.error("switchIndex ex:", switchIndex, ex)
}
//载入外语语种
try {
if(isSupportMultiLang()){
let selectForeignLang = await GM_getValue("selectForeignLang")
if(selectForeignLang){
Reflect.set(currentAPI, "EnglishLang", selectForeignLang)
}
}
console.warn("selectForeignLang load:", selectForeignLang)
} catch (ex) {
console.error("selectForeignLang load ex:", switchIndex, ex)
}
console.warn("isDoubleShow", isDoubleShow)
console.warn("isHighlight", isHighlight)
console.warn("englishAutoTranslate", englishAutoTranslate)
const excludeSitesConfig = await GM_getValue("excludeSites")
if (excludeSitesConfig) {
try {
excludeSites = JSON.parse(excludeSitesConfig)
} catch (e) {
console.error('json出错:', e, excludeSitesConfig)
}
}
console.warn('excludeSites', excludeSites)
//toastr配置
toastr.options = {
// "closeButton": false,
// "debug": false,
// "newestOnTop": false,
// "progressBar": false,
"positionClass": "toast-top-right", // 提示框位置,这里填类名
// "preventDuplicates": false,
// "onclick": null,
"showDuration": "1000", // 提示框渐显所用时间
"hideDuration": "1000", // 提示框隐藏渐隐时间
"timeOut": "5000", // 提示框持续时间
"extendedTimeOut": "2000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
}
try {
await loadConfig()
} catch (e) {
console.error("load config error:", e)
}
function handleMouseout(event) {
const target = event.target;
if (target.classList.contains('translate-main')) {
return
}
target.style.border = '';
//console.error('mouseout' + target);
}
function handleMousemove(event) {
const target = event.target;
if (target.classList.contains('translate-main')) {
return
}
target.style.border = '1px solid red';
//console.log('mousemove' + target);
}
function handleContextmenu(event) {
event.preventDefault(); // 阻止默认右键菜单的显示
const target = event.target;
console.warn('contextmenu' + target);
target.style.border = '';
//翻译
translateTo(selectTolang, target)
}
async function handleMouseUpOrTouchend(event) {
event.stopPropagation()
//copyTranslatedText
if (/copyTranslatedText/.test(event.target.id)) {
GM_setClipboard(document.querySelector('#qs_selectedText').innerText, "text");
console.log('复制成功')
Toast.success("复制成功!")
return
}
const selectText = window.getSelection().toString()
//console.error(event.target)
if (/(qs_searchBoxOuter|qs_searchBox|qs_selectedText)/.test(event.target.id)) {
return;
} else {
document.querySelectorAll('#qs_searchBoxOuter').forEach(item => {
item.remove();
})
}
if (!selectText) return;
console.warn(selectText)
let mouseX = event.pageX;
let mouseY = event.pageY;
if (event.changedTouches && event.changedTouches.length > 0) {
mouseX = event.changedTouches[0].pageX
mouseY = event.changedTouches[0].pageY
}
console.log('鼠标位置:', mouseX, mouseY);
$("body").append($(`
<div id="qs_searchBoxOuter">
<a id="qs_searchBox" style="display: block; left:${mouseX - 10}px; top: ${mouseY}px;">
<div id="qs_selectedText">${selectText}</div>
<hr>
<div id="qs_searchIconOuter"><span id="qs_searchIconInner"><svg id="copyTranslatedText" width="24" height="24" data-v-13fede38="" t="1679666016648" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6241" class="icon"><path data-v-13fede38="" d="M661.333333 234.666667A64 64 0 0 1 725.333333 298.666667v597.333333a64 64 0 0 1-64 64h-469.333333A64 64 0 0 1 128 896V298.666667a64 64 0 0 1 64-64z m-21.333333 85.333333H213.333333v554.666667h426.666667v-554.666667z m191.829333-256a64 64 0 0 1 63.744 57.856l0.256 6.144v575.701333a42.666667 42.666667 0 0 1-85.034666 4.992l-0.298667-4.992V149.333333H384a42.666667 42.666667 0 0 1-42.368-37.674666L341.333333 106.666667a42.666667 42.666667 0 0 1 37.674667-42.368L384 64h447.829333z" fill="#909399" p-id="6242"></path></svg></span></div>
</a>
</div>
`))
const old_isDoubleShow = isDoubleShow;
isDoubleShow = false;
translateTo(selectTolang, document.getElementById("qs_searchBoxOuter"), true)
setTimeout(() => {
isDoubleShow = old_isDoubleShow;
}, 2000)
console.log('鼠标松开了');
}
function leftSelect(noToast) {
if (leftSelectMode) {
console.log('鼠标选词翻译已经关闭', leftSelectMode)
leftSelectMode = false;
document.removeEventListener('mouseup', handleMouseUpOrTouchend);
document.removeEventListener('touchcancel', handleMouseUpOrTouchend);
if(!noToast){
Toast.success('选词翻译已经关闭')
}
} else {
console.log('鼠标选词翻译已经开启', leftSelectMode)
leftSelectMode = true;
document.addEventListener('mouseup', handleMouseUpOrTouchend);
document.addEventListener('touchcancel', handleMouseUpOrTouchend);
if(!noToast) {
Toast.success('选词翻译已经开启')
}
}
GM_setValue("leftSelectMode",leftSelectMode)
}
function switchAPI(openWeb) {
switchIndex++;
try {
switch (switchIndex) {
case 1:
currentAPI = APIConst.BaiduAPI
Toast.success('已经切换百度翻译,未配置api需源码中修改秘钥.建议申请自己的秘钥,详见:https://fanyi-api.baidu.com/')
break
case 2:
currentAPI = APIConst.GoogleAPI
Toast.success('已经切换谷歌翻译')
break
case 3:
currentAPI = APIConst.SogouWebAPI
Toast.success('已经切换搜狗翻译')
break