-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathgm_api.ts
More file actions
1626 lines (1500 loc) · 54.5 KB
/
gm_api.ts
File metadata and controls
1626 lines (1500 loc) · 54.5 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
import { customClone, Native } from "../global";
import type { Message, MessageConnect } from "@Packages/message/types";
import type { CustomEventMessage } from "@Packages/message/custom_event_message";
import type {
GMRegisterMenuCommandParam,
GMUnRegisterMenuCommandParam,
NotificationMessageOption,
ScriptMenuItemOption,
SWScriptMenuItemOption,
TScriptMenuItemID,
TScriptMenuItemKey,
MessageRequest,
} from "@App/app/service/service_worker/types";
import { base64ToBlob, randNum, randomMessageFlag, strToBase64 } from "@App/pkg/utils/utils";
import LoggerCore from "@App/app/logger/core";
import EventEmitter from "eventemitter3";
import GMContext from "./gm_context";
import { type ScriptRunResource } from "@App/app/repo/scripts";
import type { ValueUpdateDataEncoded } from "../types";
import { connect, sendMessage } from "@Packages/message/client";
import { getStorageName } from "@App/pkg/utils/utils";
import { ListenerManager } from "../listener_manager";
import { decodeRValue, encodeRValue, type REncoded } from "@App/pkg/utils/message_value";
import { type TGMKeyValue } from "@App/app/repo/value";
import type { ContextType } from "./gm_xhr";
import { convObjectToURL, GM_xmlhttpRequest, toBlobURL, urlToDocumentInContentPage } from "./gm_xhr";
import { ScriptEnvTag } from "@Packages/message/consts";
import { stackAsyncTask } from "@App/pkg/utils/async_queue";
// 内部函数呼叫定义
export interface IGM_Base {
sendMessage(api: string, params: any[]): Promise<any>;
connect(api: string, params: any[]): Promise<any>;
valueUpdate(data: ValueUpdateDataEncoded): void;
emitEvent(event: string, eventId: string, data: any): void;
}
export interface GMRequestHandle {
/** Abort the ongoing request */
abort: () => void;
}
const integrity = {}; // 仅防止非法实例化
let valChangeCounterId = 0;
let valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`;
const valueChangePromiseMap = new Map<string, any>();
const execEnvInit = (execEnv: GMApi) => {
if (!execEnv.contentEnvKey) {
execEnv.contentEnvKey = randomMessageFlag(); // 不重复识别字串。用于区分 mainframe subframe 等执行环境
execEnv.menuKeyRegistered = new Set();
execEnv.menuIdCounter = 0;
execEnv.regMenuCounter = 0;
}
};
// GM_Base 定义内部用变量和函数。均使用@protected
// 暂不考虑 Object.getOwnPropertyNames(GM_Base.prototype) 和 ts-morph 脚本生成
class GM_Base implements IGM_Base {
@GMContext.protected()
protected runFlag!: string;
@GMContext.protected()
protected prefix!: string;
// Extension Context 无效时释放 scriptRes
@GMContext.protected()
protected message?: Message | null;
@GMContext.protected()
protected contentMsg!: Message;
// Extension Context 无效时释放 scriptRes
@GMContext.protected()
protected scriptRes?: ScriptRunResource | null;
// Extension Context 无效时释放 valueChangeListener
@GMContext.protected()
protected valueChangeListener?: ListenerManager<GMTypes.ValueChangeListener>;
// Extension Context 无效时释放 EE
@GMContext.protected()
protected EE?: EventEmitter | null;
@GMContext.protected()
public context!: any;
@GMContext.protected()
public grantSet!: any;
@GMContext.protected()
public eventId!: number;
@GMContext.protected()
protected loadScriptResolve: (() => void) | undefined;
@GMContext.protected()
protected loadScriptPromise: Promise<void> | undefined;
constructor(options: any = null, obj: any = null) {
if (obj !== integrity) throw new TypeError("Illegal invocation");
Object.assign(this, options);
}
@GMContext.protected()
static createGMBase(options: { [key: string]: any }) {
return new GM_Base(options, integrity) as GM_Base & { [key: string]: any };
}
@GMContext.protected()
public isInvalidContext!: () => boolean;
@GMContext.protected()
public setInvalidContext!: () => void;
// 单次回调使用
@GMContext.protected()
public async sendMessage(api: string, params: any[]) {
if (!this.message || !this.scriptRes) return;
if (this.loadScriptPromise) {
await this.loadScriptPromise;
}
let ret;
try {
ret = await sendMessage(this.message, `${this.prefix}/runtime/gmApi`, {
uuid: this.scriptRes.uuid,
api,
params,
runFlag: this.runFlag,
} as MessageRequest);
} catch (e: any) {
if (`${e?.message || e}`.includes("Extension context invalidated.")) {
this.setInvalidContext(); // 之后不再进行 sendMessage 跟 EE操作
console.error(e);
} else {
throw e;
}
}
return ret;
}
// 长连接使用,connect只用于接受消息,不发送消息
@GMContext.protected()
public connect(api: string, params: any[]) {
if (!this.message || !this.scriptRes) return new Promise<MessageConnect>(() => {});
return connect(this.message, `${this.prefix}/runtime/gmApi`, {
uuid: this.scriptRes.uuid,
api,
params,
runFlag: this.runFlag,
} as MessageRequest);
}
@GMContext.protected()
public valueUpdate(data: ValueUpdateDataEncoded) {
if (!this.scriptRes || !this.valueChangeListener) return;
const scriptRes = this.scriptRes;
const { id, uuid, entries, storageName, sender, valueUpdated } = data;
if (uuid === scriptRes.uuid || storageName === getStorageName(scriptRes)) {
const valueStore = scriptRes.value;
const remote = sender.runFlag !== this.runFlag;
if (!remote && id) {
const fn = valueChangePromiseMap.get(id);
if (fn) {
valueChangePromiseMap.delete(id);
fn();
}
}
if (valueUpdated) {
const valueChanges = entries;
for (const [key, rTyped1, rTyped2] of valueChanges) {
const value = decodeRValue(rTyped1);
const oldValue = decodeRValue(rTyped2);
// 触发,并更新值
if (value === undefined) {
if (valueStore[key] !== undefined) {
delete valueStore[key];
}
} else {
valueStore[key] = value;
}
this.valueChangeListener.execute(key, oldValue, value, remote, sender.tabId);
}
}
}
}
@GMContext.protected()
emitEvent(event: string, eventId: string, data: any) {
if (!this.EE) return;
this.EE.emit(`${event}:${eventId}`, data);
}
}
// GMApi 定义 外部用API函数。不使用@protected
export default class GMApi extends GM_Base {
/**
* <tag, notificationId>
*/
notificationTagMap?: Map<string, string>;
constructor(
public prefix: string,
public message: Message,
public contentMsg: Message,
public scriptRes: ScriptRunResource
) {
// testing only 仅供测试用
const valueChangeListener = new ListenerManager<GMTypes.ValueChangeListener>();
const EE = new EventEmitter<string, any>();
let invalid = false;
super(
{
prefix,
message,
scriptRes,
valueChangeListener,
EE,
notificationTagMap: new Map(),
eventId: 0,
setInvalidContext() {
if (invalid) return;
invalid = true;
this.valueChangeListener.clear();
this.EE.removeAllListeners();
// 释放记忆
this.message = null;
this.scriptRes = null;
this.valueChangeListener = null;
this.EE = null;
},
isInvalidContext() {
return invalid;
},
},
integrity
);
}
static _GM_getValue(a: GMApi, key: string, defaultValue?: any) {
if (!a.scriptRes) return undefined;
const ret = a.scriptRes.value[key];
if (ret !== undefined) {
if (ret && typeof ret === "object") {
return customClone(ret)!;
}
return ret;
}
return defaultValue;
}
// 获取脚本的值,可以通过@storageName让多个脚本共享一个储存空间
@GMContext.API()
public GM_getValue(key: string, defaultValue?: any) {
return _GM_getValue(this, key, defaultValue);
}
@GMContext.API()
public "GM.getValue"(key: string, defaultValue?: any): Promise<any> {
// 兼容GM.getValue
return new Promise((resolve) => {
const ret = _GM_getValue(this, key, defaultValue);
resolve(ret);
});
}
static _GM_setValue(a: GMApi, promise: any, key: string, value: any) {
if (!a.scriptRes) return;
if (valChangeCounterId > 1e8) {
// 防止 valChangeCounterId 过大导致无法正常工作
valChangeCounterId = 0;
valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`;
}
const id = `${valChangeRandomId}::${++valChangeCounterId}`;
if (promise) {
valueChangePromiseMap.set(id, promise);
}
if (value === undefined) {
delete a.scriptRes.value[key];
a.sendMessage("GM_setValue", [id, key]);
} else {
// 对object的value进行一次转化
if (value && typeof value === "object") {
value = customClone(value);
}
// customClone 可能返回 undefined
a.scriptRes.value[key] = value;
if (value === undefined) {
a.sendMessage("GM_setValue", [id, key]);
} else {
a.sendMessage("GM_setValue", [id, key, value]);
}
}
return id;
}
static _GM_setValues(a: GMApi, promise: any, values: TGMKeyValue) {
if (!a.scriptRes) return;
if (valChangeCounterId > 1e8) {
// 防止 valChangeCounterId 过大导致无法正常工作
valChangeCounterId = 0;
valChangeRandomId = `${randNum(8e11, 2e12).toString(36)}`;
}
const id = `${valChangeRandomId}::${++valChangeCounterId}`;
if (promise) {
valueChangePromiseMap.set(id, promise);
}
const valueStore = a.scriptRes.value;
const keyValuePairs = [] as [string, REncoded<unknown>][];
for (const [key, value] of Object.entries(values)) {
let value_ = value;
if (value_ === undefined) {
if (valueStore[key]) delete valueStore[key];
} else {
// 对object的value进行一次转化
if (value_ && typeof value_ === "object") {
value_ = customClone(value_);
}
// customClone 可能返回 undefined
valueStore[key] = value_;
}
// 避免undefined 等空值流失,先进行映射处理
keyValuePairs.push([key, encodeRValue(value_)]);
}
a.sendMessage("GM_setValues", [id, keyValuePairs]);
return id;
}
@GMContext.API()
public GM_setValue(key: string, value: any) {
_GM_setValue(this, null, key, value);
}
@GMContext.API()
public "GM.setValue"(key: string, value: any): Promise<void> {
// Asynchronous wrapper for GM_setValue to support GM.setValue
return new Promise((resolve) => {
_GM_setValue(this, resolve, key, value);
});
}
@GMContext.API()
public GM_deleteValue(key: string): void {
_GM_setValue(this, null, key, undefined);
}
@GMContext.API()
public "GM.deleteValue"(key: string): Promise<void> {
// Asynchronous wrapper for GM_deleteValue to support GM.deleteValue
return new Promise((resolve) => {
_GM_setValue(this, resolve, key, undefined);
});
}
@GMContext.API()
public GM_listValues(): string[] {
if (!this.scriptRes) return [];
const keys = Object.keys(this.scriptRes.value);
return keys;
}
@GMContext.API()
public "GM.listValues"(): Promise<string[]> {
// Asynchronous wrapper for GM_listValues to support GM.listValues
return new Promise((resolve) => {
if (!this.scriptRes) return resolve([]);
const keys = Object.keys(this.scriptRes.value);
resolve(keys);
});
}
@GMContext.API()
public GM_setValues(values: TGMKeyValue) {
if (!values || typeof values !== "object") {
throw new Error("GM_setValues: values must be an object");
}
_GM_setValues(this, null, values);
}
@GMContext.API()
public GM_getValues(keysOrDefaults: TGMKeyValue | string[] | null | undefined) {
if (!this.scriptRes) return {};
if (!keysOrDefaults) {
// Returns all values
return customClone(this.scriptRes.value)!;
}
const result: TGMKeyValue = {};
if (Array.isArray(keysOrDefaults)) {
// 键名数组
// Handle array of keys (e.g., ['foo', 'bar'])
for (let index = 0; index < keysOrDefaults.length; index++) {
const key = keysOrDefaults[index];
if (key in this.scriptRes.value) {
// 对object的value进行一次转化
let value = this.scriptRes.value[key];
if (value && typeof value === "object") {
value = customClone(value)!;
}
result[key] = value;
}
}
} else {
// 对象 键: 默认值
// Handle object with default values (e.g., { foo: 1, bar: 2, baz: 3 })
for (const key of Object.keys(keysOrDefaults)) {
const defaultValue = keysOrDefaults[key];
result[key] = _GM_getValue(this, key, defaultValue);
}
}
return result;
}
// Asynchronous wrapper for GM.getValues
@GMContext.API({ depend: ["GM_getValues"] })
public "GM.getValues"(keysOrDefaults: TGMKeyValue | string[] | null | undefined): Promise<TGMKeyValue> {
if (!this.scriptRes) return new Promise<TGMKeyValue>(() => {});
return new Promise((resolve) => {
const ret = this.GM_getValues(keysOrDefaults);
resolve(ret);
});
}
@GMContext.API()
public "GM.setValues"(values: { [key: string]: any }): Promise<void> {
if (!this.scriptRes) return new Promise<void>(() => {});
return new Promise((resolve) => {
if (!values || typeof values !== "object") {
throw new Error("GM.setValues: values must be an object");
}
_GM_setValues(this, resolve, values);
});
}
@GMContext.API()
public GM_deleteValues(keys: string[]) {
if (!this.scriptRes) return;
if (!Array.isArray(keys)) {
console.warn("GM_deleteValues: keys must be string[]");
return;
}
const req = {} as Record<string, undefined>;
for (const key of keys) {
req[key] = undefined;
}
_GM_setValues(this, null, req);
}
// Asynchronous wrapper for GM.deleteValues
@GMContext.API()
public "GM.deleteValues"(keys: string[]): Promise<void> {
if (!this.scriptRes) return new Promise<void>(() => {});
return new Promise((resolve) => {
if (!Array.isArray(keys)) {
throw new Error("GM.deleteValues: keys must be string[]");
} else {
const req = {} as Record<string, undefined>;
for (const key of keys) {
req[key] = undefined;
}
_GM_setValues(this, resolve, req);
}
});
}
@GMContext.API()
public GM_addValueChangeListener(name: string, listener: GMTypes.ValueChangeListener): number {
if (!this.valueChangeListener) return 0;
return this.valueChangeListener.add(name, listener);
}
@GMContext.API({ depend: ["GM_addValueChangeListener"] })
public "GM.addValueChangeListener"(name: string, listener: GMTypes.ValueChangeListener): Promise<number> {
return new Promise<number>((resolve) => {
const ret = this.GM_addValueChangeListener(name, listener);
resolve(ret);
});
}
@GMContext.API()
public GM_removeValueChangeListener(listenerId: number): void {
if (!this.valueChangeListener) return;
this.valueChangeListener.remove(listenerId);
}
@GMContext.API({ depend: ["GM_removeValueChangeListener"] })
public "GM.removeValueChangeListener"(listenerId: number): Promise<void> {
return new Promise<void>((resolve) => {
this.GM_removeValueChangeListener(listenerId);
resolve();
});
}
@GMContext.API()
public GM_log(message: string, level: GMTypes.LoggerLevel = "info", ...labels: GMTypes.LoggerLabel[]): void {
if (this.isInvalidContext()) return;
if (typeof message !== "string") {
message = Native.jsonStringify(message);
}
this.sendMessage("GM_log", [message, level, labels]);
}
@GMContext.API({ depend: ["GM_log"] })
public "GM.log"(
message: string,
level: GMTypes.LoggerLevel = "info",
...labels: GMTypes.LoggerLabel[]
): Promise<void> {
return new Promise<void>((resolve) => {
this.GM_log(message, level, ...labels);
resolve();
});
}
@GMContext.API()
public CAT_createBlobUrl(blob: Blob): Promise<string> {
return Promise.resolve(toBlobURL(this, blob));
}
// 辅助GM_xml获取blob数据
@GMContext.API()
public CAT_fetchBlob(url: string): Promise<Blob> {
return this.sendMessage("CAT_fetchBlob", [url]);
}
@GMContext.API()
public async CAT_fetchDocument(url: string): Promise<Document | undefined> {
// 上下文已失效时直接返回,避免访问已释放的 message 造成异常
if (this.isInvalidContext()) return undefined;
const message = this.message as CustomEventMessage | null;
const isContentEnv = !!message && message.envTag === ScriptEnvTag.content;
return urlToDocumentInContentPage(this, url, isContentEnv);
}
static _GM_cookie(
a: IGM_Base,
action: string,
details: GMTypes.CookieDetails,
done: (cookie: GMTypes.Cookie[] | any, error: any | undefined) => void
) {
// 如果url和域名都没有,自动填充当前url
if (!details.url && !details.domain) {
details.url = window.location.href;
}
// 如果是set、delete操作,自动填充当前url
if (action === "set" || action === "delete") {
if (!details.url) {
details.url = window.location.href;
}
}
a.sendMessage("GM_cookie", [action, details])
.then((resp: any) => {
done && done(resp, undefined);
})
.catch((err) => {
done && done(undefined, err);
});
}
@GMContext.API()
public "GM.cookie"(action: string, details: GMTypes.CookieDetails) {
return new Promise((resolve, reject) => {
_GM_cookie(this, action, details, (cookie, error) => {
error ? reject(error) : resolve(cookie);
});
});
}
@GMContext.API({ follow: "GM.cookie" })
public "GM.cookie.set"(details: GMTypes.CookieDetails) {
return new Promise((resolve, reject) => {
_GM_cookie(this, "set", details, (cookie, error) => {
error ? reject(error) : resolve(cookie);
});
});
}
@GMContext.API({ follow: "GM.cookie" })
public "GM.cookie.list"(details: GMTypes.CookieDetails) {
return new Promise((resolve, reject) => {
_GM_cookie(this, "list", details, (cookie, error) => {
error ? reject(error) : resolve(cookie);
});
});
}
@GMContext.API({ follow: "GM.cookie" })
public "GM.cookie.delete"(details: GMTypes.CookieDetails) {
return new Promise((resolve, reject) => {
_GM_cookie(this, "delete", details, (cookie, error) => {
error ? reject(error) : resolve(cookie);
});
});
}
@GMContext.API({ follow: "GM_cookie" })
public "GM_cookie.set"(
details: GMTypes.CookieDetails,
done: (cookie: GMTypes.Cookie[] | any, error: any | undefined) => void
) {
_GM_cookie(this, "set", details, done);
}
@GMContext.API({ follow: "GM_cookie" })
public "GM_cookie.list"(
details: GMTypes.CookieDetails,
done: (cookie: GMTypes.Cookie[] | any, error: any | undefined) => void
) {
_GM_cookie(this, "list", details, done);
}
@GMContext.API({ follow: "GM_cookie" })
public "GM_cookie.delete"(
details: GMTypes.CookieDetails,
done: (cookie: GMTypes.Cookie[] | any, error: any | undefined) => void
) {
_GM_cookie(this, "delete", details, done);
}
@GMContext.API()
public GM_cookie(
action: string,
details: GMTypes.CookieDetails,
done: (cookie: GMTypes.Cookie[] | any, error: any | undefined) => void
) {
_GM_cookie(this, action, details, done);
}
// 已注册的「菜单唯一键」集合,用于去重与解除绑定。
// 唯一键格式:{contentEnvKey}.t{注册ID},由 execEnvInit() 建立/维护。
menuKeyRegistered: Set<string> | undefined;
// 自动产生的菜单 ID 累计器(仅在未提供 options.id 时使用)。
// 每个 contentEnvKey(执行环境)初始化时会重设;不持久化、只保证当前环境内递增唯一。
menuIdCounter: number | undefined;
// 菜单注册累计器 - 用于稳定同一Tab不同frame之选项的单独项目不合并状态
// 每个 contentEnvKey(执行环境)初始化时会重设;不持久化、只保证当前环境内递增唯一。
regMenuCounter: number | undefined;
// 内容脚本执行环境识别符,用于区分 mainframe / subframe 等环境并作为 menu key 的命名空间。
// 由 execEnvInit() 以 randomMessageFlag() 生成,避免跨 frame 的 ID 碰撞。
// (同一环境跨脚本也不一样)
contentEnvKey: string | undefined;
@GMContext.API()
public GM_registerMenuCommand(
name: string,
listener?: (inputValue?: any) => void,
options_or_accessKey?: ScriptMenuItemOption | string
): TScriptMenuItemID {
if (!this.EE) return -1;
execEnvInit(this);
this.regMenuCounter! += 1;
// 兼容 GM_registerMenuCommand(name, options_or_accessKey)
if (!options_or_accessKey && typeof listener === "object") {
options_or_accessKey = listener;
listener = undefined;
}
// 浅拷贝避免修改/共用参数
const options: SWScriptMenuItemOption = (
typeof options_or_accessKey === "string"
? { accessKey: options_or_accessKey }
: options_or_accessKey
? { ...options_or_accessKey, id: undefined, individual: undefined } // id不直接储存在options (id 影响 groupKey 操作)
: {}
) as ScriptMenuItemOption;
const isSeparator = !listener && !name;
let isIndividual = typeof options_or_accessKey === "object" ? options_or_accessKey.individual : undefined;
if (isIndividual === undefined && isSeparator) {
isIndividual = true;
}
options.mIndividualKey = isIndividual ? this.regMenuCounter : 0;
if (options.autoClose === undefined) {
options.autoClose = true;
}
if (options.nested === undefined) {
options.nested = true;
}
if (isSeparator) {
// GM_registerMenuCommand("") 时自动设为分隔线
options.mSeparator = true;
name = "";
listener = undefined;
} else {
options.mSeparator = false;
}
let providedId: string | number | undefined =
typeof options_or_accessKey === "object" ? options_or_accessKey.id : undefined;
if (providedId === undefined) providedId = this.menuIdCounter! += 1; // 如无指定,使用累计器id
const ret = providedId! as TScriptMenuItemID;
providedId = `t${providedId!}`; // 见 TScriptMenuItemID 注释
providedId = `${this.contentEnvKey!}.${providedId}` as TScriptMenuItemKey; // 区分 subframe mainframe,见 TScriptMenuItemKey 注释
const menuKey = providedId; // menuKey为唯一键:{环境识别符}.t{注册ID}
// 检查之前有否注册
if (menuKey && this.menuKeyRegistered!.has(menuKey)) {
// 有注册过,先移除 listeners
this.EE.removeAllListeners("menuClick:" + menuKey);
} else {
// 没注册过,先记录一下
this.menuKeyRegistered!.add(menuKey);
}
if (listener) {
// GM_registerMenuCommand("hi", undefined, {accessKey:"h"}) 时TM不会报错
this.EE.addListener("menuClick:" + menuKey, listener);
}
// 发送至 service worker 处理(唯一键,显示名字,不包括id的其他设定)
this.sendMessage("GM_registerMenuCommand", [menuKey, name, options] as GMRegisterMenuCommandParam);
return ret;
}
@GMContext.API({ depend: ["GM_registerMenuCommand"] })
public "GM.registerMenuCommand"(
name: string,
listener?: (inputValue?: any) => void,
options_or_accessKey?: ScriptMenuItemOption | string
): Promise<TScriptMenuItemID> {
return new Promise((resolve) => {
const ret = this.GM_registerMenuCommand(name, listener, options_or_accessKey);
resolve(ret);
});
}
@GMContext.API({ depend: ["GM_registerMenuCommand"] })
public CAT_registerMenuInput(...args: Parameters<GMApi["GM_registerMenuCommand"]>): TScriptMenuItemID {
return this.GM_registerMenuCommand(...args);
}
@GMContext.API()
public GM_addStyle(css: string): Element | undefined {
if (!this.message || !this.scriptRes) return;
if (typeof css !== "string") throw new Error("The parameter 'css' of GM_addStyle shall be a string.");
// 与content页的消息通讯实际是同步,此方法不需要经过background
// 这里直接使用同步的方式去处理, 不要有promise
const resp = (<CustomEventMessage>this.contentMsg).syncSendMessage({
action: `content/runtime/addElement`,
data: {
params: [
null,
"style",
{
textContent: css,
},
],
},
});
if (resp.code) {
throw new Error(resp.message);
}
return (<CustomEventMessage>this.contentMsg).getAndDelRelatedTarget(resp.data) as Element;
}
@GMContext.API({ depend: ["GM_addStyle"] })
public "GM.addStyle"(css: string): Promise<Element | undefined> {
return new Promise((resolve) => {
const ret = this.GM_addStyle(css);
resolve(ret);
});
}
@GMContext.API()
public GM_addElement(
parentNode: Node | string,
tagName: string | Record<string, string | number | boolean>,
attrs: Record<string, string | number | boolean> | null = {}
): Element | undefined {
if (!this.message || !this.scriptRes) return;
// 与content页的消息通讯实际是同步, 此方法不需要经过background
// 这里直接使用同步的方式去处理, 不要有promise
// 在content脚本执行的话,与直接 DOM 无异
// TrustedTypes 限制了对 DOM 的 innerHTML/outerHTML 的操作 (TrustedHTML)
// TrustedTypes 限制了对 script 的 innerHTML/outerHTML/textContent/innerText 的操作 (TrustedScript)
// CSP 限制了对 appendChild/insertChild/replaceChild/insertAdjacentElement ... 等DOM插入移除操作
let parentNodeId: number | null;
if (typeof parentNode !== "string") {
const id = (<CustomEventMessage>this.contentMsg).sendRelatedTarget(parentNode);
parentNodeId = id;
} else {
parentNodeId = null;
attrs = (tagName || {}) as Record<string, string | number | boolean>;
tagName = parentNode as string;
}
if (typeof tagName !== "string") throw new Error("The parameter 'tagName' of GM_addElement shall be a string.");
if (attrs !== null && typeof attrs !== "object") {
throw new Error("The parameter 'attrs' of GM_addElement shall be an object.");
}
// 控制传送参数,避免参数出现 non-json-selizable
const attrsCT = {} as Record<string, string | number>;
const setAttr = {} as Record<string, any>;
for (const [key, value] of Object.entries(attrs as Record<string, any>)) {
if (typeof value === "string" || typeof value === "number") {
// 数字不是标准的 attribute value type, 但常见于实际使用
attrsCT[key] = value;
} else {
// property setter for non attribute (e.g. Function, Symbol, boolean, etc)
// Function, Symbol 无法跨环境传递
setAttr[key] = value;
}
}
// 使用contentMsg同步发送消息到content脚本,由content脚本创建元素并返回
// 不使用message,因为message是在scripting环境处理的,会因为扩展的 CSP 而无法操作 DOM
const resp = (<CustomEventMessage>this.contentMsg).syncSendMessage({
action: `content/runtime/addElement`,
data: {
params: [parentNodeId, tagName, attrsCT],
},
});
if (resp.code) {
throw new Error(resp.message);
}
const el = (<CustomEventMessage>this.contentMsg).getAndDelRelatedTarget(resp.data) as Element;
// 设置属性
for (const [key, value] of Object.entries(setAttr)) {
(el as any)[key] = value;
}
// 回传元素
return el;
}
@GMContext.API({ depend: ["GM_addElement"] })
public "GM.addElement"(
parentNode: Node | string,
tagName: string | Record<string, string | number | boolean>,
attrs: Record<string, string | number | boolean> | null = {}
): Promise<Element | undefined> {
return new Promise<Element | undefined>((resolve) => {
const ret = this.GM_addElement(parentNode, tagName, attrs);
resolve(ret);
});
}
@GMContext.API()
public GM_unregisterMenuCommand(menuId: TScriptMenuItemID): void {
if (!this.EE) return;
if (!this.contentEnvKey) {
return;
}
let menuKey = `t${menuId}`; // 见 TScriptMenuItemID 注释
menuKey = `${this.contentEnvKey!}.${menuKey}` as TScriptMenuItemKey; // 区分 subframe mainframe,见 TScriptMenuItemKey 注释
this.menuKeyRegistered!.delete(menuKey);
this.EE.removeAllListeners("menuClick:" + menuKey);
// 发送至 service worker 处理(唯一键)
this.sendMessage("GM_unregisterMenuCommand", [menuKey] as GMUnRegisterMenuCommandParam);
}
@GMContext.API({ depend: ["GM_unregisterMenuCommand"] })
public "GM.unregisterMenuCommand"(menuId: TScriptMenuItemID): Promise<void> {
return new Promise<void>((resolve) => {
this.GM_unregisterMenuCommand(menuId);
resolve();
});
}
@GMContext.API({
depend: ["GM_unregisterMenuCommand"],
})
public CAT_unregisterMenuInput(...args: Parameters<GMApi["GM_unregisterMenuCommand"]>): void {
this.GM_unregisterMenuCommand(...args);
}
@GMContext.API()
public CAT_userConfig() {
return this.sendMessage("CAT_userConfig", []);
}
@GMContext.API({
depend: ["CAT_fetchBlob"],
})
public async CAT_fileStorage(action: "list" | "download" | "upload" | "delete" | "config", details: any) {
if (action === "config") {
this.sendMessage("CAT_fileStorage", ["config"]);
return;
}
const sendDetails: CATType.CATFileStorageDetails = {
baseDir: details.baseDir || "",
path: details.path || "",
filename: details.filename,
file: details.file,
};
if (action === "upload") {
const url = await toBlobURL(this, details.data);
sendDetails.data = url;
}
this.sendMessage("CAT_fileStorage", [action, sendDetails]).then(async (resp: { action: string; data: any }) => {
switch (resp.action) {
case "onload": {
if (action === "download") {
// 读取blob
const blob = await this.CAT_fetchBlob(resp.data);
details.onload && details.onload(blob);
} else {
details.onload && details.onload(resp.data);
}
break;
}
case "error": {
if (typeof resp.data.code === "undefined") {
details.onerror && details.onerror({ code: -1, message: resp.data.message });
return;
}
details.onerror && details.onerror(resp.data);
}
}
});
}
// 用于脚本跨域请求,需要@connect domain指定允许的域名
@GMContext.API()
public GM_xmlhttpRequest(details: GMTypes.XHRDetails) {
const { abort } = GM_xmlhttpRequest(this, details, false);
return { abort };
}
@GMContext.API()
public "GM.xmlHttpRequest"(details: GMTypes.XHRDetails): Promise<GMTypes.XHRResponse> & GMRequestHandle {
const { retPromise, abort } = GM_xmlhttpRequest(this, details, true);
const ret = retPromise as Promise<GMTypes.XHRResponse> & GMRequestHandle;
ret.abort = abort;
return ret;
}
/**
*
* SC的 downloadMode 设置在API呼叫,TM 的 downloadMode 设置在扩展设定
* native, disabled, browser
* native: 后台xhr下载 -> 后台chrome.download API,disabled: 禁止下载,browser: 后台chrome.download API
*
*/
static _GM_download(a: GMApi, details: GMTypes.DownloadDetails<string | Blob | File>, requirePromise: boolean) {
if (a.isInvalidContext()) {
return {
retPromise: requirePromise ? Promise.reject("GM_download: Invalid Context") : null,
abort: () => {},
};
}
let retPromiseResolve: (value: unknown) => void | undefined;
let retPromiseReject: (reason?: any) => void | undefined;
const retPromise = requirePromise
? new Promise((resolve, reject) => {
retPromiseResolve = resolve;
retPromiseReject = reject;
})
: null;
const urlPromiseLike = typeof details.url === "object" ? convObjectToURL(details.url) : details.url;
let aborted = false;
let connect: MessageConnect;
let nativeAbort: (() => any) | null = null;
const contentContext = details.context;
const makeCallbackParam = <T extends Record<string, any>, K extends T & { data?: any; context?: ContextType }>(
o: T
): K => {
const retParam = { ...o } as unknown as K;
if (o?.data) {
retParam.data = o.data;
}
if (typeof contentContext !== "undefined") {
retParam.context = contentContext;
}
return retParam as K;
};
const handle = async () => {
const url = await urlPromiseLike;
const downloadMode = details.downloadMode || "native"; // native = sc_default; browser = chrome api
details.url = url;
if (downloadMode === "browser" || url.startsWith("blob:")) {
if (typeof details.user === "string" && details.user) {
// scheme://[user[:password]@]host[:port]/path[?query][#fragment]
try {
const u = new URL(details.url);
const userPart = `${encodeURIComponent(details.user)}`;
const passwordPart = details.password ? `:${encodeURIComponent(details.password)}` : "";
details.url = `${u.protocol}//${userPart}${passwordPart}@${u.host}${u.pathname}${u.search}${u.hash}`;
} catch {
// ignored
}
}
const con = await a.connect("GM_download", [
{
method: details.method,
downloadMode: "browser", // 默认使用xhr下载
url: url as string,
name: details.name,
headers: details.headers,
saveAs: details.saveAs,
conflictAction: details.conflictAction,
timeout: details.timeout,
cookie: details.cookie,
anonymous: details.anonymous,
} as GMTypes.DownloadDetails<string>,
]);
if (aborted) return;