-
Notifications
You must be signed in to change notification settings - Fork 48
/
Google & Baidu Switcher.user.js
3293 lines (3128 loc) · 228 KB
/
Google & Baidu Switcher.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 Google & baidu Switcher (ALL in One)
// @name:en Search Engine Assistant
// @name:zh-CN 优雅的搜索引擎助手
// @name:zh-TW 優雅的搜尋引擎助手
// @name:ru помощник поисковых систем
// @name:ja 優雅な検索エンジン助手
// @version 2024.10.05.1
// @author F9y4ng
// @description “Elegant Search Engine Assistant” facilite la navigation entre moteurs de recherche, personnalise les préférences, met en évidence les mots-clés, élimine les redirections et publicités, et filtre les résultats. Compatible avec divers moteurs tels que Baidu, Google, Bing, Duckduckgo, Yandex, Sogou, Qwant, Ecosia, You, Startpage, Brave, etc.
// @description:en "Elegant search engine assistant" allows switching between engines; supports custom engines, keyword highlighting; offers redirect removal, ad blocking, keyword filtering, and auto-updates; compatible with Baidu, Google, Bing, Duckduckgo, Yandex, Sogou, Qwant, Ecosia, You, Startpage, Brave, Yahoo, Yep, Swisscows, searXNG and more.
// @description:zh-CN “优雅的搜索引擎助手”方便用户在不同的搜索引擎之间跳转;支持自定义常用搜索引擎、关键词高亮渲染;还提供去除搜索链接重定向、屏蔽搜索结果广告、使用关键词过滤搜索结果、和自动更新检测等高级功能;兼容如Baidu、Google、Bing、Duckduckgo、Yandex、Sogou、Qwant、Ecosia、You、Startpage、Brave、Yahoo、Yep、Swisscows、searXNG等多个搜索引擎。
// @description:zh-TW 「優雅的搜尋引擎助手」方便使用者在不同的搜尋引擎之間跳轉;支援自定義常用搜尋引擎、關鍵詞高亮渲染;還提供去除搜尋連結重定向、遮蔽搜尋結果廣告、使用關鍵詞過濾搜尋結果、和自動更新檢測等高階功能;相容如Baidu、Google、Bing、Duckduckgo、Yandex、Sogou、Qwant、Ecosia、You、Startpage、Brave、Yahoo、Yep、Swisscows、searXNG等多個搜尋引擎。
// @description:ru “Элегантный помощник поисковых систем” обеспечивает удобное переключение между поисковыми системами, поддерживает настройку, выделение ключевых слов и продвинутые функции. совместим с Baidu, Google, Bing, Duckduckgo, Yandex, Sogou, Qwant, Ecosia, You, Startpage, Brave, Yahoo, Yep, Swisscows, searXNG и другими поисковыми системами.
// @description:ja 「優雅な検索エンジン助手」は、検索エンジン間の切り替えを容易にし、カスタムエンジン、キーワードハイライト、リダイレクト削除、広告ブロック、キーワードフィルタリング、自動更新をサポートし、Baidu、Google、Bing、Duckduckgo、Yandex、Sogou、Qwant、Ecosia、You、Startpage、Brave、Yahoo、Yep、Swisscows、searXNGなどと互換性があります。
// @namespace https://openuserjs.org/scripts/f9y4ng/Google_baidu_Switcher_(ALL_in_One)
// @icon https://img.icons8.com/stickers/48/search-in-cloud.png
// @homepage https://f9y4ng.github.io/GreasyFork-Scripts/
// @homepageURL https://f9y4ng.github.io/GreasyFork-Scripts/
// @supportURL https://github.com/F9y4ng/GreasyFork-Scripts/issues
// @updateURL https://github.com/F9y4ng/GreasyFork-Scripts/raw/master/Google%20%26%20Baidu%20Switcher.meta.js
// @downloadURL https://github.com/F9y4ng/GreasyFork-Scripts/raw/master/Google%20%26%20Baidu%20Switcher.user.js
// @require https://update.greasyfork.org/scripts/460897/1277476/gbCookies.js#sha256-Sv+EuBerch8z/6LvAU0m/ufvjmqB1Q/kbQrX7zAvOPk=
// @match *://www.baidu.com/*
// @match *://ipv6.baidu.com/*
// @match *://image.baidu.com/search*
// @match *://kaifa.baidu.com/searchPage*
// @match *://*.bing.com/*search*
// @match *://duckduckgo.com/*
// @match *://*.sogou.com/*
// @match *://www.qwant.com/?*
// @match *://www.so.com/s*
// @match *://image.so.com/*
// @match *://so.toutiao.com/search*
// @match *://yandex.com/*search*
// @match *://yandex.ru/*search*
// @match *://www.ecosia.org/*
// @match *://*.search.yahoo.com/search*
// @match *://*.images.search.yahoo.com/search*
// @match *://you.com/search*
// @match *://www.startpage.com/*
// @match *://search.brave.com/*
// @match *://yep.com/*
// @match *://swisscows.com/*
// @match *://search.inetol.net/search*
// @match *://*.google.com/search*
// @match *://*.google.ad/search*
// @match *://*.google.ae/search*
// @match *://*.google.com.af/search*
// @match *://*.google.com.ag/search*
// @match *://*.google.com.ai/search*
// @match *://*.google.al/search*
// @match *://*.google.am/search*
// @match *://*.google.co.ao/search*
// @match *://*.google.com.ar/search*
// @match *://*.google.as/search*
// @match *://*.google.at/search*
// @match *://*.google.com.au/search*
// @match *://*.google.az/search*
// @match *://*.google.ba/search*
// @match *://*.google.com.bd/search*
// @match *://*.google.be/search*
// @match *://*.google.bf/search*
// @match *://*.google.bg/search*
// @match *://*.google.com.bh/search*
// @match *://*.google.bi/search*
// @match *://*.google.bj/search*
// @match *://*.google.com.bn/search*
// @match *://*.google.com.bo/search*
// @match *://*.google.com.br/search*
// @match *://*.google.bs/search*
// @match *://*.google.bt/search*
// @match *://*.google.co.bw/search*
// @match *://*.google.by/search*
// @match *://*.google.com.bz/search*
// @match *://*.google.ca/search*
// @match *://*.google.cd/search*
// @match *://*.google.cf/search*
// @match *://*.google.cg/search*
// @match *://*.google.ch/search*
// @match *://*.google.ci/search*
// @match *://*.google.co.ck/search*
// @match *://*.google.cl/search*
// @match *://*.google.cm/search*
// @match *://*.google.cn/search*
// @match *://*.google.com.co/search*
// @match *://*.google.co.cr/search*
// @match *://*.google.com.cu/search*
// @match *://*.google.cv/search*
// @match *://*.google.com.cy/search*
// @match *://*.google.cz/search*
// @match *://*.google.de/search*
// @match *://*.google.dj/search*
// @match *://*.google.dk/search*
// @match *://*.google.dm/search*
// @match *://*.google.com.do/search*
// @match *://*.google.dz/search*
// @match *://*.google.com.ec/search*
// @match *://*.google.ee/search*
// @match *://*.google.com.eg/search*
// @match *://*.google.es/search*
// @match *://*.google.com.et/search*
// @match *://*.google.fi/search*
// @match *://*.google.com.fj/search*
// @match *://*.google.fm/search*
// @match *://*.google.fr/search*
// @match *://*.google.ga/search*
// @match *://*.google.ge/search*
// @match *://*.google.gg/search*
// @match *://*.google.com.gh/search*
// @match *://*.google.com.gi/search*
// @match *://*.google.gl/search*
// @match *://*.google.gm/search*
// @match *://*.google.gr/search*
// @match *://*.google.com.gt/search*
// @match *://*.google.gy/search*
// @match *://*.google.hk/search*
// @match *://*.google.com.hk/search*
// @match *://*.google.hn/search*
// @match *://*.google.hr/search*
// @match *://*.google.ht/search*
// @match *://*.google.hu/search*
// @match *://*.google.co.id/search*
// @match *://*.google.ie/search*
// @match *://*.google.co.il/search*
// @match *://*.google.im/search*
// @match *://*.google.co.in/search*
// @match *://*.google.iq/search*
// @match *://*.google.is/search*
// @match *://*.google.it/search*
// @match *://*.google.je/search*
// @match *://*.google.com.jm/search*
// @match *://*.google.jo/search*
// @match *://*.google.jp/search*
// @match *://*.google.co.jp/search*
// @match *://*.google.co.ke/search*
// @match *://*.google.com.kh/search*
// @match *://*.google.ki/search*
// @match *://*.google.kg/search*
// @match *://*.google.co.kr/search*
// @match *://*.google.com.kw/search*
// @match *://*.google.kz/search*
// @match *://*.google.la/search*
// @match *://*.google.com.lb/search*
// @match *://*.google.li/search*
// @match *://*.google.lk/search*
// @match *://*.google.co.ls/search*
// @match *://*.google.lt/search*
// @match *://*.google.lu/search*
// @match *://*.google.lv/search*
// @match *://*.google.com.ly/search*
// @match *://*.google.co.ma/search*
// @match *://*.google.md/search*
// @match *://*.google.me/search*
// @match *://*.google.mg/search*
// @match *://*.google.mk/search*
// @match *://*.google.ml/search*
// @match *://*.google.com.mm/search*
// @match *://*.google.mn/search*
// @match *://*.google.ms/search*
// @match *://*.google.com.mt/search*
// @match *://*.google.mu/search*
// @match *://*.google.mv/search*
// @match *://*.google.mw/search*
// @match *://*.google.com.mx/search*
// @match *://*.google.com.my/search*
// @match *://*.google.co.mz/search*
// @match *://*.google.com.na/search*
// @match *://*.google.com.ng/search*
// @match *://*.google.com.ni/search*
// @match *://*.google.ne/search*
// @match *://*.google.nl/search*
// @match *://*.google.no/search*
// @match *://*.google.com.np/search*
// @match *://*.google.nr/search*
// @match *://*.google.nu/search*
// @match *://*.google.co.nz/search*
// @match *://*.google.com.om/search*
// @match *://*.google.com.pa/search*
// @match *://*.google.com.pe/search*
// @match *://*.google.com.pg/search*
// @match *://*.google.com.ph/search*
// @match *://*.google.com.pk/search*
// @match *://*.google.pl/search*
// @match *://*.google.pn/search*
// @match *://*.google.com.pr/search*
// @match *://*.google.ps/search*
// @match *://*.google.pt/search*
// @match *://*.google.com.py/search*
// @match *://*.google.com.qa/search*
// @match *://*.google.ro/search*
// @match *://*.google.ru/search*
// @match *://*.google.rw/search*
// @match *://*.google.com.sa/search*
// @match *://*.google.com.sb/search*
// @match *://*.google.sc/search*
// @match *://*.google.se/search*
// @match *://*.google.com.sg/search*
// @match *://*.google.sh/search*
// @match *://*.google.si/search*
// @match *://*.google.sk/search*
// @match *://*.google.com.sl/search*
// @match *://*.google.sn/search*
// @match *://*.google.so/search*
// @match *://*.google.sm/search*
// @match *://*.google.sr/search*
// @match *://*.google.st/search*
// @match *://*.google.com.sv/search*
// @match *://*.google.td/search*
// @match *://*.google.tg/search*
// @match *://*.google.co.th/search*
// @match *://*.google.com.tj/search*
// @match *://*.google.tl/search*
// @match *://*.google.tm/search*
// @match *://*.google.tn/search*
// @match *://*.google.to/search*
// @match *://*.google.com.tr/search*
// @match *://*.google.tt/search*
// @match *://*.google.com.tw/search*
// @match *://*.google.co.tz/search*
// @match *://*.google.com.ua/search*
// @match *://*.google.co.ug/search*
// @match *://*.google.co.uk/search*
// @match *://*.google.com.uy/search*
// @match *://*.google.co.uz/search*
// @match *://*.google.com.vc/search*
// @match *://*.google.co.ve/search*
// @match *://*.google.vg/search*
// @match *://*.google.co.vi/search*
// @match *://*.google.com.vn/search*
// @match *://*.google.vu/search*
// @match *://*.google.ws/search*
// @match *://*.google.rs/search*
// @match *://*.google.co.za/search*
// @match *://*.google.co.zm/search*
// @match *://*.google.co.zw/search*
// @match *://*.google.cat/search*
// @exclude *://www.google.com/sorry*
// @exclude *://www.baidu.com/link*
// @exclude *://www.sogou.com/link*
// @exclude *://www.so.com/link*
// @exclude *://so.toutiao.com/search/jump*
// @connect baidu.com
// @connect sogou.com
// @connect so.com
// @connect greasyfork.org
// @connect openuserjs.org
// @connect githubusercontent.com
// @connect favicon.yandex.net
// @grant GM_getValue
// @grant GM.getValue
// @grant GM_setValue
// @grant GM.setValue
// @grant GM_listValues
// @grant GM.listValues
// @grant GM_deleteValue
// @grant GM.deleteValue
// @grant GM_openInTab
// @grant GM.openInTab
// @grant GM_registerMenuCommand
// @grant GM.registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @note {"CN":"修正部分搜索引擎跳转按钮样式问题。","EN":"Fixed some search engine jump button style issue."}
// @note {"CN":"修正从百度首页搜索时按钮消失的问题。","EN":"Fixed buttons disappear when search from homepage."}
// @note {"CN":"修正页面滚动按钮样式切换函数的问题。","EN":"Fixed Bug of the page scroll style toggle function."}
// @note {"CN":"修正一些已知问题,优化代码,优化样式。","EN":"Fixed some known issues, optimized code & style."}
// @compatible edge 兼容Tampermonkey, Violentmonkey
// @compatible Chrome 兼容Tampermonkey, Violentmonkey
// @compatible Firefox 兼容Greasemonkey, Tampermonkey, Violentmonkey
// @compatible Opera 兼容Tampermonkey, Violentmonkey
// @compatible Safari 兼容Tampermonkey, Userscripts
// @license GPL-3.0-only
// @create 2015-10-07
// @copyright 2015-2024, F9y4ng
// @run-at document-start
// ==/UserScript==
/* jshint esversion: 11 */
void (function (ctx, SearchEngineAssistant, arrayProxy, customFns) {
"use strict";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* CUSTOM SCRIPT DEBUGGING, DO NOT TURN ON FOR DAILY USE. *
* SET TO "TRUE" FOR SCRIPT DEBUGGING, MAY CAUSE THE SCRIPT TO RUN SLOWLY. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const IS_OPEN_DEBUG = false;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* LICENSE FOR OPEN SOURCE USE: `GPLv3 ONLY`. *
* THE CODE IS COMPLETELY OPEN AND FREE, AND DOES NOT ACCEPT UNAUTHORIZED *
* DISTRIBUTION AS THIRD-PARTY STANDALONE SCRIPTS. IN CASE OF ERRORS, USAGE *
* PROBLEMS OR NEW FEATURES, PLEASE FEEDBACK IN GITHUB ISSUES, THANK YOU! *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const { defineMethod, arrayMethods, obj = Object.create(null) } = arrayProxy;
const utils = {
info: GM?.info ?? GM_info,
debugging: IS_OPEN_DEBUG,
atob: atob.bind(ctx),
btoa: btoa.bind(ctx),
alert: alert.bind(ctx),
prompt: prompt.bind(ctx),
confirm: confirm.bind(ctx),
console: Object.assign(obj, ctx.console),
};
const enhanceHistory = type => {
const original = ctx.history[type];
const event = new Event(type);
return function () {
const fn = original.apply(this, arguments);
event.arguments = arguments;
ctx.dispatchEvent(event);
return fn;
};
};
ctx.history.pushState = enhanceHistory("pushState");
ctx.history.replaceState = enhanceHistory("replaceState");
Object.entries(arrayMethods).forEach(method => void defineMethod(...method));
SearchEngineAssistant(ctx, utils, customFns);
})(
typeof window !== "undefined" ? window : this,
function (global, secureVars, customFuntions) {
"use strict";
/* PERFECTLY COMPATIBLE FOR GREASEMONKEY, TAMPERMONKEY, VIOLENTMONKEY, USERSCRIPTS 2024-03-15 F9Y4NG */
const { atob, btoa, alert, prompt, confirm, console, debugging, info: GMinfo } = secureVars;
const { oT: getObjectType, aF: asArray, hP: hasOwnProperty, gS: localStorages } = customFuntions;
const GMversion = GMinfo.version ?? GMinfo.scriptHandlerVersion ?? "unknown";
const GMscriptHandler = GMinfo.scriptHandler;
const GMsetValue = gmSelector("setValue");
const GMgetValue = gmSelector("getValue");
const GMdeleteValue = gmSelector("deleteValue");
const GMlistValues = gmSelector("listValues");
const GMopenInTab = gmSelector("openInTab");
const GMregisterMenuCommand = gmSelector("registerMenuCommand");
const GMunregisterMenuCommand = gmSelector("unregisterMenuCommand");
const GMxmlhttpRequest = gmSelector("xmlhttpRequest");
const GMunsafeWindow = gmSelector("unsafeWindow");
const GMcontentMode = gmSelector("contentMode");
/* INITIALIZE_DEBUG_FUNCTIONS */
const IS_CHN = checkLocalChineseLanguage();
const IS_DEBUG = setDebuggerMode() || debugging;
const DEBUG = IS_DEBUG ? __console.bind(console, "log") : () => {};
const ERROR = IS_DEBUG ? __console.bind(console, "error") : () => {};
const COUNT = IS_DEBUG ? __console.bind(console, "count") : () => {};
/* INITIALIZE_COMMON_CONSTANTS */
const { pT: CUR_PROTOCOL, hN: CUR_HOST_NAME, pN: CUR_PATH_NAME, iT: CUR_WINDOW_TOP } = getLocationInfo();
const def = {
count: { clickTimer: 0, duplicate: 0 },
const: {
raf: Symbol(`פֿ${generateRandomString(8, "hex")}`),
caf: Symbol(`פֿ${generateRandomString(8, "hex")}`),
loading: generateRandomString(6, "char"),
cssAttrName: `gb-css-${generateRandomString(8, "hex")}`,
rndButtonID: generateRandomString(12, "char"),
rndclassName: `SC${generateRandomString(8, "digit")}`,
rndstyleName: `SS${generateRandomString(8, "digit")}`,
rndadvName: `SA${generateRandomString(8, "digit")}`,
leftButton: generateRandomString(6, "mix"),
rightButton: generateRandomString(6, "mix"),
scrollspan: generateRandomString(8, "char"),
scrollspan2: generateRandomString(8, "char"),
scrollbars: generateRandomString(8, "char"),
scrollbars2: generateRandomString(8, "char"),
searchbox: generateRandomString(7, "mix"),
},
var: {
disappear: "ͽoFgZM8trͼ",
translucent: "ͼn8IoLXdgͽ",
securityPolicy: false,
curVersion: getMetaValue("version") ?? GMinfo.script.version ?? "2024.10.05.0",
scriptName: getMetaValue(`name:${getLocalLanguages()}`) ?? decrypt("U2VhcmNoJTIwRW5naW5lJTIwQXNzaXN0YW50"),
},
url: {
yandexIcon: decrypt("aHR0cHMlM0ElMkYlMkZmYXZpY29uLnlhbmRleC5uZXQlMkZmYXZpY29uJTJGdjI="),
backupIcon: decrypt("aHR0cHMlM0ElMkYlMkZzMjEuYXgxeC5jb20lMkYyMDI0JTJGMDYlMkYzMCUyRnBrY1VWbWoucG5n"),
feedback: getMetaValue("supportURL") ?? GMinfo.script.supportURL ?? decrypt("aHR0cHMlM0ElMkYlMkZnaXRodWIuY29tJTJGRjl5NG5nJTJGR3JlYXN5Rm9yay1TY3JpcHRzJTJGaXNzdWVz"),
homepage: getMetaValue("homepageURL") ?? GMinfo.script.homepage ?? decrypt("aHR0cHMlM0ElMkYlMkZmOXk0bmcuZ2l0aHViLmlvJTJGR3JlYXN5Rm9yay1TY3JpcHRzJTJG"),
},
notice: {
rName: generateRandomString(8, "char"),
random: generateRandomString(5, "char"),
noticeX: generateRandomString(7, "char"),
appear: generateRandomString(6, "char"),
gberror: generateRandomString(6, "mix"),
linkerror: generateRandomString(7, "mix"),
item: generateRandomString(6, "mix"),
close: generateRandomString(6, "mix"),
center: generateRandomString(6, "mix"),
success: generateRandomString(7, "char"),
warning: generateRandomString(7, "char"),
info: generateRandomString(7, "char"),
error: generateRandomString(7, "char"),
checkbox: generateRandomString(6, "char"),
configuration: generateRandomString(7, "char"),
animated: generateRandomString(7, "char"),
stopUpdate: generateRandomString(6, "mix"),
searchButton: generateRandomString(6, "mix"),
favicon: generateRandomString(6, "mix"),
favicons: generateRandomString(6, "mix"),
searchList: generateRandomString(7, "mix"),
fieldset: generateRandomString(6, "char"),
legend: generateRandomString(6, "char"),
settingList: generateRandomString(7, "mix"),
readonly: generateRandomString(8, "mix"),
hk: generateRandomString(5, "mix"),
gj: generateRandomString(5, "mix"),
lw: generateRandomString(5, "mix"),
kh: generateRandomString(5, "mix"),
ar: generateRandomString(5, "mix"),
aa: generateRandomString(5, "mix"),
au: generateRandomString(5, "mix"),
grid: generateRandomString(7, "char"),
card: generateRandomString(7, "char"),
},
};
if (checkRedundantScript(GMunsafeWindow)) return;
/* INITIALIZE_SETTIMEOUT_AND_SETINTERVAL_FUNCTION_CLASSES */
class RAF {
constructor(context) {
if (RAF.instance) return RAF.instance;
this.context = context;
this._registerAnimationFrame(context);
this.timerMap = { timeout: {}, interval: {} };
this.setTimeout = this.setTimeout.bind(this);
this.setInterval = this.setInterval.bind(this);
this.clearTimeout = this.clearTimeout.bind(this);
this.clearInterval = this.clearInterval.bind(this);
RAF.instance = this;
}
_registerAnimationFrame(scope) {
const vendor = ["ms", "moz", "webkit", "o"].Find(vendor => scope[`${vendor}RequestAnimationFrame`]);
const raf = scope.requestAnimationFrame ?? scope[`${vendor}RequestAnimationFrame`];
const caf = scope.cancelAnimationFrame ?? (scope[`${vendor}CancelAnimationFrame`] || scope[`${vendor}CancelRequestAnimationFrame`]);
Object.assign(scope, { [def.const.raf]: raf, [def.const.caf]: caf });
}
_ticking(fn, type, interval = 0, ...args) {
let lastTime = performance.now();
const timerSymbol = Symbol(type);
const step = () => {
this._setTimerMap(timerSymbol, type, step);
if (interval < 16.7 || performance.now() - lastTime >= interval) {
if (typeof fn === "function") fn(...args);
if (type === "interval") lastTime = performance.now();
else this.clearTimeout(timerSymbol);
}
};
this._setTimerMap(timerSymbol, type, step);
return timerSymbol;
}
_setTimerMap(timerSymbol, type, step) {
this.timerMap[type][timerSymbol] = this.context[def.const.raf](step);
}
_clearTimerMap(timer, type) {
this.context[def.const.caf](this.timerMap[type][timer]);
delete this.timerMap[type][timer];
}
setTimeout(fn, interval, ...args) {
return this._ticking(fn, "timeout", interval, ...args);
}
clearTimeout(timer) {
this._clearTimerMap(timer, "timeout");
}
setInterval(fn, interval, ...args) {
return this._ticking(fn, "interval", interval, ...args);
}
clearInterval(timer) {
this._clearTimerMap(timer, "interval");
}
}
const raf = new RAF(global);
/* GLOBAL_GENERAL_FUNCTIONS */
function gmSelector(rec) {
const gmFunctions = {
setValue: typeof GM_setValue !== "undefined" ? GM_setValue : GM?.setValue ?? localStorages?.setItem.bind(localStorages),
getValue: typeof GM_getValue !== "undefined" ? GM_getValue : GM?.getValue ?? localStorages?.getItem.bind(localStorages),
deleteValue: typeof GM_deleteValue !== "undefined" ? GM_deleteValue : GM?.deleteValue ?? localStorages?.removeItem.bind(localStorages),
listValues: typeof GM_listValues !== "undefined" ? GM_listValues : GM?.listValues ?? (() => []),
openInTab: typeof GM_openInTab !== "undefined" ? GM_openInTab : GM?.openInTab ?? open.bind(global),
registerMenuCommand: typeof GM_registerMenuCommand !== "undefined" ? GM_registerMenuCommand : GM?.registerMenuCommand,
unregisterMenuCommand: typeof GM_unregisterMenuCommand !== "undefined" ? GM_unregisterMenuCommand : GM?.unregisterMenuCommand,
xmlhttpRequest: typeof GM_xmlhttpRequest !== "undefined" ? GM_xmlhttpRequest : GM?.xmlHttpRequest,
unsafeWindow: typeof unsafeWindow !== "undefined" ? unsafeWindow : global,
contentMode: GMinfo.injectInto === "content" || GMinfo.script["inject-into"] === "content" || ["dom", "js"].includes(GMinfo.sandboxMode),
};
return gmFunctions[rec] ?? __console("warn", `Grant 'GM.${rec}' is not available.`) ?? (() => {});
}
function __console(action, message = "", ...args) {
const consoleMethods = {
log: ["log", "%c\ud83d\udd33 %c", "display:inline-block", "font-family:ui-monospace,monospace"],
error: ["error", "%c\ud83d\udea9 ", "display:inline-block;font-family:ui-monospace,monospace"],
warn: ["warn", "%c\ud83d\udea9 ", "display:inline-block;font-family:ui-monospace,monospace"],
count: ["count", "\ud83d\udd33 "],
};
const [consoleMethod, _] = [consoleMethods[action], this ?? console];
if (!consoleMethod) return _.log(message, ...args);
const [method, prefix, ...surfix] = consoleMethod;
return _[method](prefix + message, ...surfix, ...args);
}
function checkLocalChineseLanguage() {
const lang = navigator.language || navigator.userLanguage || "en-US";
return lang.startsWith("zh");
}
function qS(expr, target = document) {
try {
if (/^#[\w:.-]+$/.test(expr)) return target.getElementById(expr.slice(1));
return target.querySelector(expr);
} catch (e) {
return null;
}
}
function qA(expr, target = document) {
try {
return asArray(target.querySelectorAll(expr));
} catch (e) {
return [];
}
}
function toString(value) {
if (typeof value === "symbol") return value.description;
return String(value);
}
function cE(nodeName, attributes = {}) {
const el = document.createElement(nodeName);
if (getObjectType(attributes) !== "[object Object]") return el;
for (const [key, value] of setIterator(attributes)) {
if (key === "class") Array.isArray(value) ? el.classList.add(...value) : el.classList.add(value);
else if (["innerHTML", "textContent"].includes(key)) el[key] = value;
else el.setAttribute(key, value);
}
return el;
}
function random(range, type = "round") {
return Math[type]((global.crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1)) * range);
}
function gCS(node, opt = null) {
if (node?.nodeType !== Node.ELEMENT_NODE) return new Proxy(Object.create(null), { get: () => NaN });
return global.getComputedStyle(node, opt);
}
function capitalize(string) {
string = String(string ?? "").toLowerCase();
return string.replace(/\b[a-z]|\s[a-z]/g, str => str.toUpperCase());
}
function encrypt(string, encode = true) {
if (typeof string !== "string") string = toString(string);
try {
const req = encode ? encodeURIComponent(string) : string;
return btoa(req);
} catch (e) {
return "";
}
}
function decrypt(string, decode = true) {
if (typeof string !== "string") return "";
try {
const rst = atob(string.replace(/[^A-Za-z0-9+/=]/g, ""));
return decode ? decodeURIComponent(rst) : rst;
} catch (e) {
return "";
}
}
function setIterator(collection) {
if (!collection) return [][Symbol.iterator]();
collection = typeof collection[Symbol.iterator] === "function" ? collection : typeof collection.length === "number" ? asArray(collection) : Object.entries(collection);
return collection[Symbol.iterator]();
}
function uniq(array) {
if (!Array.isArray(array)) return [];
return asArray(new Set(array)).filter(Boolean);
}
function generateRandomString(length, type) {
const characters = {
mix: "mYsTBgpkwNcGzFJdOMrt8n2jUC3fWRlKVA5y16oLxIXQE7Z9buvqie4PahH0SD",
char: "zkDcUGopOvHJLfIZdPqEeRmyCSNYwrgbsFQuBXxnVWiltjMhaATK",
hex: "a62f8bc07bd15c9ad3efe4",
digit: "3927154680",
};
const [prefix, chars] = ["UKZJHQTRCSBFAYDMEVPXNWG", characters[type]];
const randomString = asArray({ length }, () => chars[random(chars.length, "floor")]).join("");
return type === "mix" ? prefix[random(prefix.length, "floor")] + randomString.slice(1) : randomString;
}
function refresh() {
return sleep(5e2, { useCachedSetTimeout: true }).then(() => global.location.reload(true));
}
function escapeHTML(string) {
if (typeof string !== "string") return "";
const element = cE("gb-escape-html", { textContent: string });
return element.innerHTML;
}
function createTrustedTypePolicy() {
const defaultPolicy = { createHTML: string => string };
if (!global.trustedTypes?.createPolicy) return defaultPolicy;
const currentHostName = global.location.hostname;
const whitelist = [{ host: "bing.com", policy: "rwflyoutDefault" }];
const policyName = whitelist.Find(entry => currentHostName.endsWith(entry.host))?.policy ?? "default";
return global.trustedTypes.createPolicy(policyName, defaultPolicy);
}
function checkRedundantScript(global) {
const redundantScripts = global["gb-init-redundantcheck"];
const scriptRedundancyWarning = () => {
const scriptRedundanceText = `\ud83d\udea9 [Redundant Scripts]:\r\nFound redundant-installed scripts: ${def.var.scriptName}. please reload to troubleshoot the issue.`;
const troubleshoot = `\ufff8\ud83d\uded1 ${IS_CHN ? "发现冗余安装的脚本,点击排查!" : "Troubleshoot Redundant"}`;
CUR_WINDOW_TOP && GMregisterMenuCommand(troubleshoot, () => void (GMopenInTab(`${def.url.feedback}/117`, false) && refresh())) && __console("error", scriptRedundanceText);
return true;
};
if (redundantScripts === true) return scriptRedundancyWarning();
global["gb-init-redundantcheck"] = true;
if (GMcontentMode) {
const redundantScriptsInfo = document.documentElement.getAttribute("gb-init-rc");
if (redundantScriptsInfo === "true") return scriptRedundancyWarning();
}
if (Object.freeze(def.const)) document.documentElement.setAttribute("gb-init-rc", true);
}
async function getNavigatorInfo() {
const creditEngine = getRealBrowserEngine(global);
const userAgentData = await getUserAgentDataFromExtension(`${GMscriptHandler} ${GMversion}`);
return userAgentData ? getGlobalInfoFromUAD(userAgentData) : getGlobalInfoFromUA(navigator.userAgent);
function getGlobalInfoFromUAD(uad) {
const platform = getFullPlatformName(uad.platform);
const mapBrandPath = ({ brand: b, version: v }) => `${/Not[^a-z]*A[^a-z]*Brand/i.test(b) ? 9 : /^Chrom(?:e|ium)$/i.test(b) ? 5 : 1}${b}\r${v}`;
const [brand, brandVersion] = uad.brands?.map(mapBrandPath).sort()[0]?.slice(1).split("\r") ?? [];
const engineMap = { Chrome: "Blink", Chromium: "Blink", Firefox: "Gecko", Safari: "WebKit" };
const mapEnginePath = ({ brand, version }) => /^(Chrom(?:e|ium)|Firefox|Safari)$/i.test(brand) && `${brand}\r${version}`;
const [engine, engineVersion] = uad.brands?.map(mapEnginePath).filter(Boolean)[0]?.split("\r") ?? [brand, brandVersion];
const engineInfo = { engine: engineMap[capitalize(engine)] ?? getEngineFromUA(navigator.userAgent), engineVersion: parseFloat(engineVersion) || 99, creditEngine };
const browserInfo = { brand: (brand?.split(/\s/) ?? []).slice(-1)[0] ?? "Unknown", brandVersion: formatVersion(brandVersion), platform };
return { ...engineInfo, ...browserInfo, source: uad.voucher ? "ext" : "uad", voucher: uad.voucher ?? null };
}
function getGlobalInfoFromUA(ua) {
const checkString = (str, exp = "") => new RegExp(str, exp).test(ua);
const getVersion = (str, offset) => checkString(str) && ua.slice(ua.indexOf(str) + offset).match(/\d+(\.\d+)*/)?.[0];
const { brand, brandVersion, engine, engineVersion } = getBrowserInfoFromUA(ua, checkString, getVersion);
const platform = getOSInfoFromUA(checkString);
return { engine, engineVersion, creditEngine, brand, brandVersion, platform, source: "ua", voucher: null };
}
async function getUserAgentDataFromExtension(voucher) {
const getVMUserAgentData = async uad => {
if (!uad) return null;
const { brand, version, browserName, browserVersion, os, arch } = uad;
const [bitness, architecture] = [arch?.split("-")[1], arch?.split("-")[0]];
let brands = [
{ brand: capitalize(brand || "Not)A;Brand"), version: brand ? version : "99" },
{ brand: capitalize(browserName), version: browserVersion },
];
if (GMinfo.userAgentData?.brands?.[0]) {
try {
return { ...(await getUserAgentDataHighEntropyValues(GMinfo.userAgentData)), voucher };
} catch (e) {
brands = [...GMinfo.userAgentData.brands, ...brands];
}
}
return { bitness, architecture, brands, platform: capitalize(os), voucher };
};
const vmuad = voucher.startsWith("Violentmonkey") && GMinfo.platform ? await getVMUserAgentData(GMinfo.platform) : null;
const tmuad = voucher.startsWith("Tampermonkey") && GMinfo.userAgentData ? { ...GMinfo.userAgentData, voucher } : null;
const uad = navigator.userAgentData?.brands?.[0] ? await getUserAgentDataHighEntropyValues(navigator.userAgentData) : null;
return vmuad ?? tmuad ?? uad;
}
async function getUserAgentDataHighEntropyValues(uad) {
return await uad.getHighEntropyValues(["bitness", "architecture", "fullVersionList"]).then(rst => {
rst.brands = rst.fullVersionList;
delete rst.fullVersionList;
return rst;
});
}
function getBrowserInfoFromUA(ua, checkString, getVersion) {
const engine = getEngineFromUA(ua);
const brandMap = {
OPR: { brand: "Opera", engine: "Blink", as: "Chrome" },
YaBrowser: { brand: "Yandex", engine: "Blink", as: "Chrome" },
Edg: { brand: "Edge", engine: "Blink", as: "Chrome" },
Chromium: { brand: "Chromium", engine: "Blink" },
Chrome: { brand: "Chrome", engine: "Blink" },
LibreWolf: { brand: "LibreWolf", engine: "Gecko", as: "Firefox" },
SeaMonkey: { brand: "SeaMonkey", engine: "Gecko", as: "Firefox" },
PaleMoon: { brand: "PaleMoon", engine: "Gecko", as: "Firefox" },
Waterfox: { brand: "Waterfox", engine: "Gecko", as: "Firefox" },
Firefox: { brand: "Firefox", engine: "Gecko" },
Konqueror: { brand: "Konqueror", engine: "webkit" },
Kindle: { brand: "Kindle", engine: "WebKit", as: "Version" },
Safari: { brand: "Safari", engine: "WebKit", as: "Version", verset: ["Version"] },
Trident: { brand: "IE", engine: "Trident", verset: ["MSIE", "rv"] },
Presto: { brand: "Opera", engine: "Presto" },
};
for (const [key, { brand, engine, verset, as }] of setIterator(brandMap)) {
if (!checkString(key)) continue;
const enVersionKey = as || key;
const engineVersion = parseFloat(getVersion(enVersionKey, enVersionKey.length + 1) || 99);
const versionKey = verset?.Find(k => checkString(k)) || key;
let brandVersion = getVersion(versionKey, versionKey.length + 1);
if (!brandVersion) continue;
return { brand, brandVersion: formatVersion(brandVersion), engine, engineVersion };
}
const { b: brand, bv: brandVersion, ev: engineVersion } = getUnregisteredBrandAndVersionFromUA(ua);
return { brand, brandVersion, engine, engineVersion };
}
function formatVersion(version) {
if (!version) return "0.0.0.0";
const numbers = version.split(".").map(num => parseInt(num) || 0);
while (numbers.length < 4) numbers.push(0);
return numbers.join(".");
}
function getFullPlatformName(platform) {
if (!platform) return "Unknown";
const os = capitalize(platform);
return /^(Like Mac|Ios)$/.test(os) ? "iOS" : os === "Cros" ? "Chrome OS" : os.startsWith("Win") ? "Windows" : os.startsWith("Mac") ? "MacOS" : os === "X11" ? "Linux" : os;
}
function getRealBrowserEngine(w) {
return w.GestureEvent ? "WebKit" : w.scrollByLines || w.getDefaultComputedStyle ? "Gecko" : w.webkitRequestFileSystem || w.queryLocalFonts ? "Blink" : "Unknown";
}
function getEngineFromUA(ua) {
return /Gecko\/|Firefox\/|FxiOS/.test(ua) ? "Gecko" : /Chrom(?:e|ium)\/|CriOS/.test(ua) ? "Blink" : /AppleWebKit\/|Version\//.test(ua) ? "WebKit" : "Unknown";
}
function getUnregisteredBrandAndVersionFromUA(ua) {
const [nameOffset, verOffset] = [ua.lastIndexOf(" ") + 1, ua.lastIndexOf("/")];
if (nameOffset === 0 || verOffset === -1 || verOffset < nameOffset) return { b: "Unknown", bv: "0.0.0.0", ev: 99 };
const brand = ua.slice(nameOffset, verOffset).trim();
const brandVersion = formatVersion(ua.slice(verOffset + 1).match(/\d*\.?\d+/)?.[0]);
const engineVersion = parseFloat(ua.match(/(Chrom(?:e|ium)|Firefox|Version)\/(\d+(?:\.\d+)*)/i)?.[2] || brandVersion || 99);
const validVersion = (!/version|\/|\(|\)|;/i.test(brand) && brandVersion) || "0.0.0.0";
return { b: brand, bv: validVersion, ev: engineVersion };
}
function getOSInfoFromUA(checkString) {
const platforms = ["like Mac", "Mac", "Android", "Debian", "Ubuntu", "Linux", "Win", "CrOS", "X11"];
const platform = platforms.Find(p => checkString(p, "i")) || "Unknown";
return getFullPlatformName(platform);
}
}
function getLocationInfo() {
const { host: h, hostname: hN, pathname: pN, protocol: pT } = global.location;
const iT = global.self === global.top;
return { h, hN, pN, pT, iT };
}
function getMetaValue(str) {
const queryReg = new RegExp(`//\\s+@${str}\\s+(.+)`);
const metaValue = (GMinfo.scriptMetaStr || GMinfo.scriptSource)?.match(queryReg);
return metaValue?.[1];
}
function getLocalLanguages(lang = navigator.language) {
const languages = { "zh-CN": true, "zh-TW": true, en: true, ja: true, ru: true };
return languages[lang] ? lang : lang.startsWith("zh") ? "zh-CN" : "en";
}
function setDebuggerMode() {
const key = decrypt("\u0052\u006a\u006c\u0035\u004e\u0047\u0035\u006e");
const value = new URLSearchParams(global.location.search).get("whoami");
return Object.is(key, value);
}
function sleep(delay, { useCachedSetTimeout } = {}) {
const timeoutFunction = useCachedSetTimeout ? setTimeout : raf.setTimeout;
const sleepPromise = new Promise(resolve => {
timeoutFunction(resolve, delay);
});
const promiseFunction = value => sleepPromise.then(() => value);
promiseFunction.then = sleepPromise.then.bind(sleepPromise);
promiseFunction.catch = sleepPromise.catch.bind(sleepPromise);
return promiseFunction;
}
function deBounce({ fn, timer, delay, immed = false, once = false } = {}) {
if (typeof fn !== "function" || !timer) return () => {};
return function (...args) {
const [name, context] = [Symbol.for(toString(timer)), this];
if (immed === true && typeof def.count[name] === "undefined") {
fn.apply(context, args);
if (once === true) return (def.count[name] = true);
} else if (def.count[name]) {
if (def.count[name] === true) return true;
raf.clearTimeout(def.count[name]);
}
def.count[name] = raf.setTimeout(() => {
fn.apply(context, args);
if (once === true) return (def.count[name] = true);
delete def.count[name];
}, Number(delay) || 0);
};
}
function safeRemoveNode(expression, scope) {
if (!expression) return false;
const pendingNodes = Array.isArray(expression) ? expression : typeof expression === "string" ? qA(expression, scope) : expression?.nodeType ? [expression] : [];
return pendingNodes.every(el => el.remove() || el.parentNode === null);
}
function createNoticeHTML(html) {
return `<div class="${def.notice.rName}"><dl>${html}</dl></div>`;
}
void (async function (tTP) {
const [CONFIGURE, VERSION, AUTOCHECK, RESULTFILTER, REMOTEICONS] = ["_configures_", "_version_", "_autoupdate_", "_resultFilter_", "_remoteicons_"];
const { engine, creditEngine, brand, voucher } = await getNavigatorInfo();
const [IS_REAL_BLINK, IS_REAL_GECKO, IS_REAL_WEBKIT] = ["Blink", "Gecko", "WebKit"].map(cE => cE === creditEngine);
const IS_CHEAT_UA = voucher === null && (engine !== creditEngine || checkBlinkCheatingUA(navigator.userAgentData));
const IS_GREASEMONKEY = ["Greasemonkey", "Userscripts"].includes(GMscriptHandler);
const cache = {
value: (data, eT = 6048e5) => ({ data, expired: Date.now() + eT }),
set: (key, ...options) => {
const cacheValue = cache.value(...options);
GMsetValue(key, encrypt(JSON.stringify(cacheValue)));
},
get: async key => {
try {
const encryptedValue = await GMgetValue(key);
if (!encryptedValue) return;
const current = Date.now();
const { data, expired } = JSON.parse(decrypt(encryptedValue));
if (data && expired > current) return data;
else cache.remove(key);
} catch (e) {
cache.remove(key);
}
},
remove: key => GMdeleteValue(key),
};
class NoticeX {
constructor(options = {}) {
this.defaultOptions = {
title: "",
text: "",
type: def.notice.success,
position: "bottomRight",
newestOnTop: false,
timeout: 2e3,
progressBar: true,
closeWith: ["button"],
animation: { open: `${def.notice.animated} ${def.notice.random}_fadeIn`, close: `${def.notice.animated} ${def.notice.random}_fadeOut` },
width: 400,
scroll: { maxHeight: 400, showOnHover: false },
callbacks: { beforeShow: [], onShow: [], afterShow: [], beforeClose: [], onClose: [], afterClose: [], onClick: [], onHover: [] },
};
this.options = { ...this.defaultOptions, ...options };
this._registerCallbacks();
}
static close(item) {
if (!item) return true;
item.classList.add(def.notice.animated, `${def.notice.random}_fadeOut`);
const closetNode = item.closest(`.${def.notice.noticeX}`);
const position = closetNode?.className.match(/\b(\w+-\w+)\b/)?.[1] || `${def.notice.noticeX}-topRight`;
return sleep(3e2)
.then(() => safeRemoveNode(item))
.then(() => qA(`.${position} .${def.notice.item}`).length === 0 && safeRemoveNode(`.${position}`));
}
show() {
this._createContainer();
const noticeX = this._appendNoticeX(this._createHeader(), this._createBody(), this._createProgressBar());
return noticeX;
}
_createContainer() {
const position = `${def.notice.noticeX}-${this.options.position}`;
if (qS(`gb-notice.${position}`)) return;
const container = cE("gb-notice", { class: [def.notice.noticeX, position, def.notice.appear] });
document.documentElement.appendChild(container);
}
_createHeader() {
if (!this.options.title && !this.options.closeWith.includes("button")) return null;
const header = cE("div", { class: `${def.notice.noticeX}-heading` });
if (this.options.title) header.innerHTML += tTP.createHTML(`<span class="${def.notice.noticeX}-heading-title" title="${this.options.title}">${this.options.title}</span>`);
if (this.options.closeWith.includes("button")) {
const close = cE("div", { class: def.notice.close, innerHTML: tTP.createHTML("×") });
header.appendChild(close);
}
return header;
}
_createBody() {
const body = cE("div", { class: `${def.notice.noticeX}-body` });
const content = cE("div", { class: `${def.notice.noticeX}-content`, innerHTML: tTP.createHTML(this.options.text) });
body.appendChild(content);
if (this.options.scroll?.maxHeight) {
body.style.overflowY = "auto";
body.style.maxHeight = `min(calc(92vh - 50px), ${this.options.scroll.maxHeight}px)`;
if (this.options.scroll?.showOnHover) body.style.visibility = "hidden";
}
return body;
}
_createProgressBar() {
const progressBar = cE("div", { class: `${def.notice.noticeX}-progressbar` });
const bar = cE("div", { class: `${def.notice.noticeX}-bar` });
progressBar.appendChild(bar);
if (this.options.progressBar && typeof this.options.timeout === "number") {
progressBar.style.animation = `${def.notice.noticeX}-progress ${this.options.timeout / 1e3}s linear forwards`;
sleep(this.options.timeout, { useCachedSetTimeout: true }).then(() => {
const item = progressBar.closest(`div.${def.notice.item}`);
if (item) this._closeWithAnimation(item);
});
}
return progressBar;
}
_appendNoticeX(header, body, progressBar) {
const targetClass = `.${def.notice.noticeX}-${this.options.position}`;
const noticeItem = cE("div", { class: [def.notice.item, this.options.type] });
if (this.options.width && Number.isInteger(this.options.width)) noticeItem.style.width = `${this.options.width}px`;
[header, body, progressBar].forEach(el => el && noticeItem.appendChild(el));
if (["top", "bottom"].includes(this.options.position)) qS(targetClass).textContent = "";
if (this.options?.animation?.open) noticeItem.className += ` ${this.options.animation.open}`;
this._executeCallbacks("beforeShow");
this._addListeners(noticeItem);
const target = qS(targetClass);
this._executeCallbacks("onShow");
this.options.newestOnTop && target ? target.insertAdjacentElement("afterbegin", noticeItem) : target.appendChild(noticeItem);
this._executeCallbacks("afterShow");
return noticeItem;
}
_closeWithAnimation(item) {
if (this.options.animation?.close) {
item.className += ` ${this.options.animation.close}`;
sleep(5e2).then(() => this._closeItem(item));
} else this._closeItem(item);
}
_addListeners(item) {
const closeBtn = qS(`.${def.notice.close}`, item);
const handleClick = () => this._closeItem(item);
if (this.options.closeWith.includes("button")) closeBtn?.addEventListener("click", handleClick);
if (this.options.closeWith.includes("click")) {
item.style.cursor = "pointer";
item.addEventListener("click", e => {
if (e.target.className !== def.notice.close) {
this._executeCallbacks("onClick");
handleClick();
}
});
} else item.addEventListener("click", e => e.target.className !== def.notice.close && this._executeCallbacks("onClick"));
item.addEventListener("mouseover", () => this._executeCallbacks("onHover"));
}
_closeItem(item) {
const closetNode = item.closest(`.${def.notice.noticeX}`);
const position = closetNode?.className.match(/\b(\w+-\w+)\b/)?.[1] || `${def.notice.noticeX}-bottomRight`;
this._executeCallbacks("beforeClose");
sleep(3e2)
.then(() => this._executeCallbacks("onClose"))
.then(() => safeRemoveNode(item))
.then(() => qA(`.${position} .${def.notice.item}`).length === 0 && safeRemoveNode(`.${position}`))
.then(() => this._executeCallbacks("afterClose"));
}
_executeCallbacks(eventName) {
this.options.callbacks[eventName]?.forEach(cb => cb?.call(this));
}
_registerCallbacks() {
Object.keys(this.options.callbacks).forEach(eventName => {
const cb = this.options.callbacks[eventName];
if (typeof cb === "function") this._on(eventName, cb);
});
}
_on(eventName, cb = () => {}) {
if (typeof cb === "function" && this.options.callbacks[eventName]) this.options.callbacks[eventName].push(cb);
return this;
}
}
function checkBlinkCheatingUA(uad) {