@whitesev/utils 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +172 -0
  2. package/dist/index.cjs.js +6017 -0
  3. package/dist/index.cjs.js.map +1 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.esm.js +6015 -0
  6. package/dist/index.esm.js.map +1 -0
  7. package/dist/index.umd.js +6023 -0
  8. package/dist/index.umd.js.map +1 -0
  9. package/dist/src/ColorConversion.d.ts +45 -0
  10. package/dist/src/Dictionary.d.ts +87 -0
  11. package/dist/src/GBKEncoder.d.ts +17 -0
  12. package/dist/src/Hooks.d.ts +5 -0
  13. package/dist/src/Httpx.d.ts +50 -0
  14. package/dist/src/LockFunction.d.ts +16 -0
  15. package/dist/src/Log.d.ts +66 -0
  16. package/dist/src/Progress.d.ts +6 -0
  17. package/dist/src/Utils.d.ts +1560 -0
  18. package/dist/src/UtilsCore.d.ts +9 -0
  19. package/dist/src/UtilsGMCookie.d.ts +36 -0
  20. package/dist/src/UtilsGMMenu.d.ts +119 -0
  21. package/dist/src/ajaxHooker.d.ts +6 -0
  22. package/dist/src/indexedDB.d.ts +165 -0
  23. package/dist/src/tryCatch.d.ts +31 -0
  24. package/index.ts +3 -0
  25. package/package.json +34 -0
  26. package/rollup.config.js +28 -0
  27. package/src/ColorConversion.ts +124 -0
  28. package/src/Dictionary.ts +158 -0
  29. package/src/GBKEncoder.js +111 -0
  30. package/src/GBKEncoder.ts +116 -0
  31. package/src/Hooks.js +73 -0
  32. package/src/Httpx.js +747 -0
  33. package/src/LockFunction.js +35 -0
  34. package/src/Log.js +256 -0
  35. package/src/Progress.js +98 -0
  36. package/src/Utils.ts +4495 -0
  37. package/src/UtilsCore.ts +39 -0
  38. package/src/UtilsGMCookie.ts +167 -0
  39. package/src/UtilsGMMenu.js +464 -0
  40. package/src/ajaxHooker.js +560 -0
  41. package/src/indexedDB.js +355 -0
  42. package/src/tryCatch.js +100 -0
  43. package/src/types/AjaxHooker.d.ts +153 -0
  44. package/src/types/DOMUtils.d.ts +188 -0
  45. package/src/types/Hook.d.ts +16 -0
  46. package/src/types/Httpx.d.ts +1308 -0
  47. package/src/types/Indexdb.d.ts +128 -0
  48. package/src/types/LockFunction.d.ts +47 -0
  49. package/src/types/Log.d.ts +91 -0
  50. package/src/types/Progress.d.ts +30 -0
  51. package/src/types/TryCatch.d.ts +6 -0
  52. package/src/types/UtilsCore.d.ts +7 -0
  53. package/src/types/UtilsGMMenu.d.ts +224 -0
  54. package/src/types/global.d.ts +58 -0
  55. package/tsconfig.json +32 -0
package/src/Utils.ts ADDED
@@ -0,0 +1,4495 @@
1
+ import { ColorConversion } from "./ColorConversion";
2
+ import { UtilsDictionary } from "./Dictionary";
3
+ import { GBKEncoder } from "./GBKEncoder";
4
+ import { UtilsCore } from "./UtilsCore";
5
+ import { UtilsGMCookie } from "./UtilsGMCookie";
6
+ import { ajaxHooker } from "./ajaxHooker";
7
+ import { GMMenu } from "./UtilsGMMenu";
8
+ import { Hooks } from "./Hooks";
9
+ import { Httpx } from "./Httpx";
10
+ import { indexedDB } from "./indexedDB";
11
+ import { LockFunction } from "./LockFunction";
12
+ import { Log } from "./Log";
13
+ import { Progress } from "./Progress";
14
+ import { TryCatch } from "./tryCatch";
15
+
16
+ class Utils {
17
+ /** 版本号 */
18
+ version = "2024.5.24";
19
+
20
+ /**
21
+ * 在页面中增加style元素,如果html节点存在子节点,添加子节点第一个,反之,添加到html节点的子节点最后一个
22
+ * @param cssText css字符串
23
+ * @returns 返回添加的CSS标签
24
+ * @example
25
+ * Utils.GM_addStyle("html{}");
26
+ * > <style type="text/css">html{}</style>
27
+ */
28
+ addStyle(cssText: string): HTMLStyleElement;
29
+ addStyle(cssText: string) {
30
+ if (typeof cssText !== "string") {
31
+ throw new Error("Utils.addStyle 参数cssText 必须为String类型");
32
+ }
33
+ let cssNode = document.createElement("style");
34
+ cssNode.setAttribute("type", "text/css");
35
+ cssNode.innerHTML = cssText;
36
+ if (document.head) {
37
+ /* 插入head最后 */
38
+ document.head.appendChild(cssNode);
39
+ } else if (document.body) {
40
+ /* 插入body后 */
41
+ document.body.appendChild(cssNode);
42
+ } else if (document.documentElement.childNodes.length === 0) {
43
+ /* 插入#html第一个元素后 */
44
+ document.documentElement.appendChild(cssNode);
45
+ } else {
46
+ /* 插入head前面 */
47
+ document.documentElement.insertBefore(
48
+ cssNode,
49
+ document.documentElement.childNodes[0]
50
+ );
51
+ }
52
+ return cssNode;
53
+ }
54
+
55
+ /**
56
+ * JSON数据从源端替换到目标端中,如果目标端存在该数据则替换,不添加,返回结果为目标端替换完毕的结果
57
+ * @param target 目标数据
58
+ * @param source 源数据
59
+ * @param isAdd 是否可以追加键,默认false
60
+ * @example
61
+ * Utils.assign({"1":1,"2":{"3":3}}, {"2":{"3":4}});
62
+ * >
63
+ * {
64
+ "1": 1,
65
+ "2": {
66
+ "3": 4
67
+ }
68
+ }
69
+ */
70
+ assign<T1, T2 extends object, T3 extends boolean>(
71
+ target: T1,
72
+ source: T2,
73
+ isAdd?: T3
74
+ ): T3 extends true ? T1 & T2 : T1;
75
+ assign(target = {}, source = {}, isAdd = false) {
76
+ let UtilsContext = this;
77
+ if (Array.isArray(source)) {
78
+ let canTraverse = source.filter((item) => {
79
+ return typeof item === "object";
80
+ });
81
+ if (!canTraverse.length) {
82
+ return source;
83
+ }
84
+ }
85
+ if (isAdd) {
86
+ for (const sourceKeyName in source) {
87
+ const targetKeyName = sourceKeyName;
88
+ let targetValue = (target as any)[targetKeyName];
89
+ let sourceValue = (source as any)[sourceKeyName];
90
+ if (
91
+ sourceKeyName in target &&
92
+ typeof sourceValue === "object" &&
93
+ !UtilsContext.isDOM(sourceValue)
94
+ ) {
95
+ /* 源端的值是object类型,且不是元素节点 */
96
+ (target as any)[sourceKeyName] = UtilsContext.assign(
97
+ targetValue,
98
+ sourceValue,
99
+ isAdd
100
+ );
101
+ continue;
102
+ }
103
+ (target as any)[sourceKeyName] = sourceValue;
104
+ }
105
+ } else {
106
+ for (const targetKeyName in target) {
107
+ if (targetKeyName in source) {
108
+ let targetValue = (target as any)[targetKeyName];
109
+ let sourceValue = (source as any)[targetKeyName];
110
+ if (
111
+ typeof sourceValue === "object" &&
112
+ !UtilsContext.isDOM(sourceValue) &&
113
+ Object.keys(sourceValue).length
114
+ ) {
115
+ /* 源端的值是object类型,且不是元素节点 */
116
+ (target as any)[targetKeyName] = UtilsContext.assign(
117
+ targetValue,
118
+ sourceValue,
119
+ isAdd
120
+ );
121
+ continue;
122
+ }
123
+ /* 直接赋值 */
124
+ (target as any)[targetKeyName] = sourceValue;
125
+ }
126
+ }
127
+ }
128
+
129
+ return target;
130
+ }
131
+ /**
132
+ * 异步替换字符串
133
+ * @param string 需要被替换的目标字符串
134
+ * @param pattern 正则匹配模型
135
+ * @param asyncFn 异步获取的函数
136
+ */
137
+ asyncReplaceAll(
138
+ string: string,
139
+ pattern: RegExp | string,
140
+ asyncFn: (item: string) => Promise<string>
141
+ ): Promise<string>;
142
+ async asyncReplaceAll(
143
+ string: string,
144
+ pattern: RegExp | string,
145
+ asyncFn: (item: string) => Promise<string>
146
+ ) {
147
+ let UtilsContext = this;
148
+ if (typeof string !== "string") {
149
+ throw new TypeError("string必须是字符串");
150
+ }
151
+ if (typeof asyncFn !== "function") {
152
+ throw new TypeError("asyncFn必须是函数");
153
+ }
154
+ let reg;
155
+ if (typeof pattern === "string") {
156
+ reg = new RegExp(UtilsContext.parseStringToRegExpString(pattern), "g");
157
+ } else if (pattern instanceof RegExp) {
158
+ if (!pattern.global) {
159
+ throw new TypeError("pattern必须是全局匹配");
160
+ }
161
+ reg = new RegExp(pattern);
162
+ } else {
163
+ throw new TypeError("pattern必须是正则对象");
164
+ }
165
+ let result = [];
166
+ let match;
167
+ let lastIndex = 0;
168
+ while ((match = reg.exec(string)) !== null) {
169
+ /* 异步获取匹配对应的字符串 */
170
+ const item = asyncFn(match[0]);
171
+ /* 获取该匹配项和上一个匹配项的中间的字符串 */
172
+ const prefix = string.slice(lastIndex, match.index);
173
+ lastIndex = match.index + match[0].length;
174
+ result.push(item);
175
+ result.push(prefix);
176
+ }
177
+ result.push(string.slice(lastIndex));
178
+ /* 等待所有异步完成 */
179
+ result = await Promise.all(result);
180
+ return result.join("");
181
+ }
182
+ /**
183
+ * ajax劫持库,支持xhr和fetch劫持。
184
+ * + 来源:https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
185
+ * + 作者:cxxjackie
186
+ * + 版本:1.4.1
187
+ * + 文档:https://scriptcat.org/zh-CN/script-show-page/637/
188
+ */
189
+ ajaxHooker: UtilsAjaxHookResult = ajaxHooker;
190
+ /**
191
+ * 根据坐标点击canvas元素的内部位置
192
+ * @param canvasElement 画布元素
193
+ * @param clientX X坐标,默认值0
194
+ * @param clientY Y坐标,默认值0
195
+ * @param view 触发的事件目标
196
+ */
197
+ canvasClickByPosition(
198
+ canvasElement: HTMLCanvasElement,
199
+ clientX?: number | string,
200
+ clientY?: number | string,
201
+ view?: Window & typeof globalThis
202
+ ): void;
203
+ canvasClickByPosition(
204
+ canvasElement: HTMLCanvasElement,
205
+ clientX = 0,
206
+ clientY = 0,
207
+ view = globalThis
208
+ ) {
209
+ if (!(canvasElement instanceof HTMLCanvasElement)) {
210
+ throw new Error(
211
+ "Utils.canvasClickByPosition 参数canvasElement必须是canvas元素"
212
+ );
213
+ }
214
+ clientX = parseInt(clientX.toString());
215
+ clientY = parseInt(clientY.toString());
216
+ const eventInit: MouseEventInit = {
217
+ cancelBubble: true,
218
+ cancelable: true,
219
+ clientX: clientX,
220
+ clientY: clientY,
221
+ // @ts-ignore
222
+ view: view,
223
+ detail: 1,
224
+ };
225
+ canvasElement.dispatchEvent(new MouseEvent("mousedown", eventInit));
226
+ canvasElement.dispatchEvent(new MouseEvent("mouseup", eventInit));
227
+ }
228
+ /**
229
+ * 【手机】检测点击的地方是否在该元素区域内
230
+ * @param element 需要检测的元素
231
+ * @returns
232
+ * + true 点击在元素上
233
+ * + false 未点击在元素上
234
+ * @example
235
+ * Utils.checkUserClickInNode(document.querySelector(".xxx"));
236
+ * > false
237
+ **/
238
+ checkUserClickInNode(element: Element | Node | HTMLElement): boolean;
239
+ checkUserClickInNode(element: Element | Node | HTMLElement) {
240
+ let UtilsContext = this;
241
+ if (!UtilsContext.isDOM(element)) {
242
+ throw new Error(
243
+ "Utils.checkUserClickInNode 参数 targetNode 必须为 Element|Node 类型"
244
+ );
245
+ }
246
+ let mouseClickPosX = Number(
247
+ (window!.event as any).clientX.toString()
248
+ ); /* 鼠标相对屏幕横坐标 */
249
+ let mouseClickPosY = Number(
250
+ (window!.event as any).clientY.toString()
251
+ ); /* 鼠标相对屏幕纵坐标 */
252
+ let elementPosXLeft = Number(
253
+ (element as HTMLElement).getBoundingClientRect().left
254
+ ); /* 要检测的元素的相对屏幕的横坐标最左边 */
255
+ let elementPosXRight = Number(
256
+ (element as HTMLElement).getBoundingClientRect().right
257
+ ); /* 要检测的元素的相对屏幕的横坐标最右边 */
258
+ let elementPosYTop = Number(
259
+ (element as HTMLElement).getBoundingClientRect().top
260
+ ); /* 要检测的元素的相对屏幕的纵坐标最上边 */
261
+ let elementPosYBottom = Number(
262
+ (element as HTMLElement).getBoundingClientRect().bottom
263
+ ); /* 要检测的元素的相对屏幕的纵坐标最下边 */
264
+ let clickNodeHTML = (window.event as any).target.innerHTML as string;
265
+ if (
266
+ mouseClickPosX >= elementPosXLeft &&
267
+ mouseClickPosX <= elementPosXRight &&
268
+ mouseClickPosY >= elementPosYTop &&
269
+ mouseClickPosY <= elementPosYBottom
270
+ ) {
271
+ return true;
272
+ } else if (
273
+ clickNodeHTML &&
274
+ (element as HTMLElement).innerHTML.includes(clickNodeHTML)
275
+ ) {
276
+ /* 这种情况是应对在界面中隐藏的元素,getBoundingClientRect获取的都是0 */
277
+ return true;
278
+ } else {
279
+ return false;
280
+ }
281
+ }
282
+ /**
283
+ * 复制formData数据
284
+ * @param formData 需要clone的数据
285
+ */
286
+ cloneFormData<T extends FormData>(formData: T): T;
287
+ cloneFormData<T extends FormData>(formData: T) {
288
+ let clonedFormData = new FormData();
289
+ for (let [key, value] of (formData as any).entries()) {
290
+ clonedFormData.append(key, value);
291
+ }
292
+ return clonedFormData;
293
+ }
294
+ /**
295
+ * 函数重载实现
296
+ * @example
297
+ * let getUsers = Utils.createOverload();
298
+ * getUsers.addImpl("",()=>{
299
+ * console.log("无参数");
300
+ * });
301
+ *
302
+ * getUsers.addImpl("boolean",()=>{
303
+ * console.log("boolean");
304
+ * });
305
+ *
306
+ * getUsers.addImpl("string",()=>{
307
+ * console.log("string");
308
+ * });
309
+ *
310
+ * getUsers.addImpl("number","string",()=>{
311
+ * console.log("number string");
312
+ * });
313
+ */
314
+ createOverload(): {
315
+ /**
316
+ * 前面的参数都是字符串,最后一个参数是函数
317
+ */
318
+ addImpl<T extends JSTypeNames[]>(
319
+ ...args: [...T, (...args: ArgsType<T>) => any]
320
+ ): void;
321
+ };
322
+ createOverload(): {
323
+ /**
324
+ * 前面的参数都是字符串,最后一个参数是函数
325
+ */
326
+ addImpl<T extends JSTypeNames[]>(
327
+ ...args: [...T, (...args: ArgsType<T>) => any]
328
+ ): void;
329
+ } {
330
+ let fnMap = new Map();
331
+ function overload(this: any, ...args: any[]) {
332
+ let key = args.map((it) => typeof it).join(",");
333
+ let fn = fnMap.get(key);
334
+ if (!fn) {
335
+ throw new TypeError("没有找到对应的实现");
336
+ }
337
+ return fn.apply(this, args);
338
+ }
339
+ overload.addImpl = function (...args: any[]) {
340
+ let fn = args.pop();
341
+ if (typeof fn !== "function") {
342
+ throw new TypeError("最后一个参数必须是函数");
343
+ }
344
+ let key = args.join(",");
345
+ fnMap.set(key, fn);
346
+ };
347
+ return overload;
348
+ }
349
+ /**
350
+ * 颜色转换
351
+ * @returns
352
+ */
353
+ ColorConversion() {
354
+ return new ColorConversion();
355
+ }
356
+ /**
357
+ * 深拷贝
358
+ * @param obj 对象
359
+ */
360
+ deepClone<T extends object | undefined | null>(obj?: T): T;
361
+ deepClone<T extends object | undefined | null>(obj?: T) {
362
+ let UtilsContext = this;
363
+ if (obj === void 0) return void 0;
364
+ if (obj === null) return null;
365
+ let clone = obj instanceof Array ? [] : {};
366
+ for (const [key, value] of Object.entries(obj)) {
367
+ (clone as any)[key] =
368
+ typeof value === "object" ? UtilsContext.deepClone(value) : value;
369
+ }
370
+ return clone;
371
+ }
372
+ /**
373
+ * 防抖函数
374
+ * @param fn 需要触发的回调
375
+ * @param delay 防抖判定时间(毫秒),默认是0ms
376
+ */
377
+ debounce<A extends any[], R>(
378
+ fn: (...args: A) => R,
379
+ delay?: number
380
+ ): (...args: A) => void;
381
+ debounce<A extends any[], R>(fn: (...args: A) => R, delay = 0) {
382
+ let timer: number = null as any;
383
+ const context = this;
384
+ return function (...args: A) {
385
+ clearTimeout(timer);
386
+ timer = setTimeout(function () {
387
+ fn.apply(context, args);
388
+ }, delay);
389
+ };
390
+ }
391
+ /**
392
+ * 删除某个父元素,父元素可能在上层或上上层或上上上层...
393
+ * @param element 当前元素
394
+ * @param targetSelector 判断是否满足父元素,参数为当前处理的父元素,满足返回true,否则false
395
+ * @returns
396
+ * + true 已删除
397
+ * + false 未删除
398
+ * @example
399
+ * Utils.deleteParentNode(document.querySelector("a"),".xxx");
400
+ * > true
401
+ **/
402
+ deleteParentNode(
403
+ element: Node | HTMLElement | Element | null,
404
+ targetSelector: string
405
+ ): boolean;
406
+ deleteParentNode(
407
+ element: Node | HTMLElement | Element | null,
408
+ targetSelector: string
409
+ ) {
410
+ let UtilsContext = this;
411
+ if (element == null) {
412
+ return;
413
+ }
414
+ if (!UtilsContext.isDOM(element)) {
415
+ throw new Error(
416
+ "Utils.deleteParentNode 参数 target 必须为 Node|HTMLElement 类型"
417
+ );
418
+ }
419
+ if (typeof targetSelector !== "string") {
420
+ throw new Error(
421
+ "Utils.deleteParentNode 参数 targetSelector 必须为 string 类型"
422
+ );
423
+ }
424
+ let result = false;
425
+ let needRemoveDOM = (element as HTMLElement).closest(targetSelector);
426
+ if (needRemoveDOM) {
427
+ needRemoveDOM.remove();
428
+ result = true;
429
+ }
430
+ return result;
431
+ }
432
+
433
+ /**
434
+ * 字典
435
+ * @example
436
+ * let dictionary = new Utils.Dictionary();
437
+ * let dictionary2 = new Utils.Dictionary();
438
+ * dictionary.set("test","111");
439
+ * dictionary.get("test");
440
+ * > '111'
441
+ * dictionary.has("test");
442
+ * > true
443
+ * dictionary.concat(dictionary2);
444
+ **/
445
+ Dictionary = UtilsDictionary;
446
+ /**
447
+ * 主动触发事件
448
+ * @param element 元素
449
+ * @param eventName 事件名称,可以是字符串,也可是字符串格式的列表
450
+ * @param details (可选)赋予触发的Event的额外属性
451
+ * + true 使用Proxy代理Event并设置获取isTrusted永远为True
452
+ * + false (默认) 不对Event进行Proxy代理
453
+ * @example
454
+ * Utils.dispatchEvent(document.querySelector("input","input"))
455
+ */
456
+ dispatchEvent(
457
+ element: HTMLElement | Document,
458
+ eventName: DOMUtils_EventType | DOMUtils_EventType[],
459
+ details?: UtilsNestedObjectWithToString<any>
460
+ ): void;
461
+ /**
462
+ * 主动触发事件
463
+ * @param element 元素
464
+ * @param eventName 事件名称,可以是字符串,也可是字符串格式的列表
465
+ * @param details (可选)赋予触发的Event的额外属性
466
+ * + true 使用Proxy代理Event并设置获取isTrusted永远为True
467
+ * + false (默认) 不对Event进行Proxy代理
468
+ * @example
469
+ * Utils.dispatchEvent(document.querySelector("input","input"))
470
+ */
471
+ dispatchEvent(
472
+ element: HTMLElement | Document,
473
+ eventName: string,
474
+ details?: UtilsNestedObjectWithToString<any>
475
+ ): void;
476
+ dispatchEvent(
477
+ element: HTMLElement | Document,
478
+ eventName: DOMUtils_EventType | DOMUtils_EventType[] | string,
479
+ details?: UtilsNestedObjectWithToString<any>
480
+ ) {
481
+ let eventNameList: string[] = [];
482
+ if (typeof eventName === "string") {
483
+ eventNameList = [eventName];
484
+ }
485
+ if (Array.isArray(eventName)) {
486
+ eventNameList = [...eventName];
487
+ }
488
+ eventNameList.forEach((_eventName_) => {
489
+ let event = new Event(_eventName_);
490
+ if (details) {
491
+ Object.assign(event, details);
492
+ }
493
+ element.dispatchEvent(event);
494
+ });
495
+ }
496
+ /**
497
+ * 下载base64格式的数据
498
+ * @param base64Data 需要转换的base64数据
499
+ * @param fileName 需要保存的文件名
500
+ * @param isIFrame (可选)是否使用iframe进行下载
501
+ * @example
502
+ * Utils.downloadBase64("data:image/jpeg:base64/,xxxxxx");
503
+ **/
504
+ downloadBase64(
505
+ base64Data: string,
506
+ fileName: string,
507
+ isIFrame?: boolean
508
+ ): void;
509
+ downloadBase64(base64Data: string, fileName: string, isIFrame = false) {
510
+ if (typeof base64Data !== "string") {
511
+ throw new Error(
512
+ "Utils.downloadBase64 参数 base64Data 必须为 string 类型"
513
+ );
514
+ }
515
+ if (typeof fileName !== "string") {
516
+ throw new Error("Utils.downloadBase64 参数 fileName 必须为 string 类型");
517
+ }
518
+ if (isIFrame) {
519
+ /* 使用iframe */
520
+ const iframeElement = document.createElement("iframe");
521
+ iframeElement.style.display = "none";
522
+ iframeElement.src = base64Data;
523
+ document.body.appendChild(iframeElement);
524
+ setTimeout(() => {
525
+ iframeElement!.contentWindow!.document.execCommand(
526
+ "SaveAs",
527
+ true,
528
+ fileName
529
+ );
530
+ document.body.removeChild(iframeElement);
531
+ }, 100);
532
+ } else {
533
+ /* 使用A标签 */
534
+ const linkElement = document.createElement("a");
535
+ linkElement.setAttribute("target", "_blank");
536
+ linkElement.download = fileName;
537
+ linkElement.href = base64Data;
538
+ linkElement.click();
539
+ }
540
+ }
541
+
542
+ /**
543
+ * 选中页面中的文字,类似Ctrl+F的选中
544
+ * @param str (可选)需要寻找的字符串,默认为空
545
+ * @param caseSensitive(可选)默认false
546
+ * + true 区分大小写
547
+ * + false (默认) 不区分大小写
548
+ * @returns
549
+ * + true 找到
550
+ * + false 未找到
551
+ * + undefined 不可使用该Api
552
+ * @example
553
+ * Utils.findWebPageVisibleText("xxxxx");
554
+ * > true
555
+ **/
556
+ findWebPageVisibleText(str?: string, caseSensitive?: boolean): boolean | void;
557
+ findWebPageVisibleText(str = "", caseSensitive = false) {
558
+ let TRange = null;
559
+ let strFound;
560
+ if ((UtilsCore.globalThis as any).find) {
561
+ /* CODE FOR BROWSERS THAT SUPPORT window.find */
562
+ let windowFind = (UtilsCore.self as any).find;
563
+ strFound = windowFind(str, caseSensitive, true, true, false);
564
+ if (strFound && self.getSelection && !self.getSelection()!.anchorNode) {
565
+ strFound = windowFind(str, caseSensitive, true, true, false);
566
+ }
567
+ if (!strFound) {
568
+ strFound = windowFind(str, 0, 1);
569
+ while (windowFind(str, 0, 1)) continue;
570
+ }
571
+ } else if (navigator.appName.indexOf("Microsoft") != -1) {
572
+ /* EXPLORER-SPECIFIC CODE */
573
+ if (TRange != null) {
574
+ TRange = TRange as any;
575
+ TRange.collapse(false);
576
+ strFound = TRange.findText(str);
577
+ if (strFound) TRange.select();
578
+ }
579
+ if (TRange == null || strFound == 0) {
580
+ TRange = (UtilsCore.self.document.body as any).createTextRange();
581
+ strFound = TRange.findText(str);
582
+ if (strFound) TRange.select();
583
+ }
584
+ } else if (navigator.appName == "Opera") {
585
+ alert("Opera browsers not supported, sorry...");
586
+ return;
587
+ }
588
+ return strFound ? true : false;
589
+ }
590
+ /**
591
+ * 定位元素上的字符串,返回一个迭代器
592
+ * @param element 目标元素
593
+ * @param text 需要定位的字符串
594
+ * @param filter (可选)过滤器函数,返回值为true是排除该元素
595
+ * @example
596
+ * let textIterator = Utils.findElementsWithText(document.documentElement,"xxxx");
597
+ * textIterator.next();
598
+ * > {value: ?HTMLElement, done: boolean, next: Function}
599
+ */
600
+ findElementsWithText<T extends HTMLElement | Element | Node>(
601
+ element: T,
602
+ text: string,
603
+ filter?: (element: T) => boolean
604
+ ): Generator<HTMLElement | ChildNode, void, any>;
605
+ *findElementsWithText<T extends HTMLElement | Element | Node>(
606
+ element: T,
607
+ text: string,
608
+ filter?: (element: T) => boolean
609
+ ) {
610
+ let that = this;
611
+ if ((element as HTMLElement).outerHTML.includes(text)) {
612
+ if ((element as HTMLElement).children.length === 0) {
613
+ let filterResult =
614
+ typeof filter === "function" ? filter(element) : false;
615
+ if (!filterResult) {
616
+ yield element as any;
617
+ }
618
+ } else {
619
+ let textElement = Array.from(element.childNodes).filter(
620
+ (ele) => ele.nodeType === Node.TEXT_NODE
621
+ );
622
+ for (let ele of textElement) {
623
+ if ((ele as any).textContent.includes(text)) {
624
+ let filterResult =
625
+ typeof filter === "function" ? filter(element) : false;
626
+ if (!filterResult) {
627
+ yield ele;
628
+ }
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ for (
635
+ let index = 0;
636
+ index < (element as HTMLElement).children.length;
637
+ index++
638
+ ) {
639
+ let childElement = (element as HTMLElement).children[index] as any;
640
+ yield* that.findElementsWithText(childElement, text, filter);
641
+ }
642
+ }
643
+ /**
644
+ * 判断该元素是否可见,如果不可见,向上找它的父元素直至找到可见的元素
645
+ * @param element
646
+ * @example
647
+ * let visibleElement = Utils.findVisibleElement(document.querySelector("a.xx"));
648
+ * > <HTMLElement>
649
+ */
650
+ findVisibleElement(element: HTMLElement | Element | Node) {
651
+ let currentElement = element as HTMLElement;
652
+ while (currentElement) {
653
+ let elementRect = currentElement.getBoundingClientRect();
654
+ if (Boolean((elementRect as any).length)) {
655
+ return currentElement;
656
+ }
657
+ currentElement = currentElement.parentElement as any;
658
+ }
659
+ return null;
660
+ }
661
+ /**
662
+ * 格式化byte为KB、MB、GB、TB、PB、EB、ZB、YB、BB、NB、DB
663
+ * @param byteSize 字节
664
+ * @param addType (可选)是否添加单位
665
+ * + true (默认) 添加单位
666
+ * + false 不添加单位
667
+ * @returns
668
+ * + {string} 当addType为true时,且保留小数点末尾2位
669
+ * + {number} 当addType为false时,且保留小数点末尾2位
670
+ * @example
671
+ * Utils.formatByteToSize("812304");
672
+ * > '793.27KB'
673
+ * @example
674
+ * Utils.formatByteToSize("812304",false);
675
+ * > 793.27
676
+ **/
677
+ formatByteToSize<T extends boolean>(
678
+ byteSize: number | string,
679
+ addType?: T
680
+ ): T extends true ? string : number;
681
+ formatByteToSize(byteSize: number | string, addType = true) {
682
+ byteSize = parseInt(byteSize.toString());
683
+ if (isNaN(byteSize)) {
684
+ throw new Error("Utils.formatByteToSize 参数 byteSize 格式不正确");
685
+ }
686
+ let result = 0;
687
+ let resultType = "KB";
688
+ let sizeData: UtilsNestedObjectWithToString<number> = {};
689
+ sizeData.B = 1;
690
+ sizeData.KB = 1024;
691
+ sizeData.MB = sizeData.KB * sizeData.KB;
692
+ sizeData.GB = sizeData.MB * sizeData.KB;
693
+ sizeData.TB = sizeData.GB * sizeData.KB;
694
+ sizeData.PB = sizeData.TB * sizeData.KB;
695
+ sizeData.EB = sizeData.PB * sizeData.KB;
696
+ sizeData.ZB = sizeData.EB * sizeData.KB;
697
+ sizeData.YB = sizeData.ZB * sizeData.KB;
698
+ sizeData.BB = sizeData.YB * sizeData.KB;
699
+ sizeData.NB = sizeData.BB * sizeData.KB;
700
+ sizeData.DB = sizeData.NB * sizeData.KB;
701
+ for (let key in sizeData) {
702
+ result = byteSize / sizeData[key];
703
+ resultType = key;
704
+ if (sizeData.KB >= result) {
705
+ break;
706
+ }
707
+ }
708
+ result = result.toFixed(2) as any;
709
+ result = addType
710
+ ? result + resultType.toString()
711
+ : (parseFloat(result.toString()) as any);
712
+ return result;
713
+ }
714
+ /**
715
+ * 应用场景: 当你想要获取数组形式的元素时,它可能是其它的选择器,那么需要按照先后顺序填入参数
716
+ * 第一个是优先级最高的,依次下降,如果都没有,返回空列表
717
+ * 支持document.querySelectorAll、$("")、()=>{return document.querySelectorAll("")}
718
+ * @param NodeList
719
+ * @example
720
+ * Utils.getNodeListValue(
721
+ * document.querySelectorAll("div.xxx"),
722
+ * document.querySelectorAll("a.xxx")
723
+ * );
724
+ * > [...div,div,div]
725
+ * @example
726
+ * Utils.getNodeListValue(divGetFunction,aGetFunction);
727
+ * > [...div,div,div]
728
+ */
729
+ getNodeListValue(...args: (NodeList | (() => HTMLElement))[]): HTMLElement[];
730
+ getNodeListValue(...args: (NodeList | (() => HTMLElement))[]) {
731
+ let resultArray: HTMLElement[] = [];
732
+ for (let arg of args) {
733
+ let value = arg as any;
734
+ if (typeof arg === "function") {
735
+ /* 方法 */
736
+ value = arg();
737
+ }
738
+ if (value.length !== 0) {
739
+ resultArray = [...value];
740
+ break;
741
+ }
742
+ }
743
+ return resultArray;
744
+ }
745
+ /**
746
+ * 自动判断N个参数,获取非空的值,如果都是空,返回最后一个值
747
+ */
748
+ getNonNullValue(...args: any[]): any;
749
+ getNonNullValue(...args: any[]) {
750
+ let resultValue = args[args.length - 1];
751
+ let UtilsContext = this;
752
+ for (const argValue of args) {
753
+ if (UtilsContext.isNotNull(argValue)) {
754
+ resultValue = argValue;
755
+ break;
756
+ }
757
+ }
758
+ return resultValue;
759
+ }
760
+ /**
761
+ * 获取格式化后的时间
762
+ * @param text (可选)需要格式化的字符串或者时间戳,默认:new Date()
763
+ * @param formatType (可选)格式化成的显示类型,默认:yyyy-MM-dd HH:mm:ss
764
+ * + yyyy 年
765
+ * + MM 月
766
+ * + dd 天
767
+ * + HH 时 (24小时制)
768
+ * + hh 时 (12小时制)
769
+ * + mm 分
770
+ * + ss 秒
771
+ * @returns {string} 返回格式化后的时间
772
+ * @example
773
+ * Utils.formatTime("2022-08-21 23:59:00","HH:mm:ss");
774
+ * > '23:59:00'
775
+ * @example
776
+ * Utils.formatTime(1899187424988,"HH:mm:ss");
777
+ * > '15:10:13'
778
+ * @example
779
+ * Utils.formatTime()
780
+ * > '2023-1-1 00:00:00'
781
+ **/
782
+ formatTime(
783
+ text?: string | number | Date,
784
+ formatType?:
785
+ | "yyyy-MM-dd HH:mm:ss"
786
+ | "yyyy/MM/dd HH:mm:ss"
787
+ | "yyyy年MM月dd日 HH时mm分ss秒"
788
+ | "yyyyMMdd"
789
+ | "yyyy_MM_dd_HH_mm_ss"
790
+ | "yyyy年MM月dd日 hh:mm:ss"
791
+ | "yyyy-MM-dd"
792
+ | "HH:mm:ss"
793
+ ): string;
794
+ formatTime(text = new Date(), formatType = "yyyy-MM-dd HH:mm:ss") {
795
+ let time = text == null ? new Date() : new Date(text);
796
+ /**
797
+ * 校验时间补0
798
+ * @param timeNum
799
+ * @returns
800
+ */
801
+ function checkTime(timeNum: number) {
802
+ if (timeNum < 10) return "0" + timeNum;
803
+ return timeNum;
804
+ }
805
+
806
+ /**
807
+ * 时间制修改 24小时制转12小时制
808
+ * @param hourNum 小时
809
+ * @returns
810
+ */
811
+ function timeSystemChange(hourNum: number) {
812
+ return hourNum > 12 ? hourNum - 12 : hourNum;
813
+ }
814
+
815
+ let timeRegexp = {
816
+ yyyy: time.getFullYear(),
817
+ /* 年 */
818
+ MM: checkTime(time.getMonth() + 1),
819
+ /* 月 */
820
+ dd: checkTime(time.getDate()),
821
+ /* 日 */
822
+ HH: checkTime(time.getHours()),
823
+ /* 时 (24小时制) */
824
+ hh: checkTime(timeSystemChange(time.getHours())),
825
+ /* 时 (12小时制) */
826
+ mm: checkTime(time.getMinutes()),
827
+ /* 分 */
828
+ ss: checkTime(time.getSeconds()),
829
+ /* 秒 */
830
+ };
831
+ Object.keys(timeRegexp).forEach(function (key) {
832
+ let replaecRegexp = new RegExp(key, "g");
833
+ formatType = formatType.replace(replaecRegexp, (timeRegexp as any)[key]);
834
+ });
835
+ return formatType;
836
+ }
837
+ /**
838
+ * 字符串格式的时间转时间戳
839
+ * @param text 字符串格式的时间,例如:
840
+ * + 2022-11-21 00:00:00
841
+ * + 00:00:00
842
+ * @returns 返回时间戳
843
+ * @example
844
+ * Utils.formatToTimeStamp("2022-11-21 00:00:00");
845
+ * > 1668960000000
846
+ **/
847
+ formatToTimeStamp(text: string): number;
848
+ formatToTimeStamp(text: string) {
849
+ /* 把字符串格式的时间(完整,包括日期和时间)格式化成时间 */
850
+ if (typeof text !== "string") {
851
+ throw new Error("Utils.formatToTimeStamp 参数 text 必须为 string 类型");
852
+ }
853
+ if (text.length === 8) {
854
+ /* 该字符串只有时分秒 */
855
+ let today = new Date();
856
+ text =
857
+ today.getFullYear() +
858
+ "-" +
859
+ (today.getMonth() + 1) +
860
+ "-" +
861
+ today.getDate() +
862
+ " " +
863
+ text;
864
+ }
865
+ text = text.substring(0, 19);
866
+ text = text.replace(/-/g, "/");
867
+ let timestamp = new Date(text).getTime();
868
+ return timestamp;
869
+ }
870
+ /**
871
+ * gbk格式的url编码,来自https://greasyfork.org/zh-CN/scripts/427726-gbk-url-js
872
+ * @example
873
+ * let gbkEncoder = new Utils.GBKEncoder();
874
+ * gbkEncoder.encode("测试");
875
+ * > '%B2%E2%CA%D4'
876
+ * gbkEncoder.decode("%B2%E2%CA%D4");
877
+ * > 测试
878
+ */
879
+ GBKEncoder = GBKEncoder;
880
+ /**
881
+ * 获取 transitionend 的在各个浏览器的兼容名
882
+ */
883
+ getTransitionEndNameList() {
884
+ return [
885
+ "webkitTransitionEnd",
886
+ "mozTransitionEnd",
887
+ "MSTransitionEnd",
888
+ "otransitionend",
889
+ "transitionend",
890
+ ];
891
+ }
892
+ /**
893
+ * 获取 animationend 的在各个浏览器的兼容名
894
+ */
895
+ getAnimationEndNameList() {
896
+ return [
897
+ "webkitAnimationEnd",
898
+ "mozAnimationEnd",
899
+ "MSAnimationEnd",
900
+ "oanimationend",
901
+ "animationend",
902
+ ];
903
+ }
904
+ /**
905
+ * 获取NodeList或Array对象中的最后一个的值
906
+ * @param targetObj
907
+ * @returns
908
+ * @example
909
+ * Utils.getArrayLastValue(document.querySelectorAll("div"));
910
+ * > div
911
+ * @example
912
+ * Utils.getArrayLastValue([1,2,3,4,5]);
913
+ * > 5
914
+ */
915
+ getArrayLastValue<R extends any>(targetObj: NodeList | any[]): R;
916
+ getArrayLastValue(targetObj: NodeList | any[]) {
917
+ return targetObj[targetObj.length - 1];
918
+ }
919
+ /**
920
+ * 应用场景: 当想获取的元素可能是不同的选择器的时候,按顺序优先级获取
921
+ * 参数类型可以是Element或者是Function
922
+ * @returns 如果都没有的话,返回null
923
+ * @example
924
+ * // 如果a.aaa不存在的话,取a.bbb,这里假设a.aaa不存在
925
+ * Utils.getArrayRealValue(document.querySelector("a.aaa"),document.querySelector("a.bbb"));
926
+ * > a.bbb
927
+ * @example
928
+ * Utils.getArrayRealValue(()=>{return document.querySelector("a.aaa").href},()=>{document.querySelector("a.bbb").getAttribute("data-href")});
929
+ * > javascript:;
930
+ */
931
+ getArrayRealValue(...args: (NodeList | (() => HTMLElement))[]): any;
932
+ getArrayRealValue(...args: (NodeList | (() => HTMLElement))[]) {
933
+ let result = null;
934
+ for (let arg of args) {
935
+ if (typeof arg === "function") {
936
+ /* 方法 */
937
+ (arg as any) = arg();
938
+ }
939
+ if (arg != null) {
940
+ result = arg;
941
+ break;
942
+ }
943
+ }
944
+ return result;
945
+ }
946
+ /**
947
+ * 获取天数差异,如何获取某个时间与另一个时间相差的天数
948
+ * @param timestamp1 (可选)时间戳(毫秒|秒),不区分哪个更大,默认为:Date.now()
949
+ * @param timestamp2 (可选)时间戳(毫秒|秒),不区分哪个更大,默认为:Date.now()
950
+ * @param type (可选)返回的数字的表达的类型,比如:年、月、天、时、分、秒、auto,默认天
951
+ * @example
952
+ * Utils.getDaysDifference(new Date().getTime());
953
+ * > 0
954
+ * @example
955
+ * Utils.getDaysDifference(new Date().getTime(),undefined,"秒");
956
+ * > 0
957
+ */
958
+ getDaysDifference(
959
+ timestamp1?: number,
960
+ timestamp2?: number,
961
+ type?: "auto"
962
+ ): string;
963
+ /**
964
+ * 获取天数差异,如何获取某个时间与另一个时间相差的天数
965
+ * @param timestamp1 (可选)时间戳(毫秒|秒),不区分哪个更大,默认为:Date.now()
966
+ * @param timestamp2 (可选)时间戳(毫秒|秒),不区分哪个更大,默认为:Date.now()
967
+ * @param type (可选)返回的数字的表达的类型,比如:年、月、天、时、分、秒、auto,默认天
968
+ * @example
969
+ * Utils.getDaysDifference(new Date().getTime());
970
+ * > 0
971
+ * @example
972
+ * Utils.getDaysDifference(new Date().getTime(),undefined,"秒");
973
+ * > 0
974
+ */
975
+ getDaysDifference(
976
+ timestamp1?: number,
977
+ timestamp2?: number,
978
+ type?: "年" | "月" | "天" | "时" | "分" | "秒"
979
+ ): number;
980
+ getDaysDifference(
981
+ timestamp1 = Date.now(),
982
+ timestamp2 = Date.now(),
983
+ type = "天"
984
+ ): number | string {
985
+ type = type.trim();
986
+ if (timestamp1.toString().length === 10) {
987
+ timestamp1 = timestamp1 * 1000;
988
+ }
989
+ if (timestamp2.toString().length === 10) {
990
+ timestamp2 = timestamp2 * 1000;
991
+ }
992
+ let smallTimeStamp = timestamp1 > timestamp2 ? timestamp2 : timestamp1;
993
+ let bigTimeStamp = timestamp1 > timestamp2 ? timestamp1 : timestamp2;
994
+ let oneSecond = 1000; /* 一秒的毫秒数 */
995
+ let oneMinute = 60 * oneSecond; /* 一分钟的毫秒数 */
996
+ let oneHour = 60 * oneMinute; /* 一小时的毫秒数 */
997
+ let oneDay = 24 * oneHour; /* 一天的毫秒数 */
998
+ let oneMonth = 30 * oneDay; /* 一个月的毫秒数(30天) */
999
+ let oneYear = 12 * oneMonth; /* 一年的毫秒数 */
1000
+ let bigDate = new Date(bigTimeStamp);
1001
+ let smallDate = new Date(smallTimeStamp);
1002
+ let remainderValue = 1;
1003
+ if (type === "年") {
1004
+ remainderValue = oneYear;
1005
+ } else if (type === "月") {
1006
+ remainderValue = oneMonth;
1007
+ } else if (type === "天") {
1008
+ remainderValue = oneDay;
1009
+ } else if (type === "时") {
1010
+ remainderValue = oneHour;
1011
+ } else if (type === "分") {
1012
+ remainderValue = oneMinute;
1013
+ } else if (type === "秒") {
1014
+ remainderValue = oneSecond;
1015
+ }
1016
+ let diffValue = Math.round(
1017
+ Math.abs(((bigDate as any) - (smallDate as any)) / remainderValue)
1018
+ );
1019
+ if (type === "auto") {
1020
+ let timeDifference = bigTimeStamp - smallTimeStamp;
1021
+ diffValue = Math.floor(timeDifference / (24 * 3600 * 1000));
1022
+ if (diffValue > 0) {
1023
+ (diffValue as any) = diffValue + "天";
1024
+ } else {
1025
+ /* 计算出小时数 */
1026
+ let leave1 =
1027
+ timeDifference % (24 * 3600 * 1000); /* 计算天数后剩余的毫秒数 */
1028
+ let hours = Math.floor(leave1 / (3600 * 1000));
1029
+ if (hours > 0) {
1030
+ (diffValue as any) = hours + "小时";
1031
+ } else {
1032
+ /* 计算相差分钟数 */
1033
+ let leave2 = leave1 % (3600 * 1000); /* 计算小时数后剩余的毫秒数 */
1034
+ let minutes = Math.floor(leave2 / (60 * 1000));
1035
+ if (minutes > 0) {
1036
+ (diffValue as any) = minutes + "分钟";
1037
+ } else {
1038
+ /* 计算相差秒数 */
1039
+ let leave3 = leave2 % (60 * 1000); /* 计算分钟数后剩余的毫秒数 */
1040
+ let seconds = Math.round(leave3 / 1000);
1041
+ (diffValue as any) = seconds + "秒";
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ return diffValue;
1047
+ }
1048
+ /**
1049
+ * 获取元素的选择器字符串
1050
+ * @param element
1051
+ * @example
1052
+ * Utils.getElementSelector(document.querySelector("a"))
1053
+ * > '.....'
1054
+ */
1055
+ getElementSelector(element: HTMLElement): string;
1056
+ getElementSelector(element: HTMLElement): string {
1057
+ let UtilsContext = this;
1058
+ // @ts-ignore
1059
+ if (!element) return;
1060
+ // @ts-ignore
1061
+ if (!element.parentElement) return;
1062
+ /* 如果元素有id属性,则直接返回id选择器 */
1063
+ if (element.id) return "#" + element.id;
1064
+
1065
+ /* 递归地获取父元素的选择器 */
1066
+ let selector = UtilsContext.getElementSelector(element.parentElement);
1067
+ if (!selector) {
1068
+ return element.tagName.toLowerCase();
1069
+ }
1070
+ /* 如果有多个相同类型的兄弟元素,则需要添加索引 */
1071
+ if (element.parentElement.querySelectorAll(element.tagName).length > 1) {
1072
+ let index =
1073
+ Array.prototype.indexOf.call(element.parentElement.children, element) +
1074
+ 1;
1075
+ selector +=
1076
+ " > " + element.tagName.toLowerCase() + ":nth-child(" + index + ")";
1077
+ } else {
1078
+ selector += " > " + element.tagName.toLowerCase();
1079
+ }
1080
+ return selector;
1081
+ }
1082
+ /**
1083
+ * 获取最大值
1084
+ * @example
1085
+ * Utils.getMaxValue(1,3,5,7,9)
1086
+ * > 9
1087
+ */
1088
+ getMaxValue(...args: number[]): number;
1089
+ /**
1090
+ * 获取最大值
1091
+ * @example
1092
+ * Utils.getMaxValue([1,3,5])
1093
+ * > 5
1094
+ */
1095
+ getMaxValue(val: number[]): number;
1096
+ /**
1097
+ * 获取最大值
1098
+ * @example
1099
+ * Utils.getMaxValue({1:123,2:345,3:456},(key,value)=>{return parseInt(value)})
1100
+ * > 456
1101
+ */
1102
+ getMaxValue(
1103
+ val: UtilsNestedObjectWithToString<number>,
1104
+ handler: (key: any, value: any) => number
1105
+ ): number;
1106
+ /**
1107
+ * 获取最大值
1108
+ * @example
1109
+ * Utils.getMaxValue([{1:123},{2:345},{3:456}],(index,value)=>{return parseInt(index)})
1110
+ * > 2
1111
+ */
1112
+ getMaxValue(...args: any[]): number {
1113
+ let result = [...args];
1114
+ let newResult: number[] = [];
1115
+ if (result.length === 0) {
1116
+ // @ts-ignore
1117
+ return;
1118
+ }
1119
+ if (result.length > 1) {
1120
+ if (
1121
+ result.length === 2 &&
1122
+ typeof result[0] === "object" &&
1123
+ typeof result[1] === "function"
1124
+ ) {
1125
+ let data = result[0];
1126
+ let handleDataFunc = result[1];
1127
+ Object.keys(data).forEach((keyName) => {
1128
+ newResult = [...newResult, handleDataFunc(keyName, data[keyName])];
1129
+ });
1130
+ } else {
1131
+ result.forEach((item) => {
1132
+ if (!isNaN(parseFloat(item))) {
1133
+ newResult = [...newResult, parseFloat(item)];
1134
+ }
1135
+ });
1136
+ }
1137
+ return Math.max(...newResult);
1138
+ } else {
1139
+ result[0].forEach((item: any) => {
1140
+ if (!isNaN(parseFloat(item))) {
1141
+ newResult = [...newResult, parseFloat(item)];
1142
+ }
1143
+ });
1144
+ return Math.max(...newResult);
1145
+ }
1146
+ }
1147
+ /**
1148
+ * 获取页面中最大的z-index
1149
+ * @param deviation 获取最大的z-index值的偏移,默认是+1
1150
+ * @example
1151
+ * Utils.getMaxZIndex();
1152
+ * > 1001
1153
+ **/
1154
+ getMaxZIndex(deviation?: number): number;
1155
+ getMaxZIndex(deviation = 1): number {
1156
+ let nodeIndexList: number[] = [];
1157
+ deviation = Number.isNaN(deviation) ? 1 : deviation;
1158
+ document.querySelectorAll("*").forEach((element) => {
1159
+ let nodeStyle = window.getComputedStyle(element);
1160
+ /* 不对position为static和display为none的元素进行获取它们的z-index */
1161
+ if (nodeStyle.position !== "static" && nodeStyle.display !== "none") {
1162
+ nodeIndexList = nodeIndexList.concat(parseInt(nodeStyle.zIndex));
1163
+ }
1164
+ });
1165
+ /* 过滤非Boolean类型 */
1166
+ nodeIndexList = nodeIndexList.filter(Boolean);
1167
+ let currentMaxZIndex = nodeIndexList.length
1168
+ ? Math.max(...nodeIndexList)
1169
+ : 0;
1170
+ return currentMaxZIndex + deviation;
1171
+ }
1172
+ /**
1173
+ * 获取最小值
1174
+ * @example
1175
+ * Utils.getMinValue(1,3,5,7,9)
1176
+ * > 1
1177
+ */
1178
+ getMinValue(...args: number[]): number;
1179
+ /**
1180
+ * 获取最小值
1181
+ * @example
1182
+ * Utils.getMinValue([1,3,5])
1183
+ * > 1
1184
+ */
1185
+ getMinValue(val: number[]): number;
1186
+ /**
1187
+ * 获取最小值
1188
+ * @example
1189
+ * Utils.getMinValue({1:123,2:345,3:456},(key,value)=>{return parseInt(value)})
1190
+ * > 123
1191
+ */
1192
+ getMinValue(
1193
+ val: UtilsNestedObjectWithToString<number>,
1194
+ handler: (key: any, value: any) => number
1195
+ ): number;
1196
+ /**
1197
+ * 获取最小值
1198
+ * @example
1199
+ * Utils.getMinValue([{1:123},{2:345},{3:456}],(index,value)=>{return parseInt(index)})
1200
+ * > 0
1201
+ */
1202
+ getMinValue(
1203
+ val: UtilsNestedObjectWithToString<number>[],
1204
+ handler: (index: number, value: any) => number
1205
+ ): number;
1206
+ getMinValue(...args: any[]): number {
1207
+ let result = [...args];
1208
+ let newResult: number[] = [];
1209
+ if (result.length === 0) {
1210
+ // @ts-ignore
1211
+ return;
1212
+ }
1213
+ if (result.length > 1) {
1214
+ if (
1215
+ result.length === 2 &&
1216
+ typeof result[0] === "object" &&
1217
+ typeof result[1] === "function"
1218
+ ) {
1219
+ let data = result[0];
1220
+ let handleDataFunc = result[1];
1221
+ Object.keys(data).forEach((keyName) => {
1222
+ newResult = [...newResult, handleDataFunc(keyName, data[keyName])];
1223
+ });
1224
+ } else {
1225
+ result.forEach((item) => {
1226
+ if (!isNaN(parseFloat(item))) {
1227
+ newResult = [...newResult, parseFloat(item)];
1228
+ }
1229
+ });
1230
+ }
1231
+ return Math.min(...newResult);
1232
+ } else {
1233
+ result[0].forEach((item: any) => {
1234
+ if (!isNaN(parseFloat(item))) {
1235
+ newResult = [...newResult, parseFloat(item)];
1236
+ }
1237
+ });
1238
+ return Math.min(...newResult);
1239
+ }
1240
+ }
1241
+ /**
1242
+ * 获取随机的安卓手机User-Agent
1243
+ * @example
1244
+ * Utils.getRandomAndroidUA();
1245
+ * > 'Mozilla/5.0 (Linux; Android 10; MI 13 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.3490.40 Mobile Safari/537.36'
1246
+ **/
1247
+ getRandomAndroidUA(): string;
1248
+ getRandomAndroidUA(): string {
1249
+ let UtilsContext = this;
1250
+ let mobileNameList = [
1251
+ "LDN-LX3",
1252
+ "RNE-L03",
1253
+ "ASUS_X00ID Build/NMF26F",
1254
+ "WAS-LX3",
1255
+ "PRA-LX3",
1256
+ "MYA-L03",
1257
+ "Moto G Play",
1258
+ "Moto C Build/NRD90M.063",
1259
+ "Redmi Note 4 Build/NRD90M",
1260
+ "HUAWEI VNS-L21 Build/HUAWEIVNS-L21",
1261
+ "VTR-L09",
1262
+ "TRT-LX3",
1263
+ "M2003J15SC Build/RP1A.200720.011; wv",
1264
+ "MI 13 Build/OPR1.170623.027; wv",
1265
+ ];
1266
+ let androidVersion = UtilsContext.getRandomValue(12, 14);
1267
+ let randomMobile = UtilsContext.getRandomValue(mobileNameList);
1268
+ let chromeVersion1 = UtilsContext.getRandomValue(115, 125);
1269
+ let chromeVersion2 = UtilsContext.getRandomValue(0, 0);
1270
+ let chromeVersion3 = UtilsContext.getRandomValue(2272, 6099);
1271
+ let chromeVersion4 = UtilsContext.getRandomValue(1, 218);
1272
+ return `Mozilla/5.0 (Linux; Android ${androidVersion}; ${randomMobile}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion1}.${chromeVersion2}.${chromeVersion3}.${chromeVersion4} Mobile Safari/537.36`;
1273
+ }
1274
+ /**
1275
+ * 获取随机值
1276
+ * @example
1277
+ * Utils.getRandomValue(1,9,6,99)
1278
+ * > 6
1279
+ */
1280
+ getRandomValue<T extends any>(...args: T[]): T;
1281
+ /**
1282
+ * 获取随机值
1283
+ * @example
1284
+ * Utils.getRandomValue([1,2,3])
1285
+ * > 3
1286
+ * @example
1287
+ * Utils.getRandomValue({1:"结果1",2:"结果2",3:"结果3"}})
1288
+ * > 结果2
1289
+ */
1290
+ getRandomValue<T extends any>(val: T[] | UtilsNestedObjectWithToString<T>): T;
1291
+ /**
1292
+ * 获取两个数之间随机值
1293
+ * @example
1294
+ * Utils.getRandomValue(1,9)
1295
+ * > 6
1296
+ */
1297
+ getRandomValue(val_1: number, val_2: number): number;
1298
+ /**
1299
+ * 获取随机值
1300
+ * @example
1301
+ * Utils.getRandomValue({1:1},{2:2})
1302
+ * > {1: 1}
1303
+ */
1304
+ getRandomValue<T extends any>(
1305
+ val_1: UtilsNestedObjectWithToString<T>,
1306
+ val_2: UtilsNestedObjectWithToString<T>
1307
+ ): T;
1308
+ getRandomValue(...args: any[]): any {
1309
+ let result = [...args];
1310
+ if (result.length > 1) {
1311
+ if (
1312
+ result.length === 2 &&
1313
+ typeof result[0] === "number" &&
1314
+ typeof result[1] === "number"
1315
+ ) {
1316
+ let leftNumber = result[0] > result[1] ? result[1] : result[0];
1317
+ let rightNumber = result[0] > result[1] ? result[0] : result[1];
1318
+ return (
1319
+ Math.round(Math.random() * (rightNumber - leftNumber)) + leftNumber
1320
+ );
1321
+ } else {
1322
+ return result[Math.floor(Math.random() * result.length)];
1323
+ }
1324
+ } else if (result.length === 1) {
1325
+ let paramData = result[0];
1326
+ if (Array.isArray(paramData)) {
1327
+ return paramData[Math.floor(Math.random() * paramData.length)];
1328
+ } else if (
1329
+ typeof paramData === "object" &&
1330
+ Object.keys(paramData).length > 0
1331
+ ) {
1332
+ let paramObjDataKey =
1333
+ Object.keys(paramData)[
1334
+ Math.floor(Math.random() * Object.keys(paramData).length)
1335
+ ];
1336
+ return paramData[paramObjDataKey];
1337
+ } else {
1338
+ return paramData;
1339
+ }
1340
+ }
1341
+ }
1342
+ /**
1343
+ * 获取随机的电脑端User-Agent
1344
+ * + Mozilla/5.0:以前用于Netscape浏览器,目前大多数浏览器UA都会带有
1345
+ * + Windows NT 13:代表Window11系统
1346
+ * + Windows NT 10.0:代表Window10系统
1347
+ * + Windows NT 6.1:代表windows7系统
1348
+ * + WOW64:Windows-on-Windows 64-bit,32位的应用程序运行于此64位处理器上
1349
+ * + Win64:64位
1350
+ * + AppleWebKit/537.36:浏览器内核
1351
+ * + KHTML:HTML排版引擎
1352
+ * + like Gecko:这不是Geckeo 浏览器,但是运行起来像Geckeo浏览器
1353
+ * + Chrome/106.0.5068.19:Chrome版本号
1354
+ * + Safari/537.36:宣称自己是Safari?
1355
+ * @returns 返回随机字符串
1356
+ * @example
1357
+ * Utils.getRandomPCUA();
1358
+ * > 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.5068.19 Safari/537.36'
1359
+ **/
1360
+ getRandomPCUA(): string {
1361
+ let UtilsContext = this;
1362
+ let chromeVersion1 = UtilsContext.getRandomValue(115, 126);
1363
+ let chromeVersion2 = UtilsContext.getRandomValue(0, 0);
1364
+ let chromeVersion3 = UtilsContext.getRandomValue(2272, 6099);
1365
+ let chromeVersion4 = UtilsContext.getRandomValue(1, 218);
1366
+ return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion1}.${chromeVersion2}.${chromeVersion3}.${chromeVersion4} Safari/537.36`;
1367
+ }
1368
+ /**
1369
+ * 获取元素上的使用React框架的实例属性,目前包括reactFiber、reactProps、reactEvents、reactEventHandlers、reactInternalInstance
1370
+ * @param element 需要获取的目标元素
1371
+ * @returns
1372
+ * @example
1373
+ * Utils.getReactObj(document.querySelector("input"))?.reactProps?.onChange({target:{value:"123"}});
1374
+ */
1375
+ getReactObj(element: HTMLElement | Element): {
1376
+ reactFiber?: AnyObject;
1377
+ reactProps?: AnyObject;
1378
+ reactEvents?: AnyObject;
1379
+ reactEventHandlers?: AnyObject;
1380
+ reactInternalInstance?: AnyObject;
1381
+ reactContainer?: AnyObject;
1382
+ } {
1383
+ let result = {};
1384
+ Object.keys(element).forEach((domPropsName) => {
1385
+ if (domPropsName.startsWith("__react")) {
1386
+ let propsName = domPropsName.replace(/__(.+)\$.+/i, "$1");
1387
+ if (propsName in result) {
1388
+ new Error("重复属性 " + domPropsName);
1389
+ } else {
1390
+ (result as any)[propsName] = (element as any)[domPropsName];
1391
+ }
1392
+ }
1393
+ });
1394
+ return result;
1395
+ }
1396
+ /**
1397
+ * 获取对象上的Symbol属性,如果没设置keyName,那么返回一个对象,对象是所有遍历到的Symbol对象
1398
+ * @param target 目标对象
1399
+ * @param keyName (可选)Symbol名或者Symbol对象
1400
+ */
1401
+ getSymbol(target: any, keyName?: string | symbol) {
1402
+ if (typeof target !== "object") {
1403
+ throw new TypeError("target不是一个对象");
1404
+ }
1405
+ let objectsSymbols = Object.getOwnPropertySymbols(target);
1406
+ if (typeof keyName === "string") {
1407
+ let findSymbol = objectsSymbols.find((key) => {
1408
+ return key.toString() === keyName;
1409
+ });
1410
+ if (findSymbol) {
1411
+ return target[findSymbol];
1412
+ }
1413
+ } else if (typeof keyName === "symbol") {
1414
+ let findSymbol = objectsSymbols.find((key) => {
1415
+ return key === keyName;
1416
+ });
1417
+ if (findSymbol) {
1418
+ return (target as any)[findSymbol];
1419
+ }
1420
+ } else {
1421
+ let result = {};
1422
+ objectsSymbols.forEach((item) => {
1423
+ (result as any)[item] = target[item];
1424
+ });
1425
+ return result;
1426
+ }
1427
+ }
1428
+ /**
1429
+ * 获取文本的字符长度
1430
+ * @param text
1431
+ * @example
1432
+ * Utils.getTextLength("测试文本")
1433
+ * > 12
1434
+ */
1435
+ getTextLength(text: string): number {
1436
+ let encoder = new TextEncoder();
1437
+ let bytes = encoder.encode(text);
1438
+ return bytes.length;
1439
+ }
1440
+ /**
1441
+ * 获取文本占据的空间大小,返回自动的单位,如12 Kb,14 K,20 MB,1 GB
1442
+ * @param text 目标字符串
1443
+ * @param addType (可选)是否添加单位
1444
+ * + true (默认) 自动添加单位
1445
+ * + false 不添加单位
1446
+ * @example
1447
+ * Utils.getTextStorageSize("测试文本");
1448
+ * > '12.00B'
1449
+ */
1450
+ getTextStorageSize<T extends boolean>(
1451
+ text: string,
1452
+ addType?: T
1453
+ ): T extends true ? string : number;
1454
+ getTextStorageSize(text: string, addType = true) {
1455
+ let UtilsContext = this;
1456
+ return UtilsContext.formatByteToSize(
1457
+ UtilsContext.getTextLength(text),
1458
+ addType
1459
+ );
1460
+ }
1461
+ /**
1462
+ * 获取迅雷协议的Url
1463
+ * @param url Url链接或者其它信息
1464
+ */
1465
+ getThunderUrl(url: string): string;
1466
+ getThunderUrl(url: string): string {
1467
+ if (url == null) {
1468
+ throw new TypeError("url不能为空");
1469
+ }
1470
+ if (typeof url !== "string") {
1471
+ throw new TypeError("url必须是string类型");
1472
+ }
1473
+ if (url.trim() === "") {
1474
+ throw new TypeError("url不能为空字符串或纯空格");
1475
+ }
1476
+ return `thunder://${globalThis.btoa("AA" + url + "ZZ")}`;
1477
+ }
1478
+ /**
1479
+ * 对于GM_cookie的兼容写法,当无法使用GM_cookie时可以使用这个,但是并不完全兼容,有些写不出来且限制了httponly是无法访问的
1480
+ * @example
1481
+ let GM_cookie = new Utils.GM_Cookie();
1482
+ GM_cookie.list({name:"xxx_cookie_xxx"},function(cookies,error){
1483
+ if (!error) {
1484
+ console.log(cookies);
1485
+ console.log(cookies.value);
1486
+ } else {
1487
+ console.error(error);
1488
+ }
1489
+ });
1490
+ GM_cookie.set({name:"xxx_cookie_test_xxx",value:"这是Cookie测试值"},function(error){
1491
+ if (error) {
1492
+ console.error(error);
1493
+ } else {
1494
+ console.log('Cookie set successfully.');
1495
+ }
1496
+ })
1497
+ GM_cookie.delete({name:"xxx_cookie_test_xxx"},function(error){
1498
+ if (error) {
1499
+ console.error(error);
1500
+ } else {
1501
+ console.log('Cookie set successfully.');
1502
+ }
1503
+ })
1504
+ **/
1505
+ GM_Cookie = UtilsGMCookie;
1506
+ /**
1507
+ * 注册油猴菜单,要求本地存储的键名不能存在其它键名`GM_Menu_Local_Map`会冲突/覆盖
1508
+ * @example
1509
+ let GM_Menu = new Utils.GM_Menu({
1510
+ data: [
1511
+ {
1512
+ menu_key: "menu_key",
1513
+ text: "测试按钮",
1514
+ enable: true,
1515
+ accessKey: "a",
1516
+ autoClose: false,
1517
+ showText(text, enable) {
1518
+ return "[" + (enable ? "√" : "×") + "]" + text;
1519
+ },
1520
+ callback(data) {
1521
+ console.log("点击菜单,值修改为", data.enable);
1522
+ },
1523
+ },
1524
+ ],
1525
+ autoReload: false,
1526
+ GM_getValue,
1527
+ GM_setValue,
1528
+ GM_registerMenuCommand,
1529
+ GM_unregisterMenuCommand,
1530
+ });
1531
+
1532
+
1533
+ // 获取某个菜单项的值
1534
+ GM_Menu.get("menu_key");
1535
+ > true
1536
+
1537
+ // 获取某个菜单项的开启/关闭后显示的文本
1538
+ GM_Menu.getShowTextValue("menu_key");
1539
+ > √测试按钮
1540
+
1541
+ // 添加键为menu_key2的菜单项
1542
+ GM_Menu.add({
1543
+ key:"menu_key2",
1544
+ text: "测试按钮2",
1545
+ enable: false,
1546
+ showText(text,enable){
1547
+ return "[" + (enable ? "√" : "×") + "]" + text;
1548
+ },
1549
+ callback(data){
1550
+ console.log("点击菜单,值修改为",data.enable);
1551
+ }
1552
+ });
1553
+ // 使用数组的方式添加多个菜单,如menu_key3、menu_key4
1554
+ GM_Menu.add([
1555
+ {
1556
+ key:"menu_key3",
1557
+ text: "测试按钮3",
1558
+ enable: false,
1559
+ showText(text,enable){
1560
+ return "[" + (enable ? "√" : "×") + "]" + text;
1561
+ },
1562
+ callback(data){
1563
+ console.log("点击菜单,值修改为",data.enable);
1564
+ }
1565
+ },
1566
+ {
1567
+ key:"menu_key4",
1568
+ text: "测试按钮4",
1569
+ enable: false,
1570
+ showText(text,enable){
1571
+ return "[" + (enable ? "√" : "×") + "]" + text;
1572
+ },
1573
+ callback(data){
1574
+ console.log("点击菜单,值修改为",data.enable);
1575
+ }
1576
+ }
1577
+ ]);
1578
+
1579
+ // 更新键为menu_key的显示文字和点击回调
1580
+ GM_Menu.update({
1581
+ menu_key:{
1582
+ text: "更新后的测试按钮",
1583
+ enable: true,
1584
+ showText(text,enable){
1585
+ return "[" + (enable ? "√" : "×") + "]" + text;
1586
+ },
1587
+ callback(data){
1588
+ console.log("点击菜单更新后的测试按钮,新值修改为",data.enable);
1589
+ }
1590
+ }
1591
+ });
1592
+
1593
+ // 删除键为menu_key的菜单
1594
+ GM_Menu.delete("menu_key");
1595
+ **/
1596
+ GM_Menu: UtilsGMMenu = GMMenu as any;
1597
+ /**
1598
+ * 基于Function prototype,能够勾住和释放任何函数
1599
+ *
1600
+ * .hook
1601
+ * + realFunc {string} 用于保存原始函数的函数名称,用于unHook
1602
+ * + hookFunc {string} 替换的hook函数
1603
+ * + context {object} 目标函数所在对象,用于hook非window对象下的函数,如String.protype.slice,carInstance1
1604
+ * + methodName {string} 匿名函数需显式传入目标函数名eg:this.Begin = function(){....};}
1605
+ *
1606
+ * .unhook
1607
+ * + realFunc {string} 用于保存原始函数的函数名称,用于unHook
1608
+ * + funcName {string} 被Hook的函数名称
1609
+ * + context {object} 目标函数所在对象,用于hook非window对象下的函数,如String.protype.slice,carInstance1
1610
+ * @example
1611
+ let hook = new Utils.Hooks();
1612
+ hook.initEnv();
1613
+ function myFunction(){
1614
+ console.log("我自己需要执行的函数");
1615
+ }
1616
+ function testFunction(){
1617
+ console.log("正常执行的函数");
1618
+ }
1619
+ testFunction.hook(testFunction,myFunction,window);
1620
+ **/
1621
+ Hooks: UtilsHooks = Hooks;
1622
+
1623
+ /**
1624
+ * 为减少代码量和回调,把GM_xmlhttpRequest封装
1625
+ * 文档地址: https://www.tampermonkey.net/documentation.php?ext=iikm
1626
+ * 其中onloadstart、onprogress、onreadystatechange是回调形式,onabort、ontimeout、onerror可以设置全局回调函数
1627
+ * @param _GM_xmlHttpRequest_ 油猴中的GM_xmlhttpRequest
1628
+ * @example
1629
+ let httpx = new Utils.Httpx(GM_xmlhttpRequest);
1630
+ let postResp = await httpx.post({
1631
+ url:url,
1632
+ data:JSON.stringify({
1633
+ test:1
1634
+ }),
1635
+ timeout: 5000
1636
+ });
1637
+ console.log(postResp);
1638
+ > {
1639
+ status: true,
1640
+ data: {responseText: "...", response: xxx,...},
1641
+ msg: "请求完毕",
1642
+ type: "onload",
1643
+ }
1644
+
1645
+ if(postResp === "onload" && postResp.status){
1646
+ // onload
1647
+ }else if(postResp === "ontimeout"){
1648
+ // ontimeout
1649
+ }
1650
+ * @example
1651
+ // 也可以先配置全局参数
1652
+ let httpx = new Utils.Httpx(GM_xmlhttpRequest);
1653
+ httpx.config({
1654
+ timeout: 5000,
1655
+ async: false,
1656
+ responseType: "html",
1657
+ redirect: "follow",
1658
+ })
1659
+ // 优先级为 默认details < 全局details < 单独的details
1660
+ */
1661
+ Httpx: UtilsHttpx = Httpx;
1662
+ /**
1663
+ * 浏览器端的indexedDB操作封装
1664
+ * @example
1665
+ let db = new Utils.indexedDB('web_DB', 'nav_text')
1666
+ let data = {name:'管理员', roleId: 1, type: 1};
1667
+ db.save('list',data).then((resolve)=>{
1668
+ console.log(resolve,'存储成功')
1669
+ })
1670
+
1671
+ db.get('list').then((resolve)=>{
1672
+ console.log(resolve,'查询成功')
1673
+ })
1674
+
1675
+ db.getPaging('list',20,10).then((resolve)=>{
1676
+ console.log(resolve,'查询分页偏移第20,一共10行成功');
1677
+ })
1678
+
1679
+ db.delete('list').then(resolve=>{
1680
+ console.log(resolve,'删除成功---->>>>>>name')
1681
+ })
1682
+
1683
+ db.deleteAll().then(resolve=>{
1684
+ console.log(resolve,'清除数据库---->>>>>>name')
1685
+ })
1686
+ **/
1687
+ indexedDB: UtilsIndexedDB = indexedDB;
1688
+ /**
1689
+ * 判断目标函数是否是Native Code
1690
+ * @param target
1691
+ * @returns
1692
+ * + true 是Native
1693
+ * + false 不是Native
1694
+ * @example
1695
+ * Utils.isNativeFunc(window.location.assign)
1696
+ * > true
1697
+ */
1698
+ isNativeFunc(target: Function): boolean;
1699
+ isNativeFunc(target: Function): boolean {
1700
+ return Boolean(
1701
+ target.toString().match(/^function .*\(\) { \[native code\] }$/)
1702
+ );
1703
+ }
1704
+ /**
1705
+ * 判断当前的位置是否位于页面底部附近
1706
+ * @param nearValue (可选)判断在页面底部的误差值,默认:50
1707
+ * @returns
1708
+ * + true 在底部附近
1709
+ * + false 不在底部附近
1710
+ */
1711
+ isNearBottom(nearValue?: number): boolean;
1712
+ isNearBottom(nearValue: number = 50): boolean {
1713
+ var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
1714
+ var windowHeight =
1715
+ window.innerHeight || document.documentElement.clientHeight;
1716
+ var documentHeight = document.documentElement.scrollHeight;
1717
+ return scrollTop + windowHeight >= documentHeight - nearValue;
1718
+ }
1719
+ /**
1720
+ * 判断对象是否是元素
1721
+ * @param target
1722
+ * @returns
1723
+ * + true 是元素
1724
+ * + false 不是元素
1725
+ * @example
1726
+ * Utils.isDOM(document.querySelector("a"))
1727
+ * > true
1728
+ */
1729
+ isDOM(target: any): boolean;
1730
+ isDOM(target: any): boolean {
1731
+ return target instanceof Node;
1732
+ }
1733
+ /**
1734
+ * 判断浏览器是否支持全屏
1735
+ */
1736
+ isFullscreenEnabled(): boolean;
1737
+ isFullscreenEnabled(): boolean {
1738
+ return !!(
1739
+ (UtilsCore.document as any).fullscreenEnabled ||
1740
+ (UtilsCore.document as any).webkitFullScreenEnabled ||
1741
+ (UtilsCore.document as any).mozFullScreenEnabled ||
1742
+ (UtilsCore.document as any).msFullScreenEnabled
1743
+ );
1744
+ }
1745
+ /**
1746
+ * 判断对象是否是jQuery对象
1747
+ * @param target
1748
+ * @returns
1749
+ * + true 是jQuery对象
1750
+ * + false 不是jQuery对象
1751
+ * @example
1752
+ * Utils.isJQuery($("a"))
1753
+ * > true
1754
+ */
1755
+ isJQuery(target: any): boolean;
1756
+ isJQuery(target: any): boolean {
1757
+ let result = false;
1758
+ // @ts-ignore
1759
+ if (typeof jQuery === "object" && target instanceof jQuery) {
1760
+ result = true;
1761
+ }
1762
+ if (target == null) {
1763
+ return false;
1764
+ }
1765
+ if (typeof target === "object") {
1766
+ /* 也有种可能,这个jQuery对象是1.8.3版本的,页面中的jQuery是3.4.1版本的 */
1767
+ let jQueryProps = [
1768
+ "add",
1769
+ "addBack",
1770
+ "addClass",
1771
+ "after",
1772
+ "ajaxComplete",
1773
+ "ajaxError",
1774
+ "ajaxSend",
1775
+ "ajaxStart",
1776
+ "ajaxStop",
1777
+ "ajaxSuccess",
1778
+ "animate",
1779
+ "append",
1780
+ "appendTo",
1781
+ "attr",
1782
+ "before",
1783
+ "bind",
1784
+ "blur",
1785
+ "change",
1786
+ "children",
1787
+ "clearQueue",
1788
+ "click",
1789
+ "clone",
1790
+ "closest",
1791
+ "constructor",
1792
+ "contents",
1793
+ "contextmenu",
1794
+ "css",
1795
+ "data",
1796
+ "dblclick",
1797
+ "delay",
1798
+ "delegate",
1799
+ "dequeue",
1800
+ "each",
1801
+ "empty",
1802
+ "end",
1803
+ "eq",
1804
+ "extend",
1805
+ "fadeIn",
1806
+ "fadeOut",
1807
+ "fadeTo",
1808
+ "fadeToggle",
1809
+ "filter",
1810
+ "find",
1811
+ "first",
1812
+ "focus",
1813
+ "focusin",
1814
+ "focusout",
1815
+ "get",
1816
+ "has",
1817
+ "hasClass",
1818
+ "height",
1819
+ "hide",
1820
+ "hover",
1821
+ "html",
1822
+ "index",
1823
+ "init",
1824
+ "innerHeight",
1825
+ "innerWidth",
1826
+ "insertAfter",
1827
+ "insertBefore",
1828
+ "is",
1829
+ "jquery",
1830
+ "keydown",
1831
+ "keypress",
1832
+ "keyup",
1833
+ "last",
1834
+ "load",
1835
+ "map",
1836
+ "mousedown",
1837
+ "mouseenter",
1838
+ "mouseleave",
1839
+ "mousemove",
1840
+ "mouseout",
1841
+ "mouseover",
1842
+ "mouseup",
1843
+ "next",
1844
+ "nextAll",
1845
+ "not",
1846
+ "off",
1847
+ "offset",
1848
+ "offsetParent",
1849
+ "on",
1850
+ "one",
1851
+ "outerHeight",
1852
+ "outerWidth",
1853
+ "parent",
1854
+ "parents",
1855
+ "position",
1856
+ "prepend",
1857
+ "prependTo",
1858
+ "prev",
1859
+ "prevAll",
1860
+ "prevUntil",
1861
+ "promise",
1862
+ "prop",
1863
+ "pushStack",
1864
+ "queue",
1865
+ "ready",
1866
+ "remove",
1867
+ "removeAttr",
1868
+ "removeClass",
1869
+ "removeData",
1870
+ "removeProp",
1871
+ "replaceAll",
1872
+ "replaceWith",
1873
+ "resize",
1874
+ "scroll",
1875
+ "scrollLeft",
1876
+ "scrollTop",
1877
+ "select",
1878
+ "show",
1879
+ "siblings",
1880
+ "slice",
1881
+ "slideDown",
1882
+ "slideToggle",
1883
+ "slideUp",
1884
+ "sort",
1885
+ "splice",
1886
+ "text",
1887
+ "toArray",
1888
+ "toggle",
1889
+ "toggleClass",
1890
+ "trigger",
1891
+ "triggerHandler",
1892
+ "unbind",
1893
+ "width",
1894
+ "wrap",
1895
+ ];
1896
+ for (const jQueryPropsName of jQueryProps) {
1897
+ if (!(jQueryPropsName in target)) {
1898
+ result = false;
1899
+ /* console.log(jQueryPropsName); */
1900
+ break;
1901
+ } else {
1902
+ result = true;
1903
+ }
1904
+ }
1905
+ }
1906
+ return result;
1907
+ }
1908
+ /**
1909
+ * 判断当前设备是否是移动端
1910
+ * @param userAgent (可选)UA字符串,默认使用当前的navigator.userAgent
1911
+ * @returns
1912
+ * + true 是移动端
1913
+ * + false 不是移动端
1914
+ * @example
1915
+ * Utils.isPhone();
1916
+ * > true
1917
+ **/
1918
+ isPhone(userAgent?: string): boolean;
1919
+ isPhone(userAgent: string = navigator.userAgent): boolean {
1920
+ return Boolean(/(iPhone|iPad|iPod|iOS|Android|Mobile)/i.test(userAgent));
1921
+ }
1922
+ /**
1923
+ * 判断传递的字符串是否是由相同的字符组成
1924
+ * @param targetStr 需要判断的字符串,长度(.length)需要≥2
1925
+ * @param coefficient 系数(默认:1),某个字符重复的系数大于它那么就是返回true,默认全部
1926
+ */
1927
+ isSameChars(targetStr: string, coefficient?: number): boolean;
1928
+ isSameChars(targetStr: string, coefficient: number = 1): boolean {
1929
+ if (typeof targetStr !== "string") {
1930
+ throw new TypeError("参数 str 必须是 string 类型");
1931
+ }
1932
+ if (targetStr.length < 2) {
1933
+ return false;
1934
+ }
1935
+ targetStr = targetStr.toLowerCase();
1936
+ const targetCharMap: UtilsNestedObjectWithToString<string> = {};
1937
+ let targetStrLength = 0;
1938
+ for (const char of targetStr) {
1939
+ if (Reflect.has(targetCharMap, char)) {
1940
+ targetCharMap[char]++;
1941
+ } else {
1942
+ targetCharMap[char] = 1;
1943
+ }
1944
+ targetStrLength++;
1945
+ }
1946
+ let result = false;
1947
+ for (const char in targetCharMap) {
1948
+ if (targetCharMap[char] / targetStrLength >= coefficient) {
1949
+ result = true;
1950
+ break;
1951
+ }
1952
+ }
1953
+ return result;
1954
+ }
1955
+ /**
1956
+ * 判断对象是否不为空
1957
+ * @returns {boolean}
1958
+ * + true 不为空
1959
+ * + false 为空
1960
+ * @example
1961
+ * Utils.isNotNull("123");
1962
+ * > true
1963
+ */
1964
+ isNotNull(...args: any[]): boolean;
1965
+ isNotNull(...args: any[]): boolean {
1966
+ let UtilsContext = this;
1967
+ return !UtilsContext.isNull.apply(this, args);
1968
+ }
1969
+ /**
1970
+ * 判断对象或数据是否为空
1971
+ * + `String`判空的值,如 ""、"null"、"undefined"、" "
1972
+ * + `Number`判空的值,如 0
1973
+ * + `Object`判空的值,如 {}、null、undefined
1974
+ * + `Array`(存在属性Symbol.iterator)判空的值,如 []
1975
+ * + `Boolean`判空的值,如false
1976
+ * + `Function`判空的值,如()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){}
1977
+ * @returns
1978
+ * + true 为空
1979
+ * + false 不为空
1980
+ * @example
1981
+ Utils.isNull({});
1982
+ > true
1983
+ * @example
1984
+ Utils.isNull([]);
1985
+ > true
1986
+ * @example
1987
+ Utils.isNull(" ");
1988
+ > true
1989
+ * @example
1990
+ Utils.isNull(function(){});
1991
+ > true
1992
+ * @example
1993
+ Utils.isNull(()=>{}));
1994
+ > true
1995
+ * @example
1996
+ Utils.isNull("undefined");
1997
+ > true
1998
+ * @example
1999
+ Utils.isNull("null");
2000
+ > true
2001
+ * @example
2002
+ Utils.isNull(" ", false);
2003
+ > true
2004
+ * @example
2005
+ Utils.isNull([1],[]);
2006
+ > false
2007
+ * @example
2008
+ Utils.isNull([],[1]);
2009
+ > false
2010
+ * @example
2011
+ Utils.isNull(false,[123]);
2012
+ > false
2013
+ **/
2014
+ isNull(...args: any[]): boolean;
2015
+ isNull(...args: any[]): boolean {
2016
+ let result = true;
2017
+ let checkList = [...args];
2018
+ for (const objItem of checkList) {
2019
+ let itemResult = false;
2020
+ if (objItem === null || objItem === undefined) {
2021
+ itemResult = true;
2022
+ } else {
2023
+ switch (typeof objItem) {
2024
+ case "object":
2025
+ if (typeof objItem[Symbol.iterator] === "function") {
2026
+ /* 可迭代 */
2027
+ itemResult = objItem.length === 0;
2028
+ } else {
2029
+ itemResult = Object.keys(objItem).length === 0;
2030
+ }
2031
+ break;
2032
+ case "number":
2033
+ itemResult = objItem === 0;
2034
+ break;
2035
+ case "string":
2036
+ itemResult =
2037
+ objItem.trim() === "" ||
2038
+ objItem === "null" ||
2039
+ objItem === "undefined";
2040
+ break;
2041
+ case "boolean":
2042
+ itemResult = !objItem;
2043
+ break;
2044
+ case "function":
2045
+ let funcStr = objItem.toString().replace(/\s/g, "");
2046
+ /* 排除()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){} */
2047
+ itemResult = Boolean(
2048
+ funcStr.match(/^\(.*?\)=>\{\}$|^function.*?\(.*?\)\{\}$/)
2049
+ );
2050
+ break;
2051
+ }
2052
+ }
2053
+ result = result && itemResult;
2054
+ }
2055
+
2056
+ return result;
2057
+ }
2058
+
2059
+ /**
2060
+ * 判断浏览器主题是否是暗黑|深色模式
2061
+ */
2062
+ isThemeDark(): boolean;
2063
+ isThemeDark(): boolean {
2064
+ return globalThis.matchMedia("(prefers-color-scheme: dark)").matches;
2065
+ }
2066
+ /**
2067
+ * 判断元素是否在页面中可见
2068
+ * @param element 需要检查的元素,可以是普通元素|数组形式的元素|通过querySelectorAll获取的元素数组
2069
+ * @param inView
2070
+ * + true 在窗口可视区域
2071
+ * + false 不在窗口可视区域
2072
+ * @returns
2073
+ * + true 可见
2074
+ * + false 不可见
2075
+ * @example
2076
+ * Utils.isVisible(document.documentElement)
2077
+ * > true
2078
+ */
2079
+ isVisible(element: HTMLElement[] | NodeList, inView?: boolean): boolean;
2080
+ isVisible(
2081
+ element: HTMLElement[] | NodeList,
2082
+ inView: boolean = false
2083
+ ): boolean {
2084
+ let needCheckDomList = [];
2085
+ if (element instanceof Array || element instanceof NodeList) {
2086
+ element = element as HTMLElement[];
2087
+ needCheckDomList = [...element];
2088
+ } else {
2089
+ needCheckDomList = [element];
2090
+ }
2091
+ let result = true;
2092
+ for (const domItem of needCheckDomList) {
2093
+ let domDisplay = window.getComputedStyle(domItem);
2094
+ if (domDisplay.display === "none") {
2095
+ result = false;
2096
+ } else {
2097
+ let domClientRect = domItem.getBoundingClientRect();
2098
+ if (inView) {
2099
+ let viewportWidth =
2100
+ window.innerWidth || document.documentElement.clientWidth;
2101
+ let viewportHeight =
2102
+ window.innerHeight || document.documentElement.clientHeight;
2103
+ result = !(
2104
+ domClientRect.right < 0 ||
2105
+ domClientRect.left > viewportWidth ||
2106
+ domClientRect.bottom < 0 ||
2107
+ domClientRect.top > viewportHeight
2108
+ );
2109
+ } else {
2110
+ result = Boolean(domItem.getClientRects().length);
2111
+ }
2112
+ }
2113
+ if (!result) {
2114
+ /* 有一个不可见就退出循环 */
2115
+ break;
2116
+ }
2117
+ }
2118
+ return result;
2119
+ }
2120
+
2121
+ /**
2122
+ * 判断是否是Via浏览器环境
2123
+ * @returns
2124
+ * + true 是Via
2125
+ * + false 不是Via
2126
+ * @example
2127
+ * Utils.isWebView_Via()
2128
+ * > false
2129
+ */
2130
+ isWebView_Via(): boolean;
2131
+ isWebView_Via(): boolean {
2132
+ let result = true;
2133
+ let UtilsContext = this;
2134
+ if (typeof (UtilsCore.top.window as any).via === "object") {
2135
+ for (const key in Object.values((UtilsCore.top.window as any).via)) {
2136
+ if (Reflect.has((UtilsCore.top.window as any).via, key)) {
2137
+ let objValueFunc = (UtilsCore.top.window as any).via[key];
2138
+ if (
2139
+ typeof objValueFunc === "function" &&
2140
+ UtilsContext.isNativeFunc(objValueFunc)
2141
+ ) {
2142
+ result = true;
2143
+ } else {
2144
+ result = false;
2145
+ break;
2146
+ }
2147
+ }
2148
+ }
2149
+ } else {
2150
+ result = false;
2151
+ }
2152
+ return result;
2153
+ }
2154
+ /**
2155
+ * 判断是否是X浏览器环境
2156
+ * @returns
2157
+ * + true 是X浏览器
2158
+ * + false 不是X浏览器
2159
+ * @example
2160
+ * Utils.isWebView_X()
2161
+ * > false
2162
+ */
2163
+ isWebView_X(): boolean;
2164
+ isWebView_X(): boolean {
2165
+ let result = true;
2166
+ let UtilsContext = this;
2167
+ if (typeof (UtilsCore.top.window as any).mbrowser === "object") {
2168
+ for (const key in Object.values((UtilsCore.top.window as any).mbrowser)) {
2169
+ if (Reflect.has((UtilsCore.top.window as any).mbrowser, key)) {
2170
+ let objValueFunc = (UtilsCore.top.window as any).mbrowser[key];
2171
+ if (
2172
+ typeof objValueFunc === "function" &&
2173
+ UtilsContext.isNativeFunc(objValueFunc)
2174
+ ) {
2175
+ result = true;
2176
+ } else {
2177
+ result = false;
2178
+ break;
2179
+ }
2180
+ }
2181
+ }
2182
+ } else {
2183
+ result = false;
2184
+ }
2185
+ return result;
2186
+ }
2187
+ /**
2188
+ * 把对象内的value值全部取出成数组
2189
+ * @param target 目标对象
2190
+ * @returns 返回数组
2191
+ * @example
2192
+ * Utils.parseObjectToArray({"工具类":"jsonToArray","return","Array"});
2193
+ * > ['jsonToArray', 'Array']
2194
+ **/
2195
+ parseObjectToArray(target: AnyObject): any;
2196
+ parseObjectToArray(target: AnyObject): any {
2197
+ if (typeof target !== "object") {
2198
+ throw new Error(
2199
+ "Utils.parseObjectToArray 参数 target 必须为 object 类型"
2200
+ );
2201
+ }
2202
+ let result: any[] = [];
2203
+ Object.keys(target).forEach(function (keyName) {
2204
+ result = result.concat(target[keyName]);
2205
+ });
2206
+ return result;
2207
+ }
2208
+ /**
2209
+ * 监听某个元素键盘按键事件或window全局按键事件
2210
+ * 按下有值的键时触发,按下Ctrl\Alt\Shift\Meta是无值键。按下先触发keydown事件,再触发keypress事件。
2211
+ * @param target 需要监听的对象,可以是全局Window或者某个元素
2212
+ * @param eventName 事件名,默认keypress
2213
+ * @param callback 自己定义的回调事件,参数1为当前的key,参数2为组合按键,数组类型,包含ctrl、shift、alt和meta(win键或mac的cmd键)
2214
+ * @example
2215
+ Utils.listenKeyboard(window,(keyName,keyValue,otherKey,event)=>{
2216
+ if(keyName === "Enter"){
2217
+ console.log("回车按键的值是:"+keyValue)
2218
+ }
2219
+ if(otherKey.indexOf("ctrl") && keyName === "Enter" ){
2220
+ console.log("Ctrl和回车键");
2221
+ }
2222
+ })
2223
+ * @example
2224
+ 字母和数字键的键码值(keyCode)
2225
+ 按键 键码 按键 键码 按键 键码 按键 键码
2226
+ A 65 J 74 S 83 1 49
2227
+ B 66 K 75 T 84 2 50
2228
+ C 67 L 76 U 85 3 51
2229
+ D 68 M 77 V 86 4 52
2230
+ E 69 N 78 W 87 5 53
2231
+ F 70 O 79 X 88 6 54
2232
+ G 71 P 80 Y 89 7 55
2233
+ H 72 Q 81 Z 90 8 56
2234
+ I 73 R 82 0 48 9 57
2235
+
2236
+ 数字键盘上的键的键码值(keyCode)
2237
+ 功能键键码值(keyCode)
2238
+ 按键 键码 按键 键码 按键 键码 按键 键码
2239
+ 0 96 8 104 F1 112 F7 118
2240
+ 1 97 9 105 F2 113 F8 119
2241
+ 2 98 * 106 F3 114 F9 120
2242
+ 3 99 + 107 F4 115 F10 121
2243
+ 4 100 Enter 108 F5 116 F11 122
2244
+ 5 101 - 109 F6 117 F12 123
2245
+ 6 102 . 110
2246
+ 7 103 / 111
2247
+
2248
+ 控制键键码值(keyCode)
2249
+ 按键 键码 按键 键码 按键 键码 按键 键码
2250
+ BackSpace 8 Esc 27 → 39 -_ 189
2251
+ Tab 9 Spacebar 32 ↓ 40 .> 190
2252
+ Clear 12 Page Up 33 Insert 45 /? 191
2253
+ Enter 13 Page Down 34 Delete 46 `~ 192
2254
+ Shift 16 End 35 Num Lock 144 [{ 219
2255
+ Control 17 Home 36 ;: 186 \| 220
2256
+ Alt 18 ← 37 =+ 187 ]} 221
2257
+ Cape Lock 20 ↑ 38 ,< 188 '" 222
2258
+
2259
+ 多媒体键码值(keyCode)
2260
+ 按键 键码
2261
+ 音量加 175
2262
+ 音量减 174
2263
+ 停止 179
2264
+ 静音 173
2265
+ 浏览器 172
2266
+ 邮件 180
2267
+ 搜索 170
2268
+ 收藏 171
2269
+ **/
2270
+ listenKeyboard(
2271
+ target: Window | Node | HTMLElement | typeof globalThis,
2272
+ eventName: "keyup" | "keypress" | "keydown",
2273
+ callback: (
2274
+ keyName: string,
2275
+ keyValue: string,
2276
+ otherCodeList: string[],
2277
+ event: KeyboardEvent
2278
+ ) => void
2279
+ ): {
2280
+ removeListen(): void;
2281
+ };
2282
+ listenKeyboard(
2283
+ target: Window | Node | HTMLElement | typeof globalThis,
2284
+ eventName: "keyup" | "keypress" | "keydown" = "keypress",
2285
+ callback: (
2286
+ keyName: string,
2287
+ keyValue: string,
2288
+ otherCodeList: string[],
2289
+ event: KeyboardEvent
2290
+ ) => void
2291
+ ): {
2292
+ removeListen(): void;
2293
+ } {
2294
+ if (
2295
+ typeof target !== "object" ||
2296
+ (typeof target["addEventListener"] !== "function" &&
2297
+ typeof target["removeEventListener"] !== "function")
2298
+ ) {
2299
+ throw new Error(
2300
+ "Utils.listenKeyboard 参数 target 必须为 Window|HTMLElement 类型"
2301
+ );
2302
+ }
2303
+ let keyEvent = function (event: KeyboardEvent) {
2304
+ let keyName = event.key || event.code;
2305
+ let keyValue = event.charCode || event.keyCode || event.which;
2306
+ let otherCodeList = [];
2307
+ if (event.ctrlKey) {
2308
+ otherCodeList.push("ctrl");
2309
+ }
2310
+ if (event.altKey) {
2311
+ otherCodeList.push("alt");
2312
+ }
2313
+ if (event.metaKey) {
2314
+ otherCodeList.push("meta");
2315
+ }
2316
+ if (event.shiftKey) {
2317
+ otherCodeList.push("shift");
2318
+ }
2319
+ if (typeof callback === "function") {
2320
+ callback(keyName, keyValue.toString(), otherCodeList, event);
2321
+ }
2322
+ };
2323
+ target.addEventListener(eventName, keyEvent as any);
2324
+ return {
2325
+ removeListen() {
2326
+ target.removeEventListener(eventName, keyEvent as any);
2327
+ },
2328
+ };
2329
+ }
2330
+ /**
2331
+ * 自动锁对象,用于循环判断运行的函数,在循环外new后使用,注意,如果函数内部存在异步操作,需要使用await
2332
+ * @example
2333
+ let lock = new Utils.LockFunction(()=>{console.log(1)}))
2334
+ lock.run();
2335
+ > 1
2336
+ * @example
2337
+ let lock = new Utils.LockFunction(()=>{console.log(1)}),true) -- 异步操作
2338
+ await lock.run();
2339
+ > 1
2340
+ **/
2341
+ LockFunction: UtilsLockFunction = LockFunction;
2342
+ /**
2343
+ * 日志对象
2344
+ * @param _GM_info_ 油猴管理器的API GM_info,或者是一个对象,如{"script":{name:"Utils.Log"}}
2345
+ * @example
2346
+ let log = new Utils.Log(GM_info);
2347
+ log.info("普通输出");
2348
+ > 普通输出
2349
+
2350
+ log.success("成功输出");
2351
+ > 成功输出
2352
+
2353
+ log.error("错误输出");
2354
+ > 错误输出
2355
+
2356
+ log.warn("警告输出");
2357
+ > 警告输出
2358
+
2359
+ log.tag = "自定义tag信息";
2360
+ log.info("自定义info的颜色","#e0e0e0");
2361
+ > 自定义info的颜色
2362
+
2363
+ log.config({
2364
+ successColor: "#31dc02",
2365
+ errorColor: "#e02d2d",
2366
+ infoColor: "black",
2367
+ })
2368
+ log.success("颜色为#31dc02");
2369
+ > 颜色为#31dc02
2370
+ */
2371
+ Log: UtilsLog = Log;
2372
+ /**
2373
+ * 合并数组内的JSON的值字符串
2374
+ * @param data 需要合并的数组
2375
+ * @param handleFunc 处理的函数|JSON的key
2376
+ * @example
2377
+ * Utils.mergeArrayToString([{"name":"数组内数据部分字段合并成字符串->"},{"name":"mergeToString"}],(item)=>{return item["name"]});
2378
+ * > '数组内数据部分字段合并成字符串->mergeToString'
2379
+ **/
2380
+ mergeArrayToString(data: any[], handleFunc?: (val: any) => any): string;
2381
+ mergeArrayToString(data: any[], handleFunc?: (val: any) => any): string {
2382
+ if (!(data instanceof Array)) {
2383
+ throw new Error("Utils.mergeArrayToString 参数 data 必须为 Array 类型");
2384
+ }
2385
+ let content = "";
2386
+ if (typeof handleFunc === "function") {
2387
+ data.forEach((item) => {
2388
+ content += handleFunc(item);
2389
+ });
2390
+ } else if (typeof handleFunc === "string") {
2391
+ data.forEach((item) => {
2392
+ content += item[handleFunc];
2393
+ });
2394
+ } else {
2395
+ data.forEach((item) => {
2396
+ Object.values(item)
2397
+ .filter((item2) => typeof item2 === "string")
2398
+ .forEach((item3) => {
2399
+ content += item3;
2400
+ });
2401
+ });
2402
+ }
2403
+ return content;
2404
+ }
2405
+ /**
2406
+ * 监听页面元素改变并处理
2407
+ * @param target 需要监听的元素,如果不存在,可以等待它出现
2408
+ * @param observer_config MutationObserver的配置
2409
+ * @example
2410
+ Utils.mutationObserver(document.querySelector("div.xxxx"),{
2411
+ "callback":(mutations, observer)=>{},
2412
+ "config":{childList:true,attributes:true}
2413
+ });
2414
+ * @example
2415
+ Utils.mutationObserver(document.querySelectorAll("div.xxxx"),{
2416
+ "callback":(mutations, observer)=>{},
2417
+ "config":{childList:true,attributes:true}}
2418
+ );
2419
+ * @example
2420
+ Utils.mutationObserver($("div.xxxx"),{
2421
+ "callback":(mutations, observer)=>{},
2422
+ "config":{childList:true,attributes:true}}
2423
+ );
2424
+ **/
2425
+ mutationObserver(
2426
+ target: HTMLElement | Node | NodeList | Document,
2427
+ observer_config: {
2428
+ config?: MutationObserverInit;
2429
+ callback: MutationCallback;
2430
+ }
2431
+ ): MutationObserver;
2432
+ mutationObserver(
2433
+ target: HTMLElement | Node | NodeList | Document,
2434
+ observer_config: {
2435
+ config?: MutationObserverInit;
2436
+ callback: MutationCallback;
2437
+ }
2438
+ ): MutationObserver {
2439
+ let UtilsContext = this;
2440
+ if (
2441
+ !(target instanceof Node) &&
2442
+ !(target instanceof NodeList) &&
2443
+ !UtilsContext.isJQuery(target)
2444
+ ) {
2445
+ throw new Error(
2446
+ "Utils.mutationObserver 参数 target 必须为 Node|NodeList|jQuery类型"
2447
+ );
2448
+ }
2449
+
2450
+ let default_obverser_config = {
2451
+ /* 监听到元素有反馈,需执行的函数 */
2452
+ callback: () => {},
2453
+ config: {
2454
+ /**
2455
+ * @type {boolean|undefined}
2456
+ * + true 监听以 target 为根节点的整个子树。包括子树中所有节点的属性,而不仅仅是针对 target
2457
+ * + false (默认) 不生效
2458
+ */
2459
+ subtree: void 0,
2460
+ /**
2461
+ * @type {boolean|undefined}
2462
+ * + true 监听 target 节点中发生的节点的新增与删除(同时,如果 subtree 为 true,会针对整个子树生效)
2463
+ * + false (默认) 不生效
2464
+ */
2465
+ childList: void 0,
2466
+ /**
2467
+ * @type {boolean|undefined}
2468
+ * + true 观察所有监听的节点属性值的变化。默认值为 true,当声明了 attributeFilter 或 attributeOldValue
2469
+ * + false (默认) 不生效
2470
+ */
2471
+ attributes: void 0,
2472
+ /**
2473
+ * 一个用于声明哪些属性名会被监听的数组。如果不声明该属性,所有属性的变化都将触发通知
2474
+ * @type {[...string]|undefined}
2475
+ */
2476
+ attributeFilter: void 0,
2477
+ /**
2478
+ * @type {boolean|undefined}
2479
+ * + true 记录上一次被监听的节点的属性变化;可查阅 MutationObserver 中的 Monitoring attribute values 了解关于观察属性变化和属性值记录的详情
2480
+ * + false (默认) 不生效
2481
+ */
2482
+ attributeOldValue: void 0,
2483
+ /**
2484
+ * @type {boolean|undefined}
2485
+ * + true 监听声明的 target 节点上所有字符的变化。默认值为 true,如果声明了 characterDataOldValue
2486
+ * + false (默认) 不生效
2487
+ */
2488
+ characterData: void 0,
2489
+ /**
2490
+ * @type {boolean|undefined}
2491
+ * + true 记录前一个被监听的节点中发生的文本变化
2492
+ * + false (默认) 不生效
2493
+ */
2494
+ characterDataOldValue: void 0,
2495
+ },
2496
+ };
2497
+ observer_config = UtilsContext.assign(
2498
+ default_obverser_config,
2499
+ observer_config
2500
+ );
2501
+ let MutationObserver =
2502
+ (UtilsCore.window as any).MutationObserver ||
2503
+ (UtilsCore.window as any).webkitMutationObserver ||
2504
+ (UtilsCore.window as any).MozMutationObserver;
2505
+ /** @type {MutationObserver} */
2506
+ let mutationObserver = new MutationObserver(function (
2507
+ mutations: MutationRecord[],
2508
+ observer: MutationObserver
2509
+ ) {
2510
+ observer_config?.callback(mutations, observer);
2511
+ });
2512
+ if (target instanceof Node) {
2513
+ /* 传入的参数是节点元素 */
2514
+ mutationObserver.observe(target, observer_config.config);
2515
+ } else if (target instanceof NodeList) {
2516
+ /* 传入的参数是节点元素数组 */
2517
+ target.forEach((item) => {
2518
+ mutationObserver.observe(item, observer_config.config);
2519
+ });
2520
+ } else if (UtilsContext.isJQuery(target)) {
2521
+ /* 传入的参数是jQuery对象 */
2522
+ (target as any).each((index: any, item: any) => {
2523
+ mutationObserver.observe(item, observer_config.config);
2524
+ });
2525
+ } else {
2526
+ /* 未知 */
2527
+ console.error("Utils.mutationObserver 未知参数", arguments);
2528
+ }
2529
+ return mutationObserver;
2530
+ }
2531
+ /**
2532
+ * 去除全局window下的Utils,返回控制权
2533
+ * @example
2534
+ * let utils = Utils.noConflict();
2535
+ * > ...
2536
+ */
2537
+ noConflict = function () {
2538
+ if ((UtilsCore.window as any).Utils) {
2539
+ Reflect.deleteProperty(UtilsCore.window as any, "Utils");
2540
+ }
2541
+ (UtilsCore.window as any).Utils = utils;
2542
+ return utils;
2543
+ };
2544
+ /**
2545
+ * 恢复/释放该对象内的为function,让它无效/有效
2546
+ * @param needReleaseObject 需要操作的对象
2547
+ * @param needReleaseName 需要操作的对象的名字
2548
+ * @param functionNameList (可选)需要释放的方法,默认:全部方法
2549
+ * @param release (可选)
2550
+ * + true (默认) 释放该对象下的某些方法
2551
+ * + false 恢复该对象下的某些方法
2552
+ * @example
2553
+ // 释放该方法
2554
+ Utils.noConflictFunc(console,"console",["log"],true);
2555
+ console.log;
2556
+ > () => {}
2557
+
2558
+ * @example
2559
+ // 恢复该方法
2560
+ Utils.noConflictFunc(console,"console",["log"],false);
2561
+ console.log;
2562
+ > ƒ log() { [native code] }
2563
+
2564
+ * @example
2565
+ // 释放所有方法
2566
+ Utils.noConflictFunc(console,"console",[],true);
2567
+ console.debug;
2568
+ > () => {}
2569
+
2570
+ * @example
2571
+ // 恢复所有方法
2572
+ Utils.noConflictFunc(console,"console",[],false);
2573
+ console.debug;
2574
+ > ƒ log() { [native code] }
2575
+ **/
2576
+ noConflictFunc(
2577
+ needReleaseObject: object,
2578
+ needReleaseName: string,
2579
+ functionNameList?: any[],
2580
+ release?: boolean
2581
+ ): void;
2582
+ noConflictFunc(
2583
+ needReleaseObject: object,
2584
+ needReleaseName: string,
2585
+ functionNameList: any[] = [],
2586
+ release: boolean = true
2587
+ ): void {
2588
+ let UtilsContext = this;
2589
+ if (typeof needReleaseObject !== "object") {
2590
+ throw new Error(
2591
+ "Utils.noConflictFunc 参数 needReleaseObject 必须为 object 类型"
2592
+ );
2593
+ }
2594
+ if (typeof needReleaseName !== "string") {
2595
+ throw new Error(
2596
+ "Utils.noConflictFunc 参数 needReleaseName 必须为 string 类型"
2597
+ );
2598
+ }
2599
+ if (!Array.isArray(functionNameList)) {
2600
+ throw new Error(
2601
+ "Utils.noConflictFunc 参数 functionNameList 必须为 Array 类型"
2602
+ );
2603
+ }
2604
+ let needReleaseKey = "__" + needReleaseName;
2605
+ /**
2606
+ * 释放所有
2607
+ */
2608
+ function releaseAll() {
2609
+ if (typeof (UtilsCore.window as any)[needReleaseKey] !== "undefined") {
2610
+ /* 已存在 */
2611
+ return;
2612
+ }
2613
+ (UtilsCore.window as any)[needReleaseKey] =
2614
+ UtilsContext.deepClone(needReleaseObject);
2615
+ Object.values(needReleaseObject).forEach((value) => {
2616
+ if (typeof value === "function") {
2617
+ (needReleaseObject as any)[value.name] = () => {};
2618
+ }
2619
+ });
2620
+ }
2621
+ /**
2622
+ * 释放单个
2623
+ */
2624
+ function releaseOne() {
2625
+ Array.from(functionNameList).forEach((item) => {
2626
+ Object.values(needReleaseObject).forEach((value) => {
2627
+ if (typeof value === "function") {
2628
+ if (
2629
+ typeof (UtilsCore.window as any)[needReleaseKey] === "undefined"
2630
+ ) {
2631
+ (UtilsCore.window as any)[needReleaseKey] = {};
2632
+ }
2633
+ if (item === value.name) {
2634
+ (UtilsCore.window as any)[needReleaseKey][value.name] = (
2635
+ needReleaseObject as any
2636
+ )[value.name];
2637
+ (needReleaseObject as any)[value.name] = () => {};
2638
+ }
2639
+ }
2640
+ });
2641
+ });
2642
+ }
2643
+ /**
2644
+ * 恢复所有
2645
+ */
2646
+ function recoveryAll() {
2647
+ if (typeof (UtilsCore.window as any)[needReleaseKey] === "undefined") {
2648
+ /* 未存在 */
2649
+ return;
2650
+ }
2651
+ Object.assign(
2652
+ needReleaseObject,
2653
+ (UtilsCore.window as any)[needReleaseKey]
2654
+ );
2655
+ Reflect.deleteProperty(UtilsCore.window as any, "needReleaseKey");
2656
+ }
2657
+
2658
+ /**
2659
+ * 恢复单个
2660
+ */
2661
+ function recoveryOne() {
2662
+ if (typeof (UtilsCore.window as any)[needReleaseKey] === "undefined") {
2663
+ /* 未存在 */
2664
+ return;
2665
+ }
2666
+ Array.from(functionNameList).forEach((item) => {
2667
+ if ((UtilsCore.window as any)[needReleaseKey][item]) {
2668
+ (needReleaseObject as any)[item] = (UtilsCore.window as any)[
2669
+ needReleaseKey
2670
+ ][item];
2671
+ Reflect.deleteProperty(
2672
+ (UtilsCore.window as any)[needReleaseKey],
2673
+ item
2674
+ );
2675
+ if (
2676
+ Object.keys((UtilsCore.window as any)[needReleaseKey]).length === 0
2677
+ ) {
2678
+ Reflect.deleteProperty(window, needReleaseKey);
2679
+ }
2680
+ }
2681
+ });
2682
+ }
2683
+ if (release) {
2684
+ /* 释放 */
2685
+ if (functionNameList.length === 0) {
2686
+ releaseAll();
2687
+ } else {
2688
+ /* 对单个进行操作 */
2689
+ releaseOne();
2690
+ }
2691
+ } else {
2692
+ /* 恢复 */
2693
+ if (functionNameList.length === 0) {
2694
+ recoveryAll();
2695
+ } else {
2696
+ /* 对单个进行操作 */
2697
+ recoveryOne();
2698
+ }
2699
+ }
2700
+ }
2701
+ /**
2702
+ * base64转blob
2703
+ * @param dataUri base64的数据
2704
+ * @returns blob的链接
2705
+ * @example
2706
+ * Utils.parseBase64ToBlob("data:image/jpeg;base64,.....");
2707
+ * > blob://xxxxxxx
2708
+ **/
2709
+ parseBase64ToBlob(dataUri: string): Blob;
2710
+ parseBase64ToBlob(dataUri: string): Blob {
2711
+ if (typeof dataUri !== "string") {
2712
+ throw new Error(
2713
+ "Utils.parseBase64ToBlob 参数 dataUri 必须为 string 类型"
2714
+ );
2715
+ }
2716
+ let dataUriSplit = dataUri.split(","),
2717
+ dataUriMime = (dataUriSplit[0] as any).match(/:(.*?);/)[1],
2718
+ dataUriBase64Str = atob(dataUriSplit[1]),
2719
+ dataUriLength = dataUriBase64Str.length,
2720
+ u8arr = new Uint8Array(dataUriLength);
2721
+ while (dataUriLength--) {
2722
+ u8arr[dataUriLength] = dataUriBase64Str.charCodeAt(dataUriLength);
2723
+ }
2724
+ return new Blob([u8arr], {
2725
+ type: dataUriMime,
2726
+ });
2727
+ }
2728
+ /**
2729
+ * base64转File对象
2730
+ * @param dataUri base64的数据
2731
+ * @param fileName (可选)文件名,默认:example
2732
+ * @returns blob的链接
2733
+ * @example
2734
+ * Utils.parseBase64ToFile("data:image/jpeg;base64,.....","测试文件");
2735
+ * > object
2736
+ **/
2737
+ parseBase64ToFile(dataUri: string, fileName?: string): File;
2738
+ parseBase64ToFile(dataUri: string, fileName = "example") {
2739
+ if (typeof dataUri !== "string") {
2740
+ throw new Error(
2741
+ "Utils.parseBase64ToFile 参数 dataUri 必须为 string 类型"
2742
+ );
2743
+ }
2744
+ if (typeof fileName !== "string") {
2745
+ throw new Error(
2746
+ "Utils.parseBase64ToFile 参数 fileName 必须为 string 类型"
2747
+ );
2748
+ }
2749
+ let dataUriSplit = dataUri.split(","),
2750
+ dataUriMime = (dataUriSplit[0] as any).match(/:(.*?);/)[1],
2751
+ dataUriBase64Str = atob(dataUriSplit[1]),
2752
+ dataUriLength = dataUriBase64Str.length,
2753
+ u8arr = new Uint8Array(dataUriLength);
2754
+ while (dataUriLength--) {
2755
+ u8arr[dataUriLength] = dataUriBase64Str.charCodeAt(dataUriLength);
2756
+ }
2757
+ return new File([u8arr], fileName, {
2758
+ type: dataUriMime,
2759
+ });
2760
+ }
2761
+ /**
2762
+ * 将正则匹配到的结果取出最后一个值并转换成int格式
2763
+ * @param matchList 正则匹配的列表
2764
+ * @param defaultValue 正则匹配的列表为空时,或者正则匹配的列表最后一项不为Int,返回该默认值0
2765
+ * @example
2766
+ * Utils.parseInt(["dadaadada123124","123124"],0);
2767
+ * > 123124
2768
+ *
2769
+ * @example
2770
+ * Utils.parseInt(null,0);
2771
+ * > 0
2772
+ * @example
2773
+ * Utils.parseInt(["aaaaaa"]);
2774
+ * > 0
2775
+ *
2776
+ * @example
2777
+ * Utils.parseInt(["aaaaaa"],"66");
2778
+ * > 66
2779
+ *
2780
+ * @example
2781
+ * Utils.parseInt(["aaaaaaa"],"aa");
2782
+ * > NaN
2783
+ **/
2784
+ parseInt(matchList?: any[], defaultValue?: number): number;
2785
+ parseInt(matchList: any[] = [], defaultValue = 0): number {
2786
+ if (matchList == null) {
2787
+ return parseInt(defaultValue.toString());
2788
+ }
2789
+ let parseValue = parseInt(matchList[matchList.length - 1]);
2790
+ if (isNaN(parseValue)) {
2791
+ parseValue = parseInt(defaultValue.toString());
2792
+ }
2793
+ return parseValue;
2794
+ }
2795
+ /**
2796
+ * blob转File对象
2797
+ * @param blobUrl 需要转换的blob的链接
2798
+ * @param fileName (可选)转换成的File对象的文件名称,默认:example
2799
+ * @example
2800
+ * Utils.parseBlobToFile("blob://xxxxx");
2801
+ * > object
2802
+ **/
2803
+ parseBlobToFile(blobUrl: string, fileName?: string): Promise<File | Error>;
2804
+ async parseBlobToFile(
2805
+ blobUrl: string,
2806
+ fileName: string = "example"
2807
+ ): Promise<File | Error> {
2808
+ return new Promise((resolve, reject) => {
2809
+ fetch(blobUrl)
2810
+ .then((response) => response.blob())
2811
+ .then((blob) => {
2812
+ const file = new File([blob], fileName, { type: blob.type });
2813
+ resolve(file);
2814
+ })
2815
+ .catch((error) => {
2816
+ console.error("Error:", error);
2817
+ reject(error);
2818
+ });
2819
+ });
2820
+ }
2821
+ /**
2822
+ * 解析CDATA格式的内容字符串
2823
+ * @param text 传入CDATA字符串
2824
+ * @returns 返回解析出的内容
2825
+ * @example
2826
+ * let xml = "<root><![CDATA[This is some CDATA content.]]></root>";
2827
+ * console.log(Utils.parseCDATA(xml));
2828
+ * > This is some CDATA content.
2829
+ */
2830
+ parseCDATA(text: string): string;
2831
+ parseCDATA(text: string = ""): string {
2832
+ let result = "";
2833
+ let cdataRegexp = /<\!\[CDATA\[([\s\S]*)\]\]>/;
2834
+ let cdataMatch = cdataRegexp.exec(text.trim());
2835
+ if (cdataMatch && cdataMatch.length > 1) {
2836
+ result = cdataMatch[cdataMatch.length - 1];
2837
+ }
2838
+ return result;
2839
+ }
2840
+ /**
2841
+ * 【异步函数】File对象转base64
2842
+ * @param fileObj 需要转换的File对象
2843
+ * @example
2844
+ * await Utils.parseFileToBase64(object);
2845
+ * > 'data:image/jpeg:base64/,xxxxxx'
2846
+ **/
2847
+ parseFileToBase64(fileObj: File): Promise<string>;
2848
+ async parseFileToBase64(fileObj: File): Promise<string> {
2849
+ let reader = new FileReader();
2850
+ reader.readAsDataURL(fileObj);
2851
+ return new Promise((resolve) => {
2852
+ reader.onload = function (event: any) {
2853
+ resolve(event.target.result as string);
2854
+ };
2855
+ });
2856
+ }
2857
+ /**
2858
+ * 解析字符串
2859
+ * @param text 要解析的 DOMString。它必须包含 HTML、xml、xhtml+xml 或 svg 文档。
2860
+ * @param mimeType (可选)解析成的类型
2861
+ * + (默认)text/html
2862
+ * + text/xml
2863
+ * + application/xml
2864
+ * + application/xhtml+xml
2865
+ * + image/svg+xml
2866
+ * @example
2867
+ * Utils.parseFromString("<p>123<p>");
2868
+ * > #document
2869
+ */
2870
+ parseFromString(
2871
+ text: string,
2872
+ mimeType?:
2873
+ | "text/html"
2874
+ | "text/xml"
2875
+ | "application/xml"
2876
+ | "application/xhtml+xml"
2877
+ | "image/svg+xml"
2878
+ ): HTMLElement | XMLDocument | SVGElement;
2879
+ parseFromString(
2880
+ text: string,
2881
+ mimeType:
2882
+ | "text/html"
2883
+ | "text/xml"
2884
+ | "application/xml"
2885
+ | "application/xhtml+xml"
2886
+ | "image/svg+xml" = "text/html"
2887
+ ): HTMLElement | XMLDocument | SVGElement {
2888
+ let parser = new DOMParser();
2889
+ return parser.parseFromString(text, mimeType);
2890
+ }
2891
+ /**
2892
+ * 将字符串进行正则转义
2893
+ * 例如:^替换$
2894
+ * 转换:\^替换\$
2895
+ */
2896
+ parseStringToRegExpString(text: string): string;
2897
+ parseStringToRegExpString(text: string): string {
2898
+ if (typeof text !== "string") {
2899
+ throw new TypeError("string必须是字符串");
2900
+ }
2901
+ let regString = text.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
2902
+ return regString;
2903
+ }
2904
+ /**
2905
+ * 阻止事件传递
2906
+ * @param element 要进行处理的元素
2907
+ * @param eventNameList (可选)要阻止的事件名|列表
2908
+ * @param capture (可选)是否捕获,默认false
2909
+ * @example
2910
+ * Utils.preventEvent(document.querySelector("a"),"click")
2911
+ * @example
2912
+ * Utils.preventEvent(event);
2913
+ */
2914
+ preventEvent(event: Event): boolean;
2915
+ /**
2916
+ * 阻止事件传递
2917
+ * @param element 要进行处理的元素
2918
+ * @param eventNameList (可选)要阻止的事件名|列表
2919
+ * @param capture (可选)是否捕获,默认false
2920
+ * @example
2921
+ * Utils.preventEvent(document.querySelector("a"),"click")
2922
+ * @example
2923
+ * Utils.preventEvent(event);
2924
+ */
2925
+ preventEvent(
2926
+ element: HTMLElement,
2927
+ eventNameList?: string | string[],
2928
+ capture?: boolean
2929
+ ): boolean;
2930
+ preventEvent(
2931
+ element: HTMLElement | Event,
2932
+ eventNameList: string | string[] = [],
2933
+ capture?: boolean
2934
+ ): boolean | undefined {
2935
+ function stopEvent(event: Event) {
2936
+ /* 阻止事件的默认行为发生。例如,当点击一个链接时,浏览器会默认打开链接的URL */
2937
+ event?.preventDefault();
2938
+ /* 停止事件的传播,阻止它继续向更上层的元素冒泡,事件将不会再传播给其他的元素 */
2939
+ event?.stopPropagation();
2940
+ /* 阻止事件传播,并且还能阻止元素上的其他事件处理程序被触发 */
2941
+ event?.stopImmediatePropagation();
2942
+ return false;
2943
+ }
2944
+ if (arguments.length === 1) {
2945
+ /* 直接阻止事件 */
2946
+ return stopEvent(arguments[0]);
2947
+ } else {
2948
+ /* 添加对应的事件来阻止触发 */
2949
+ if (typeof eventNameList === "string") {
2950
+ eventNameList = [eventNameList];
2951
+ }
2952
+ eventNameList.forEach((eventName) => {
2953
+ (element as HTMLElement).addEventListener(eventName, stopEvent, {
2954
+ capture: Boolean(capture),
2955
+ });
2956
+ });
2957
+ }
2958
+ }
2959
+ /**
2960
+ * 在canvas元素节点上绘制进度圆圈
2961
+ * @example
2962
+ let progress = new Utils.Process({canvasNode:document.querySelector("canvas")});
2963
+ progress.draw();
2964
+ * **/
2965
+ Progress: UtilsProgress = Progress;
2966
+ /**
2967
+ * 劫持Event的isTrust为true,注入时刻,ducument-start
2968
+ * @param isTrustValue (可选)让isTrusted为true
2969
+ * @param filter (可选)过滤出需要的事件名,true为需要,false为不需要
2970
+ * @example
2971
+ * Utils.registerTrustClickEvent()
2972
+ */
2973
+ registerTrustClickEvent(
2974
+ isTrustValue?: boolean,
2975
+ filter?: (typeName: string) => boolean
2976
+ ): void;
2977
+ registerTrustClickEvent(
2978
+ isTrustValue: boolean = true,
2979
+ filter?: (typeName: string) => boolean
2980
+ ): void {
2981
+ function trustEvent(event: Event) {
2982
+ return new Proxy(event, {
2983
+ get: function (target, property) {
2984
+ if (property === "isTrusted") {
2985
+ return isTrustValue;
2986
+ } else {
2987
+ return Reflect.get(target, property);
2988
+ }
2989
+ },
2990
+ });
2991
+ }
2992
+ if (filter == null) {
2993
+ filter = function (typeName) {
2994
+ return typeName === "click";
2995
+ };
2996
+ }
2997
+ const originalListener = EventTarget.prototype.addEventListener;
2998
+ EventTarget.prototype.addEventListener = function (...args) {
2999
+ let type = args[0];
3000
+ let callback = args[1];
3001
+ let options = args[2];
3002
+ if (filter(type)) {
3003
+ if (typeof callback === "function") {
3004
+ args[1] = function (event) {
3005
+ callback.call(this, trustEvent(event));
3006
+ };
3007
+ } else if (
3008
+ typeof callback === "object" &&
3009
+ "handleEvent" in (callback as any)
3010
+ ) {
3011
+ let oldHandleEvent = (callback as any)["handleEvent"];
3012
+
3013
+ (args[1] as any)["handleEvent"] = function (event: Event) {
3014
+ if (event == null) {
3015
+ return;
3016
+ }
3017
+ try {
3018
+ /* Proxy对象使用instanceof会报错 */
3019
+ event instanceof Proxy;
3020
+ oldHandleEvent.call(this, trustEvent(event));
3021
+ } catch (error) {
3022
+ // @ts-ignore
3023
+ event["isTrusted"] = isTrustValue;
3024
+ }
3025
+ };
3026
+ }
3027
+ }
3028
+ return originalListener.apply(this, args);
3029
+ };
3030
+ }
3031
+ /**
3032
+ * 将数字进行正/负转换
3033
+ * @param num 需要进行转换的数字
3034
+ */
3035
+ reverseNumber(num: number): number;
3036
+ reverseNumber(num: number): number {
3037
+ let reversedNum = 0;
3038
+ let isNegative = false;
3039
+
3040
+ if (num < 0) {
3041
+ isNegative = true;
3042
+ num = Math.abs(num);
3043
+ }
3044
+
3045
+ while (num > 0) {
3046
+ reversedNum = reversedNum * 10 + (num % 10);
3047
+ num = Math.floor(num / 10);
3048
+ }
3049
+
3050
+ return isNegative ? -reversedNum : reversedNum;
3051
+ }
3052
+ /**
3053
+ * 将元素上的文本或元素使用光标进行选中
3054
+ *
3055
+ * 注意,如果设置startIndex和endIndex,且元素上并无可选则的坐标,那么会报错
3056
+ * @param element 目标元素
3057
+ * @param childTextNode 目标元素下的#text元素
3058
+ * @param startIndex (可选)开始坐标,可为空
3059
+ * @param endIndex (可选)结束坐标,可为空
3060
+ */
3061
+ selectElementText(
3062
+ element: HTMLElement | Element | Node,
3063
+ childTextNode: ChildNode,
3064
+ startIndex?: number,
3065
+ endIndex?: number
3066
+ ): void;
3067
+ selectElementText(
3068
+ element: HTMLElement | Element | Node,
3069
+ childTextNode: ChildNode,
3070
+ startIndex?: number,
3071
+ endIndex?: number
3072
+ ): void {
3073
+ let range = document.createRange();
3074
+ range.selectNodeContents(element);
3075
+ if (childTextNode) {
3076
+ if (childTextNode.nodeType !== Node.TEXT_NODE) {
3077
+ throw new TypeError("childTextNode必须是#text元素");
3078
+ }
3079
+ if (startIndex != null && endIndex != null) {
3080
+ range.setStart(childTextNode, startIndex);
3081
+ range.setEnd(childTextNode, endIndex);
3082
+ }
3083
+ }
3084
+
3085
+ let selection = globalThis.getSelection();
3086
+ if (selection) {
3087
+ selection.removeAllRanges();
3088
+ selection.addRange(range);
3089
+ }
3090
+ }
3091
+ /**
3092
+ * 复制到剪贴板
3093
+ * @param data 需要复制到剪贴板的文本
3094
+ * @param info (可选)默认:text/plain
3095
+ * @example
3096
+ * Utils.setClip({1:2});
3097
+ * > {"1":2}
3098
+ * @example
3099
+ * Utils.setClip( ()=>{
3100
+ * console.log(1)
3101
+ * });
3102
+ * > ()=>{console.log(1)}
3103
+ * @example
3104
+ * Utils.setClip("xxxx");
3105
+ * > xxxx
3106
+ * @example
3107
+ * Utils.setClip("xxxx","html");
3108
+ * > xxxx
3109
+ * @example
3110
+ * Utils.setClip("xxxx","text/plain");
3111
+ * > xxxx
3112
+ **/
3113
+ setClip(
3114
+ data: any,
3115
+ info?:
3116
+ | {
3117
+ type: string;
3118
+ mimetype: string;
3119
+ }
3120
+ | string
3121
+ ): Promise<boolean>;
3122
+ setClip(
3123
+ data: any,
3124
+ info?:
3125
+ | {
3126
+ type: string;
3127
+ mimetype: string;
3128
+ }
3129
+ | string
3130
+ ): Promise<boolean> {
3131
+ if (typeof data === "object") {
3132
+ if (data instanceof Element) {
3133
+ data = data.outerHTML;
3134
+ } else {
3135
+ data = JSON.stringify(data);
3136
+ }
3137
+ } else if (typeof data !== "string") {
3138
+ data = data.toString();
3139
+ }
3140
+ let textType = typeof info === "object" ? info.type : (info as string);
3141
+ if (textType.includes("html")) {
3142
+ textType = "text/html";
3143
+ } else {
3144
+ textType = "text/plain";
3145
+ }
3146
+ class UtilsClipboard {
3147
+ #resolve;
3148
+ #copyData;
3149
+ #copyDataType;
3150
+ constructor(
3151
+ resolve: (value: boolean | PromiseLike<boolean>) => void,
3152
+ copyData: any,
3153
+ copyDataType: string
3154
+ ) {
3155
+ this.#resolve = resolve;
3156
+ this.#copyData = copyData;
3157
+ this.#copyDataType = copyDataType;
3158
+ }
3159
+ async init() {
3160
+ let copyStatus = false;
3161
+ let requestPermissionStatus = await this.requestClipboardPermission();
3162
+ if (
3163
+ this.hasClipboard() &&
3164
+ (this.hasClipboardWrite() || this.hasClipboardWriteText())
3165
+ ) {
3166
+ try {
3167
+ copyStatus = await this.copyDataByClipboard();
3168
+ } catch (error) {
3169
+ console.error("复制失败,使用第二种方式,error👉", error);
3170
+ copyStatus = this.copyTextByTextArea();
3171
+ }
3172
+ } else {
3173
+ copyStatus = this.copyTextByTextArea();
3174
+ }
3175
+ this.#resolve(copyStatus);
3176
+ this.destroy();
3177
+ }
3178
+ destroy() {
3179
+ // @ts-ignore
3180
+ this.#resolve = null;
3181
+ // @ts-ignore
3182
+ this.#copyData = null;
3183
+ // @ts-ignore
3184
+ this.#copyDataType = null;
3185
+ }
3186
+ isText() {
3187
+ return this.#copyDataType.includes("text");
3188
+ }
3189
+ hasClipboard() {
3190
+ return navigator?.clipboard != null;
3191
+ }
3192
+ hasClipboardWrite() {
3193
+ return navigator?.clipboard?.write != null;
3194
+ }
3195
+ hasClipboardWriteText() {
3196
+ return navigator?.clipboard?.writeText != null;
3197
+ }
3198
+ /**
3199
+ * 使用textarea和document.execCommand("copy")来复制文字
3200
+ */
3201
+ copyTextByTextArea() {
3202
+ try {
3203
+ let copyElement = document.createElement("textarea");
3204
+ copyElement.value = this.#copyData;
3205
+ copyElement.setAttribute("type", "text");
3206
+ copyElement.setAttribute("style", "opacity:0;position:absolute;");
3207
+ copyElement.setAttribute("readonly", "readonly");
3208
+ document.body.appendChild(copyElement);
3209
+ copyElement.select();
3210
+ document.execCommand("copy");
3211
+ document.body.removeChild(copyElement);
3212
+ return true;
3213
+ } catch (error) {
3214
+ console.error("复制失败,error👉", error);
3215
+ return false;
3216
+ }
3217
+ }
3218
+ /**
3219
+ * 申请剪贴板权限
3220
+ * @returns {Promise<boolean>}
3221
+ */
3222
+ requestClipboardPermission() {
3223
+ return new Promise((resolve, reject) => {
3224
+ if (navigator.permissions && navigator.permissions.query) {
3225
+ navigator.permissions
3226
+ .query({
3227
+ // @ts-ignore
3228
+ name: "clipboard-write",
3229
+ })
3230
+ .then((permissionStatus) => {
3231
+ resolve(true);
3232
+ })
3233
+ .catch(
3234
+ /** @param {TypeError} error */
3235
+ (error) => {
3236
+ console.error([
3237
+ "申请剪贴板权限失败,尝试直接写入👉",
3238
+ error.message ?? error.name ?? error.stack,
3239
+ ]);
3240
+ resolve(false);
3241
+ }
3242
+ );
3243
+ } else {
3244
+ resolve(false);
3245
+ }
3246
+ });
3247
+ }
3248
+ /**
3249
+ * 使用clipboard直接写入数据到剪贴板
3250
+ */
3251
+ copyDataByClipboard(): Promise<boolean> {
3252
+ return new Promise((resolve, reject) => {
3253
+ if (this.isText()) {
3254
+ /* 只复制文字 */
3255
+ navigator.clipboard
3256
+ .writeText(this.#copyData)
3257
+ .then(() => {
3258
+ resolve(true);
3259
+ })
3260
+ .catch((error) => {
3261
+ reject(error);
3262
+ });
3263
+ } else {
3264
+ /* 可复制对象 */
3265
+ let textBlob = new Blob([this.#copyData], {
3266
+ type: this.#copyDataType,
3267
+ });
3268
+ navigator.clipboard
3269
+ .write([
3270
+ new ClipboardItem({
3271
+ [this.#copyDataType]: textBlob,
3272
+ }),
3273
+ ])
3274
+ .then(() => {
3275
+ resolve(true);
3276
+ })
3277
+ .catch((error) => {
3278
+ reject(error);
3279
+ });
3280
+ }
3281
+ });
3282
+ }
3283
+ }
3284
+ return new Promise((resolve) => {
3285
+ const utilsClipboard = new UtilsClipboard(resolve, data, textType);
3286
+ if (document.hasFocus()) {
3287
+ utilsClipboard.init();
3288
+ } else {
3289
+ window.addEventListener(
3290
+ "focus",
3291
+ () => {
3292
+ utilsClipboard.init();
3293
+ },
3294
+ { once: true }
3295
+ );
3296
+ }
3297
+ });
3298
+ }
3299
+ /**
3300
+ * 【异步函数】等待N秒执行函数
3301
+ * @param callback 待执行的函数(字符串)
3302
+ * @param delayTime (可选)延时时间(ms),默认:0
3303
+ * @example
3304
+ * await Utils.setTimeout(()=>{}, 2500);
3305
+ * > ƒ tryCatchObj() {}
3306
+ * @example
3307
+ * await Utils.setTimeout("()=>{console.log(12345)}", 2500);
3308
+ * > ƒ tryCatchObj() {}
3309
+ **/
3310
+ setTimeout(callback: (() => void) | string, delayTime?: number): Promise<any>;
3311
+ setTimeout(
3312
+ callback: (() => void) | string,
3313
+ delayTime: number = 0
3314
+ ): Promise<any> {
3315
+ let UtilsContext = this;
3316
+ if (typeof callback !== "function" && typeof callback !== "string") {
3317
+ throw new TypeError(
3318
+ "Utils.setTimeout 参数 callback 必须为 function|string 类型"
3319
+ );
3320
+ }
3321
+ if (typeof delayTime !== "number") {
3322
+ throw new TypeError("Utils.setTimeout 参数 delayTime 必须为 number 类型");
3323
+ }
3324
+ return new Promise((resolve) => {
3325
+ setTimeout(() => {
3326
+ resolve(UtilsContext.tryCatch().run(callback));
3327
+ }, delayTime);
3328
+ });
3329
+ }
3330
+ /**
3331
+ * 【异步函数】延迟xxx毫秒
3332
+ * @param delayTime (可选)延时时间(ms),默认:0
3333
+ * @example
3334
+ * await Utils.sleep(2500)
3335
+ **/
3336
+ sleep(delayTime?: number): Promise<void>;
3337
+ sleep(delayTime: number = 0): Promise<void> {
3338
+ if (typeof delayTime !== "number") {
3339
+ throw new Error("Utils.sleep 参数 delayTime 必须为 number 类型");
3340
+ }
3341
+ return new Promise((resolve) => {
3342
+ setTimeout(() => {
3343
+ resolve(void 0);
3344
+ }, delayTime);
3345
+ });
3346
+ }
3347
+ /**
3348
+ * 向右拖动滑块
3349
+ * @param selector 选择器|元素
3350
+ * @param offsetX (可选)水平拖动长度,默认:window.innerWidth
3351
+ * @example
3352
+ * Utils.dragSlider("#xxxx");
3353
+ * @example
3354
+ * Utils.dragSlider("#xxxx",100);
3355
+ */
3356
+ dragSlider(selector: string | Element | Node, offsetX?: number): void;
3357
+ dragSlider(
3358
+ selector: string | Element | Node,
3359
+ offsetX: number = UtilsCore.window.innerWidth
3360
+ ): void {
3361
+ function initMouseEvent(
3362
+ eventName: string,
3363
+ offSetX: number,
3364
+ offSetY: number
3365
+ ) {
3366
+ let win = unsafeWindow || window;
3367
+ let mouseEvent = document.createEvent("MouseEvents");
3368
+ mouseEvent.initMouseEvent(
3369
+ eventName,
3370
+ true,
3371
+ true,
3372
+ win,
3373
+ 0,
3374
+ offSetX,
3375
+ offSetY,
3376
+ offSetX,
3377
+ offSetY,
3378
+ false,
3379
+ false,
3380
+ false,
3381
+ false,
3382
+ 0,
3383
+ null
3384
+ );
3385
+ return mouseEvent;
3386
+ }
3387
+ let sliderElement =
3388
+ typeof selector === "string"
3389
+ ? document.querySelector(selector)
3390
+ : selector;
3391
+ if (
3392
+ !(sliderElement instanceof Node) ||
3393
+ !(sliderElement instanceof Element)
3394
+ ) {
3395
+ throw new Error("Utils.dragSlider 参数selector 必须为Node/Element类型");
3396
+ }
3397
+ let rect = sliderElement.getBoundingClientRect(),
3398
+ x0 = rect.x || rect.left,
3399
+ y0 = rect.y || rect.top,
3400
+ x1 = x0 + offsetX,
3401
+ y1 = y0;
3402
+ sliderElement.dispatchEvent(initMouseEvent("mousedown", x0, y0));
3403
+ sliderElement.dispatchEvent(initMouseEvent("mousemove", x1, y1));
3404
+ sliderElement.dispatchEvent(initMouseEvent("mouseleave", x1, y1));
3405
+ sliderElement.dispatchEvent(initMouseEvent("mouseout", x1, y1));
3406
+ }
3407
+ /**
3408
+ * 使目标元素进入全屏
3409
+ * @param element (可选)目标元素,默认:document.documentElement
3410
+ * @param options (可选)配置,一般不用
3411
+ * @example
3412
+ * Utils.enterFullScreen();
3413
+ */
3414
+ enterFullScreen(element: HTMLElement, options?: FullscreenOptions): void;
3415
+ enterFullScreen(
3416
+ element: HTMLElement = UtilsCore.document.documentElement,
3417
+ options?: FullscreenOptions
3418
+ ): void {
3419
+ try {
3420
+ if (element.requestFullscreen) {
3421
+ element.requestFullscreen(options);
3422
+ } else if ((element as any).webkitRequestFullScreen) {
3423
+ (element as any).webkitRequestFullScreen();
3424
+ } else if ((element as any).mozRequestFullScreen) {
3425
+ (element as any).mozRequestFullScreen();
3426
+ } else if ((element as any).msRequestFullscreen) {
3427
+ (element as any).msRequestFullscreen();
3428
+ } else {
3429
+ throw new TypeError("该浏览器不支持全屏API");
3430
+ }
3431
+ } catch (err) {
3432
+ console.error(err);
3433
+ }
3434
+ }
3435
+ /**
3436
+ * 使浏览器退出全屏
3437
+ * @param element (可选)目标元素,默认:document.documentElement
3438
+ * @example
3439
+ * Utils.exitFullScreen();
3440
+ */
3441
+ exitFullScreen(element?: HTMLElement): Promise<void>;
3442
+ exitFullScreen(
3443
+ element: HTMLElement = document.documentElement
3444
+ ): Promise<void> {
3445
+ if (UtilsCore.document.exitFullscreen) {
3446
+ return UtilsCore.document.exitFullscreen();
3447
+ } else if ((UtilsCore.document as any).msExitFullscreen) {
3448
+ return (UtilsCore.document as any).msExitFullscreen();
3449
+ } else if ((UtilsCore.document as any).mozCancelFullScreen) {
3450
+ return (UtilsCore.document as any).mozCancelFullScreen();
3451
+ } else if ((UtilsCore.document as any).webkitCancelFullScreen) {
3452
+ return (UtilsCore.document as any).webkitCancelFullScreen();
3453
+ } else {
3454
+ return new Promise((resolve, reject) => {
3455
+ reject(new TypeError("该浏览器不支持全屏API"));
3456
+ });
3457
+ }
3458
+ }
3459
+ /**
3460
+ * 数组按照内部某个值的大小比对排序,如[{"time":"2022-1-1"},{"time":"2022-2-2"}]
3461
+ * @param data 数据|获取数据的方法
3462
+ * @param getPropertyValueFunc 数组内部项的某个属性的值的方法,参数为这个项
3463
+ * @param sortByDesc (可选)排序方式
3464
+ * + true (默认)倒序(值最大排第一个,如:6、5、4、3...)
3465
+ * + false 升序(值最小排第一个,如:1、2、3、4...)
3466
+ * @returns 返回比较排序完成的数组
3467
+ * @example
3468
+ * Utils.sortListByProperty([{"time":"2022-1-1"},{"time":"2022-2-2"}],(item)=>{return item["time"]})
3469
+ * > [{time: '2022-2-2'},{time: '2022-1-1'}]
3470
+ * @example
3471
+ * Utils.sortListByProperty([{"time":"2022-1-1"},{"time":"2022-2-2"}],(item)=>{return item["time"]},false)
3472
+ * > [{time: '2022-1-1'},{time: '2022-2-2'}]
3473
+ **/
3474
+ sortListByProperty<T extends any[] | NodeList>(
3475
+ data: T,
3476
+ getPropertyValueFunc: string | ((value: T) => any),
3477
+ sortByDesc?: boolean
3478
+ ): T;
3479
+ sortListByProperty<T extends any[] | NodeList>(
3480
+ data: T,
3481
+ getPropertyValueFunc: string | ((value: T) => any),
3482
+ sortByDesc: boolean = true
3483
+ ): T {
3484
+ let UtilsContext = this;
3485
+ if (
3486
+ typeof getPropertyValueFunc !== "function" &&
3487
+ typeof getPropertyValueFunc !== "string"
3488
+ ) {
3489
+ throw new Error(
3490
+ "Utils.sortListByProperty 参数 getPropertyValueFunc 必须为 function|string 类型"
3491
+ );
3492
+ }
3493
+ if (typeof sortByDesc !== "boolean") {
3494
+ throw new Error(
3495
+ "Utils.sortListByProperty 参数 sortByDesc 必须为 boolean 类型"
3496
+ );
3497
+ }
3498
+ let getObjValue = function (obj: any) {
3499
+ return typeof getPropertyValueFunc === "string"
3500
+ ? obj[getPropertyValueFunc]
3501
+ : getPropertyValueFunc(obj);
3502
+ };
3503
+ /**
3504
+ * 排序方法
3505
+ * @param {any} after_obj
3506
+ * @param {any} before_obj
3507
+ * @returns
3508
+ */
3509
+ let sortFunc = function (after_obj: any, before_obj: any) {
3510
+ let beforeValue = getObjValue(before_obj); /* 前 */
3511
+ let afterValue = getObjValue(after_obj); /* 后 */
3512
+ if (sortByDesc) {
3513
+ if (afterValue > beforeValue) {
3514
+ return -1;
3515
+ } else if (afterValue < beforeValue) {
3516
+ return 1;
3517
+ } else {
3518
+ return 0;
3519
+ }
3520
+ } else {
3521
+ if (afterValue < beforeValue) {
3522
+ return -1;
3523
+ } else if (afterValue > beforeValue) {
3524
+ return 1;
3525
+ } else {
3526
+ return 0;
3527
+ }
3528
+ }
3529
+ };
3530
+ /**
3531
+ * 排序元素方法
3532
+ * @param nodeList 元素列表
3533
+ * @param getNodeListFunc 获取元素列表的函数
3534
+ */
3535
+ let sortNodeFunc = function (
3536
+ nodeList: NodeListOf<HTMLElement>,
3537
+ getNodeListFunc: () => NodeListOf<HTMLElement>
3538
+ ) {
3539
+ let nodeListLength = nodeList.length;
3540
+ for (let i = 0; i < nodeListLength - 1; i++) {
3541
+ for (let j = 0; j < nodeListLength - 1 - i; j++) {
3542
+ let beforeNode = nodeList[j];
3543
+ let afterNode = nodeList[j + 1];
3544
+ let beforeValue = getObjValue(beforeNode); /* 前 */
3545
+ let afterValue = getObjValue(afterNode); /* 后 */
3546
+ if (
3547
+ (sortByDesc == true && beforeValue < afterValue) ||
3548
+ (sortByDesc == false && beforeValue > afterValue)
3549
+ ) {
3550
+ /* 升序/降序 */
3551
+ /* 相邻元素两两对比 */
3552
+ let temp = beforeNode.nextElementSibling;
3553
+ afterNode.after(beforeNode);
3554
+ if (temp == null) {
3555
+ /* 如果为空,那么是最后一个元素,使用append */
3556
+ (temp as any).parentNode.appendChild(afterNode);
3557
+ } else {
3558
+ /* 不为空,使用before */
3559
+ temp.before(afterNode);
3560
+ }
3561
+ nodeList = getNodeListFunc();
3562
+ }
3563
+ }
3564
+ }
3565
+ };
3566
+ let result = data;
3567
+ let getDataFunc = null;
3568
+ if (data instanceof Function) {
3569
+ getDataFunc = data;
3570
+ data = (data as any)();
3571
+ }
3572
+ if (Array.isArray(data)) {
3573
+ data.sort(sortFunc);
3574
+ } else if (data instanceof NodeList || UtilsContext.isJQuery(data)) {
3575
+ sortNodeFunc(data as any, getDataFunc as any);
3576
+ result = (getDataFunc as any)();
3577
+ } else {
3578
+ throw new Error(
3579
+ "Utils.sortListByProperty 参数 data 必须为 Array|NodeList|jQuery 类型"
3580
+ );
3581
+ }
3582
+ return result;
3583
+ }
3584
+ /**
3585
+ * 字符串转正则,用于把字符串中不规范的字符进行转义
3586
+ * @param targetString 需要进行转换的字符串
3587
+ * @param flags 正则标志
3588
+ */
3589
+ stringToRegular(
3590
+ targetString: string | RegExp,
3591
+ flags?: "g" | "i" | "m" | "u" | "y" | string
3592
+ ): RegExp;
3593
+ stringToRegular(
3594
+ targetString: string | RegExp,
3595
+ flags: "g" | "i" | "m" | "u" | "y" | string = "ig"
3596
+ ): RegExp {
3597
+ let reg;
3598
+ // @ts-ignore
3599
+ flags = flags.toLowerCase();
3600
+ if (typeof targetString === "string") {
3601
+ reg = new RegExp(
3602
+ targetString.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"),
3603
+ flags
3604
+ );
3605
+ } else if ((targetString as any) instanceof RegExp) {
3606
+ reg = targetString;
3607
+ } else {
3608
+ throw new Error(
3609
+ "Utils.stringToRegular 参数targetString必须是string|Regexp类型"
3610
+ );
3611
+ }
3612
+ return reg;
3613
+ }
3614
+ /**
3615
+ * 字符串首字母转大写
3616
+ * @param targetString 目标字符串
3617
+ * @param otherStrToLowerCase (可选)剩余部分字符串转小写,默认false
3618
+ */
3619
+ stringTitleToUpperCase(
3620
+ targetString: string,
3621
+ otherStrToLowerCase?: boolean
3622
+ ): string;
3623
+ stringTitleToUpperCase(
3624
+ targetString: string,
3625
+ otherStrToLowerCase: boolean = false
3626
+ ): string {
3627
+ let newTargetString = targetString.slice(0, 1).toUpperCase();
3628
+ if (otherStrToLowerCase) {
3629
+ newTargetString = newTargetString + targetString.slice(1).toLowerCase();
3630
+ } else {
3631
+ newTargetString = newTargetString + targetString.slice(1);
3632
+ }
3633
+ return newTargetString;
3634
+ }
3635
+ /**
3636
+ * 判断目标字符串是否是以xxx开始
3637
+ *
3638
+ * 如果searchString是字符串数组,那么判断的结果则是字符串数组中的任意字符匹配到返回true
3639
+ * @param target 目标字符串
3640
+ * @param searchString 需要搜索的字符串
3641
+ * @param position (可选)目标字符串的判断起点,要求≥0,默认为0
3642
+ */
3643
+ startsWith(
3644
+ target: string,
3645
+ searchString: string | RegExp | string[],
3646
+ position?: number
3647
+ ): boolean;
3648
+ startsWith(
3649
+ target: string,
3650
+ searchString: string | RegExp | string[],
3651
+ position: number = 0
3652
+ ): boolean {
3653
+ let UtilsContext = this;
3654
+ if (position > target.length) {
3655
+ /* 超出目标字符串的长度 */
3656
+ return false;
3657
+ }
3658
+ if (position !== 0) {
3659
+ target = target.slice(position, target.length);
3660
+ }
3661
+ let searchStringRegexp = searchString;
3662
+ if (typeof searchString === "string") {
3663
+ searchStringRegexp = new RegExp(`^${searchString}`);
3664
+ } else if (Array.isArray(searchString)) {
3665
+ let flag = false;
3666
+ for (const searcStr of searchString) {
3667
+ if (!UtilsContext.startsWith(target, searcStr, position)) {
3668
+ flag = true;
3669
+ break;
3670
+ }
3671
+ }
3672
+ return flag;
3673
+ }
3674
+ return Boolean(target.match(searchStringRegexp as RegExp));
3675
+ }
3676
+ /**
3677
+ * 字符串首字母转小写
3678
+ * @param targetString 目标字符串
3679
+ * @param otherStrToLowerCase (可选)剩余部分字符串转大写,默认false
3680
+ */
3681
+ stringTitleToLowerCase(
3682
+ targetString: string,
3683
+ otherStrToUpperCase?: boolean
3684
+ ): string;
3685
+ stringTitleToLowerCase(
3686
+ targetString: string,
3687
+ otherStrToUpperCase: boolean = false
3688
+ ): string {
3689
+ let newTargetString = targetString.slice(0, 1).toLowerCase();
3690
+ if (otherStrToUpperCase) {
3691
+ newTargetString = newTargetString + targetString.slice(1).toUpperCase();
3692
+ } else {
3693
+ newTargetString = newTargetString + targetString.slice(1);
3694
+ }
3695
+ return newTargetString;
3696
+ }
3697
+ /**
3698
+ * 字符串转Object对象,类似'{"test":""}' => {"test":""}
3699
+ * @param data
3700
+ * @param errorCallBack (可选)错误回调
3701
+ * @example
3702
+ * Utils.toJSON("{123:123}")
3703
+ * > {123:123}
3704
+ */
3705
+ toJSON<T extends AnyObject>(
3706
+ data: string | null,
3707
+ errorCallBack?: (error: Error) => void
3708
+ ): T;
3709
+ toJSON<T extends AnyObject>(
3710
+ data: string | null,
3711
+ errorCallBack?: (error: Error) => void
3712
+ ): T {
3713
+ let UtilsContext = this;
3714
+ let result: AnyObject = {};
3715
+ if (typeof data === "object") {
3716
+ return data as any;
3717
+ }
3718
+ UtilsContext.tryCatch()
3719
+ .config({ log: false })
3720
+ .error((error: Error) => {
3721
+ UtilsContext.tryCatch()
3722
+ .error(() => {
3723
+ try {
3724
+ result = (UtilsCore.window as any).eval("(" + data + ")");
3725
+ } catch (error2: any) {
3726
+ if (typeof errorCallBack === "function") {
3727
+ errorCallBack(error2);
3728
+ }
3729
+ }
3730
+ })
3731
+ .run(() => {
3732
+ if (
3733
+ data &&
3734
+ /^[\],:{}\s]*$/.test(
3735
+ data
3736
+ .replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
3737
+ .replace(
3738
+ /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
3739
+ "]"
3740
+ )
3741
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, "")
3742
+ )
3743
+ ) {
3744
+ result = new Function("return " + data)();
3745
+ } else {
3746
+ if (typeof errorCallBack === "function") {
3747
+ errorCallBack(new Error("target is not a JSON"));
3748
+ }
3749
+ }
3750
+ });
3751
+ })
3752
+ .run(() => {
3753
+ data = (data as string).trim();
3754
+ result = JSON.parse(data);
3755
+ });
3756
+ return result as any;
3757
+ }
3758
+ /**
3759
+ * 对象转为UrlSearchParams格式的字符串
3760
+ * @param obj 目标对象,可以是对象组成的数组
3761
+ */
3762
+ toSearchParamsStr(obj: object | object[]): string;
3763
+ toSearchParamsStr(obj: object | object[]): string {
3764
+ let UtilsContext = this;
3765
+ let searhParamsStr = "";
3766
+ if (Array.isArray(obj)) {
3767
+ obj.forEach((item) => {
3768
+ if (searhParamsStr === "") {
3769
+ searhParamsStr += UtilsContext.toSearchParamsStr(item);
3770
+ } else {
3771
+ searhParamsStr += "&" + UtilsContext.toSearchParamsStr(item);
3772
+ }
3773
+ });
3774
+ } else {
3775
+ searhParamsStr = new URLSearchParams(Object.entries(obj)).toString();
3776
+ }
3777
+ return searhParamsStr;
3778
+ }
3779
+ /**
3780
+ * 提供一个封装了 try-catch 的函数,可以执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
3781
+ * @returns 返回一个对象,其中包含 error 和 run 两个方法。
3782
+ * @example
3783
+ * Utils.tryCatch().error().run(()=>{console.log(1)});
3784
+ * > 1
3785
+ * @example
3786
+ * Utils.tryCatch().config({log:true}).error((error)=>{console.log(error)}).run(()=>{throw new Error('测试错误')});
3787
+ * > ()=>{throw new Error('测试错误')}出现错误
3788
+ */
3789
+ tryCatch = TryCatch;
3790
+ /**
3791
+ * 数组去重,去除重复的值
3792
+ * @param uniqueArrayData 需要去重的数组
3793
+ * @param compareArrayData 用来比较的数组
3794
+ * @param compareFun 数组比较方法,如果值相同,去除该数据
3795
+ * @returns 返回去重完毕的数组
3796
+ * @example
3797
+ * Utils.uniqueArray([1,2,3],[1,2],(item,item2)=>{return item===item2 ? true:false});
3798
+ * > [3]
3799
+ *
3800
+ * @example
3801
+ * Utils.uniqueArray([1,2,3],[1,2]);
3802
+ * > [3]
3803
+ *
3804
+ * @example
3805
+ * Utils.uniqueArray([{"key":1,"value":2},{"key":2}],[{"key":1}],(item,item2)=>{return item["key"] === item2["key"] ? true:false});
3806
+ * > [{"key": 2}]
3807
+ **/
3808
+ uniqueArray<T extends any, TT extends any>(
3809
+ uniqueArrayData?: T[],
3810
+ compareArrayData?: TT[],
3811
+ compareFun?: (item1: T, item2: TT) => boolean
3812
+ ): any[];
3813
+ uniqueArray<T extends any, TT extends any>(
3814
+ uniqueArrayData: T[] = [],
3815
+ compareArrayData: TT[] = [],
3816
+ compareFun: (item1: T, item2: TT) => boolean = (item, item2) => {
3817
+ // @ts-ignore
3818
+ return item === item2;
3819
+ }
3820
+ ): any[] {
3821
+ return Array.from(uniqueArrayData).filter(
3822
+ (item) =>
3823
+ !Array.from(compareArrayData).some(function (item2) {
3824
+ return compareFun(item, item2);
3825
+ })
3826
+ );
3827
+ }
3828
+ /**
3829
+ * 等待函数数组全部执行完毕,注意,每个函数的顺序不是同步
3830
+ * @param data 需要遍历的数组
3831
+ * @param handleFunc 对该数组进行操作的函数,该函数的参数为数组格式的参数,[数组下标,数组项]
3832
+ * @example
3833
+ * await Utils.waitArrayLoopToEnd([callback,callback,callback],xxxcallback);
3834
+ **/
3835
+ waitArrayLoopToEnd(
3836
+ data: any[] | HTMLElement[],
3837
+ handleFunc: Function
3838
+ ): Promise<void[]>;
3839
+ waitArrayLoopToEnd(
3840
+ data: any[] | HTMLElement[],
3841
+ handleFunc: Function
3842
+ ): Promise<void[]> {
3843
+ let UtilsContext = this;
3844
+ if (typeof handleFunc !== "function" && typeof handleFunc !== "string") {
3845
+ throw new Error(
3846
+ "Utils.waitArrayLoopToEnd 参数 handleDataFunction 必须为 function|string 类型"
3847
+ );
3848
+ }
3849
+ return Promise.all(
3850
+ Array.from(data).map(async (item, index) => {
3851
+ await UtilsContext.tryCatch(index, item).run(handleFunc);
3852
+ })
3853
+ );
3854
+ }
3855
+ /**
3856
+ * 等待指定元素出现,支持多个selector
3857
+ * @param nodeSelectors 一个或多个节点选择器,必须为字符串类型
3858
+ * @example
3859
+ * Utils.waitNode("div.xxx").then( element =>{
3860
+ * console.log(element); // div.xxx => HTMLElement
3861
+ * })
3862
+ * @example
3863
+ * Utils.waitNode("div.xxx","a.xxx").then( (elementList)=>{
3864
+ * console.log(elementList[0]); // div.xxx => HTMLElement
3865
+ * console.log(elementList[1]); // a.xxx => HTMLElement
3866
+ * })
3867
+ */
3868
+ waitNode<T extends HTMLElement>(nodeSelector: string | [string]): Promise<T>;
3869
+ /**
3870
+ * 等待指定元素出现,支持多个selector
3871
+ * @param nodeSelectors 一个或多个节点选择器,必须为字符串类型
3872
+ * @example
3873
+ * Utils.waitNode("div.xxx").then( element =>{
3874
+ * console.log(element); // div.xxx => HTMLElement
3875
+ * })
3876
+ * @example
3877
+ * Utils.waitNode("div.xxx","a.xxx").then( (elementList)=>{
3878
+ * console.log(elementList[0]); // div.xxx => HTMLElement
3879
+ * console.log(elementList[1]); // a.xxx => HTMLElement
3880
+ * })
3881
+ */
3882
+ waitNode<T extends HTMLElement>(...nodeSelectors: string[]): Promise<T[]>;
3883
+ /**
3884
+ * 等待指定元素出现,支持多个selector
3885
+ * @param nodeSelectors 一个或多个节点选择器,必须为字符串类型
3886
+ * @example
3887
+ * Utils.waitNode("div.xxx").then( element =>{
3888
+ * console.log(element); // div.xxx => HTMLElement
3889
+ * })
3890
+ * @example
3891
+ * Utils.waitNode("div.xxx","a.xxx").then( (elementList)=>{
3892
+ * console.log(elementList[0]); // div.xxx => HTMLElement
3893
+ * console.log(elementList[1]); // a.xxx => HTMLElement
3894
+ * })
3895
+ */
3896
+ waitNode<T extends HTMLElement>(...nodeSelectors: string[]): Promise<T | T[]>;
3897
+ async waitNode<T extends HTMLElement>(
3898
+ ...nodeSelectors: string | string[] | any
3899
+ ): Promise<T | T[]> {
3900
+ /* 检查每个参数是否为字符串类型 */
3901
+ for (let nodeSelector of nodeSelectors) {
3902
+ if (typeof nodeSelector !== "string") {
3903
+ throw new Error("Utils.waitNode 参数必须都是 string 类型");
3904
+ }
3905
+ }
3906
+ let UtilsContext = this;
3907
+ return new Promise((resolve) => {
3908
+ /* 防止触发第二次回调 */
3909
+ let isReturn = false;
3910
+
3911
+ /**
3912
+ * 检查所有选择器是否匹配到节点
3913
+ * @param observer
3914
+ */
3915
+ let checkNodes = (observer?: MutationObserver) => {
3916
+ let isFind = true;
3917
+ let selectNodeArray: HTMLElement[] = [];
3918
+ for (let selector of nodeSelectors) {
3919
+ let element = document.querySelector(selector) as HTMLElement | null;
3920
+ if (!element) {
3921
+ /* 没找到,直接退出循环 */
3922
+ isFind = false;
3923
+ break;
3924
+ }
3925
+ selectNodeArray.push(element);
3926
+ }
3927
+ if (isFind) {
3928
+ isReturn = true;
3929
+ observer?.disconnect();
3930
+ /* 如果只有一个选择器,那么返回数组中存储的第一个 */
3931
+ if (selectNodeArray.length === 1) {
3932
+ resolve(selectNodeArray[0] as any);
3933
+ } else {
3934
+ resolve(selectNodeArray as any);
3935
+ }
3936
+ }
3937
+ };
3938
+
3939
+ /* 在函数开始时检查节点是否已经存在 */
3940
+ checkNodes();
3941
+
3942
+ /* 监听 DOM 的变化,直到至少有一个节点被匹配到 */
3943
+ UtilsContext.mutationObserver(document.documentElement, {
3944
+ config: { subtree: true, childList: true, attributes: true },
3945
+ callback: (mutations, observer) => {
3946
+ if (isReturn) {
3947
+ return;
3948
+ }
3949
+ checkNodes(observer);
3950
+ },
3951
+ });
3952
+ });
3953
+ }
3954
+ /**
3955
+ * 在规定时间内,等待任意元素出现,支持多个selector,如果未出现,则关闭监听
3956
+ * @param nodeSelectorsList 一个或多个节点选择器,必须为字符串类型
3957
+ * @param maxTime (可选)xx毫秒(ms)后关闭监听,默认:0(ms)
3958
+ * @example
3959
+ * Utils.waitNodeWithInterval("a.xxx",30000).then(element=>{
3960
+ * console.log(element);
3961
+ * })
3962
+ * @example
3963
+ * Utils.waitNodeWithInterval(["div.xxx","a.xxx"],30000).then(elementList=>{
3964
+ * console.log(elementList[0]); // div.xxx => HTMLElement
3965
+ * console.log(elementList[1]); // a.xxx => HTMLElement
3966
+ * })
3967
+ */
3968
+ waitNodeWithInterval<T extends HTMLElement>(
3969
+ nodeSelectorsList?: string[] | string,
3970
+ maxTime?: number
3971
+ ): Promise<T | T[]>;
3972
+ waitNodeWithInterval<T extends HTMLElement>(
3973
+ nodeSelectorsList: string[] | string = [],
3974
+ maxTime: number = 0
3975
+ ): Promise<T | T[]> {
3976
+ let UtilsContext = this;
3977
+ let nodeSelectors: string[] = [];
3978
+ /* 检查每个参数是否为字符串类型 */
3979
+ if (Array.isArray(nodeSelectorsList)) {
3980
+ for (let nodeSelector of nodeSelectorsList) {
3981
+ if (typeof nodeSelector !== "string") {
3982
+ throw new Error(
3983
+ "Utils.waitNodeWithInterval 参数nodeSelectorsList必须为 string[] 类型"
3984
+ );
3985
+ }
3986
+ }
3987
+ nodeSelectors = nodeSelectorsList;
3988
+ } else {
3989
+ nodeSelectors.push(nodeSelectorsList);
3990
+ }
3991
+
3992
+ return new Promise((resolve, reject) => {
3993
+ /* 防止触发第二次回调 */
3994
+ let isReturn = false;
3995
+
3996
+ /* 检查所有选择器是否匹配到节点 */
3997
+ let checkNodes = (observer?: MutationObserver) => {
3998
+ let isFind = true;
3999
+ let selectNodeArray = [];
4000
+ for (let selector of nodeSelectors) {
4001
+ let element = document.querySelector(selector);
4002
+ if (!element) {
4003
+ /* 没找到,直接退出循环 */
4004
+ isFind = false;
4005
+ break;
4006
+ }
4007
+ selectNodeArray.push(element);
4008
+ }
4009
+ if (isFind) {
4010
+ isReturn = true;
4011
+ observer?.disconnect();
4012
+ /* 如果只有一个选择器,那么返回数组中存储的第一个 */
4013
+ if (selectNodeArray.length === 1) {
4014
+ resolve(selectNodeArray[0] as any);
4015
+ } else {
4016
+ resolve(selectNodeArray as any);
4017
+ }
4018
+ }
4019
+ };
4020
+
4021
+ /* 在函数开始时检查节点是否已经存在 */
4022
+ checkNodes();
4023
+
4024
+ /* 监听 DOM 的变化,直到至少有一个节点被匹配到 */
4025
+ let mutationObserver = UtilsContext.mutationObserver(
4026
+ document.documentElement,
4027
+ {
4028
+ config: { subtree: true, childList: true, attributes: true },
4029
+ callback: (mutations, observer) => {
4030
+ if (isReturn) {
4031
+ return;
4032
+ }
4033
+ checkNodes(observer);
4034
+ },
4035
+ }
4036
+ );
4037
+ setTimeout(() => {
4038
+ mutationObserver.disconnect();
4039
+ reject();
4040
+ }, maxTime);
4041
+ });
4042
+ }
4043
+
4044
+ /**
4045
+ * 等待任意元素出现,支持多个selector
4046
+ * @param nodeSelectors 一个或多个节点选择器,必须为字符串类型
4047
+ * @example
4048
+ * Utils.waitAnyNode("div.xxx","a.xxx").then( element =>{
4049
+ * console.log(element); // a.xxx => HTMLElement
4050
+ * })
4051
+ */
4052
+ waitAnyNode<T extends HTMLElement>(...nodeSelectors: any[]): Promise<T>;
4053
+ waitAnyNode<T extends HTMLElement>(...nodeSelectors: any[]): Promise<T> {
4054
+ let UtilsContext = this;
4055
+ /* 检查每个参数是否为字符串类型 */
4056
+ for (let nodeSelector of nodeSelectors) {
4057
+ if (typeof nodeSelector !== "string") {
4058
+ throw new Error("Utils.waitNode 参数必须为 ...string 类型");
4059
+ }
4060
+ }
4061
+
4062
+ return new Promise((resolve) => {
4063
+ /* 防止触发第二次回调 */
4064
+ let isReturn = false;
4065
+
4066
+ /* 检查所有选择器是否存在任意匹配到元素 */
4067
+ let checkNodes = (observer?: MutationObserver) => {
4068
+ let selectNode = null;
4069
+ for (let selector of nodeSelectors) {
4070
+ selectNode = document.querySelector(selector);
4071
+ if (selectNode) {
4072
+ /* 找到,退出循环 */
4073
+ break;
4074
+ }
4075
+ }
4076
+ if (selectNode) {
4077
+ isReturn = true;
4078
+ observer?.disconnect();
4079
+ resolve(selectNode);
4080
+ }
4081
+ };
4082
+
4083
+ /* 在函数开始时检查节点是否已经存在 */
4084
+ checkNodes();
4085
+
4086
+ /* 监听 DOM 的变化,直到至少有一个节点被匹配到 */
4087
+ UtilsContext.mutationObserver(document.documentElement, {
4088
+ config: { subtree: true, childList: true, attributes: true },
4089
+ callback: (mutations, observer) => {
4090
+ if (isReturn) {
4091
+ return;
4092
+ }
4093
+ checkNodes(observer);
4094
+ },
4095
+ });
4096
+ });
4097
+ }
4098
+ /**
4099
+ * 等待指定元素出现
4100
+ * @param nodeSelectors
4101
+ * @returns 当nodeSelectors为数组多个时,
4102
+ * 返回如:[ NodeList, NodeList ],
4103
+ * 当nodeSelectors为单个时,
4104
+ * 返回如:NodeList。
4105
+ * NodeList元素与页面存在强绑定,当已获取该NodeList,但是页面中却删除了,该元素在NodeList中会被自动删除
4106
+ * @example
4107
+ * Utils.waitNodeList("div.xxx").then( nodeList =>{
4108
+ * console.log(nodeList) // div.xxx => NodeList
4109
+ * })
4110
+ * @example
4111
+ * Utils.waitNodeList("div.xxx","a.xxx").then( nodeListArray =>{
4112
+ * console.log(nodeListArray[0]) // div.xxx => NodeList
4113
+ * console.log(nodeListArray[1]) // a.xxx => NodeList
4114
+ * })
4115
+ */
4116
+ waitNodeList<T extends HTMLElement>(nodeSelector: string): Promise<T>;
4117
+ /**
4118
+ * 等待指定元素出现,支持多个selector
4119
+ * @param nodeSelectors
4120
+ * @returns 当nodeSelectors为数组多个时,
4121
+ * 返回如:[ NodeList, NodeList ],
4122
+ * 当nodeSelectors为单个时,
4123
+ * 返回如:NodeList。
4124
+ * NodeList元素与页面存在强绑定,当已获取该NodeList,但是页面中却删除了,该元素在NodeList中会被自动删除
4125
+ * @example
4126
+ * Utils.waitNodeList("div.xxx").then( nodeList =>{
4127
+ * console.log(nodeList) // div.xxx => NodeList
4128
+ * })
4129
+ * @example
4130
+ * Utils.waitNodeList("div.xxx","a.xxx").then( nodeListArray =>{
4131
+ * console.log(nodeListArray[0]) // div.xxx => NodeList
4132
+ * console.log(nodeListArray[1]) // a.xxx => NodeList
4133
+ * })
4134
+ */
4135
+ waitNodeList<T extends HTMLElement>(
4136
+ ...nodeSelectors: string[]
4137
+ ): Promise<NodeListOf<T>[]>;
4138
+ waitNodeList<T extends HTMLElement>(
4139
+ ...nodeSelectors: string[]
4140
+ ): Promise<NodeListOf<T>[]> {
4141
+ let UtilsContext = this;
4142
+ /* 检查每个参数是否为字符串类型 */
4143
+ for (let nodeSelector of nodeSelectors) {
4144
+ if (typeof nodeSelector !== "string") {
4145
+ throw new Error("Utils.waitNode 参数必须为 ...string 类型");
4146
+ }
4147
+ }
4148
+
4149
+ return new Promise((resolve) => {
4150
+ /* 防止触发第二次回调 */
4151
+ let isReturn = false;
4152
+
4153
+ /* 检查所有选择器是否匹配到节点 */
4154
+ let checkNodes = (observer?: MutationObserver) => {
4155
+ let isFind = true;
4156
+ let selectNodes = [];
4157
+ for (let selector of nodeSelectors) {
4158
+ let nodeList = document.querySelectorAll(selector);
4159
+ if (nodeList.length === 0) {
4160
+ /* 没找到,直接退出循环 */
4161
+ isFind = false;
4162
+ break;
4163
+ }
4164
+ selectNodes.push(nodeList);
4165
+ }
4166
+ if (isFind) {
4167
+ isReturn = true;
4168
+ observer?.disconnect();
4169
+ /* 如果只有一个选择器,那么返回第一个 */
4170
+ if (selectNodes.length === 1) {
4171
+ resolve(selectNodes[0] as any);
4172
+ } else {
4173
+ resolve(selectNodes as any);
4174
+ }
4175
+ }
4176
+ };
4177
+
4178
+ /* 在函数开始时检查节点是否已经存在 */
4179
+ checkNodes();
4180
+
4181
+ /* 监听 DOM 的变化,直到至少有一个节点被匹配到 */
4182
+ UtilsContext.mutationObserver(document.documentElement, {
4183
+ config: { subtree: true, childList: true, attributes: true },
4184
+ callback: (mutations, observer) => {
4185
+ if (isReturn) {
4186
+ return;
4187
+ }
4188
+ checkNodes(observer);
4189
+ },
4190
+ });
4191
+ });
4192
+ }
4193
+ /**
4194
+ * 等待任意元素出现,支持多个selector
4195
+ * @param nodeSelectors
4196
+ * @returns 返回NodeList
4197
+ * NodeList元素与页面存在强绑定,当已获取该NodeList,但是页面中却删除了,该元素在NodeList中会被自动删除
4198
+ * @example
4199
+ * Utils.waitAnyNodeList("div.xxx").then( nodeList =>{
4200
+ * console.log(nodeList) // div.xxx => NodeList
4201
+ * })
4202
+ * @example
4203
+ * Utils.waitAnyNodeList("div.xxx","a.xxx").then( nodeList =>{
4204
+ * console.log(nodeList) // a.xxx => NodeList
4205
+ * })
4206
+ */
4207
+ waitAnyNodeList<T extends HTMLElement>(
4208
+ ...nodeSelectors: string[]
4209
+ ): Promise<NodeListOf<T>[]>;
4210
+ waitAnyNodeList<T extends HTMLElement>(
4211
+ ...nodeSelectors: string[]
4212
+ ): Promise<NodeListOf<T>[]> {
4213
+ let UtilsContext = this;
4214
+ /* 检查每个参数是否为字符串类型 */
4215
+ for (let nodeSelector of nodeSelectors) {
4216
+ if (typeof nodeSelector !== "string") {
4217
+ throw new Error("Utils.waitNode 参数必须为 ...string 类型");
4218
+ }
4219
+ }
4220
+
4221
+ return new Promise((resolve) => {
4222
+ /* 防止触发第二次回调 */
4223
+ let isReturn = false;
4224
+
4225
+ /* 检查所有选择器是否匹配到节点 */
4226
+ let checkNodes = (observer?: MutationObserver) => {
4227
+ let selectNodes = [];
4228
+ for (let selector of nodeSelectors) {
4229
+ selectNodes = document.querySelectorAll(selector) as any;
4230
+ if (selectNodes.length) {
4231
+ /* 找到,退出循环 */
4232
+ break;
4233
+ }
4234
+ }
4235
+ if (selectNodes.length) {
4236
+ isReturn = true;
4237
+ observer?.disconnect();
4238
+ resolve(selectNodes);
4239
+ }
4240
+ };
4241
+
4242
+ /* 在函数开始时检查节点是否已经存在 */
4243
+ checkNodes();
4244
+
4245
+ /* 监听 DOM 的变化,直到至少有一个节点被匹配到 */
4246
+ UtilsContext.mutationObserver(document.documentElement, {
4247
+ config: { subtree: true, childList: true, attributes: true },
4248
+ callback: (mutations, observer) => {
4249
+ if (isReturn) {
4250
+ return;
4251
+ }
4252
+ checkNodes(observer);
4253
+ },
4254
+ });
4255
+ });
4256
+ }
4257
+ /**
4258
+ * 等待对象上的属性出现
4259
+ * @param checkObj 检查的对象
4260
+ * @param checkPropertyName 检查的对象的属性名
4261
+ * @example
4262
+ * await Utils.waitProperty(window,"test");
4263
+ * console.log("test success set");
4264
+ *
4265
+ * window.test = 1;
4266
+ * > "test success set"
4267
+ *
4268
+ */
4269
+ waitProperty<T extends any>(
4270
+ checkObj: AnyObject | (() => AnyObject),
4271
+ checkPropertyName: string
4272
+ ): Promise<T>;
4273
+ waitProperty<T extends any>(
4274
+ checkObj: AnyObject | (() => AnyObject),
4275
+ checkPropertyName: string
4276
+ ): Promise<T> {
4277
+ return new Promise((resolve) => {
4278
+ let obj = checkObj;
4279
+ if (typeof checkObj === "function") {
4280
+ obj = checkObj();
4281
+ }
4282
+ if (Reflect.has(obj, checkPropertyName)) {
4283
+ resolve((obj as any)[checkPropertyName]);
4284
+ } else {
4285
+ Object.defineProperty(obj, checkPropertyName, {
4286
+ set: function (value) {
4287
+ try {
4288
+ resolve(value);
4289
+ } catch (error) {
4290
+ console.error("Error setting property:", error);
4291
+ }
4292
+ },
4293
+ });
4294
+ }
4295
+ });
4296
+ }
4297
+ /**
4298
+ * 在规定时间内等待对象上的属性出现
4299
+ * @param checkObj 检查的对象
4300
+ * @param checkPropertyName 检查的对象的属性名
4301
+ * @param intervalTimer (可选)检查间隔时间(ms),默认250ms
4302
+ * @param maxTime (可选)限制在多长时间内,默认-1(不限制时间)
4303
+ * @example
4304
+ * await Utils.waitPropertyByInterval(window,"test");
4305
+ * console.log("test success set");
4306
+ */
4307
+ waitPropertyByInterval<T extends any>(
4308
+ checkObj: AnyObject | (() => AnyObject),
4309
+ checkPropertyName: string | ((obj: any) => boolean),
4310
+ intervalTimer?: number,
4311
+ maxTime?: number
4312
+ ): Promise<T>;
4313
+ waitPropertyByInterval<T extends any>(
4314
+ checkObj: AnyObject | (() => AnyObject),
4315
+ checkPropertyName: string | ((obj: any) => boolean),
4316
+ intervalTimer: number = 250,
4317
+ maxTime: number = -1
4318
+ ): Promise<T> {
4319
+ if (checkObj == null) {
4320
+ throw new TypeError("checkObj 不能为空对象 ");
4321
+ }
4322
+ let isResolve = false;
4323
+ return new Promise((resolve, reject) => {
4324
+ let interval = setInterval(() => {
4325
+ let obj = checkObj;
4326
+ if (typeof checkObj === "function") {
4327
+ obj = checkObj();
4328
+ }
4329
+ if (
4330
+ (typeof checkPropertyName === "function" && checkPropertyName(obj)) ||
4331
+ Reflect.has(obj, checkPropertyName as string)
4332
+ ) {
4333
+ isResolve = true;
4334
+ clearInterval(interval);
4335
+ resolve((obj as any)[checkPropertyName as string]);
4336
+ }
4337
+ }, intervalTimer);
4338
+ if (maxTime !== -1) {
4339
+ setTimeout(() => {
4340
+ if (!isResolve) {
4341
+ clearInterval(interval);
4342
+ reject();
4343
+ }
4344
+ }, maxTime);
4345
+ }
4346
+ });
4347
+ }
4348
+ /**
4349
+ * 在规定时间内等待元素上的__vue__属性或者__vue__属性上的某个值出现出现
4350
+ * @param element 目标元素
4351
+ * @param propertyName (可选)vue上的属性名或者传递一个获取属性的方法返回boolean
4352
+ * @param timer (可选)间隔时间(ms),默认:250(ms)
4353
+ * @param maxTime(可选) 限制在多长时间内,默认:-1(不限制时间)
4354
+ * @param vueName (可选)vue挂载的属性名,默认:__vue__
4355
+ * @example
4356
+ * await Utils.waitVueByInterval(
4357
+ * function(){
4358
+ * return document.querySelector("a.xx")
4359
+ * },
4360
+ * function(__vue__){
4361
+ * return Boolean(__vue__.xxx == null);
4362
+ * },
4363
+ * 250,
4364
+ * 10000,
4365
+ * "__vue__"
4366
+ * )
4367
+ */
4368
+ waitVueByInterval(
4369
+ element: HTMLElement | (() => HTMLElement),
4370
+ propertyName: string | ((__vue__: any) => boolean),
4371
+ timer?: number,
4372
+ maxTime?: number,
4373
+ vueName?: "__vue__" | string
4374
+ ): Promise<boolean>;
4375
+ async waitVueByInterval(
4376
+ element: HTMLElement | (() => HTMLElement),
4377
+ propertyName: string | ((__vue__: any) => boolean),
4378
+ timer = 250,
4379
+ maxTime = -1,
4380
+ vueName = "__vue__"
4381
+ ) {
4382
+ if (element == null) {
4383
+ throw new Error("Utils.waitVueByInterval 参数element 不能为空");
4384
+ }
4385
+ let flag = false;
4386
+ let UtilsContext = this;
4387
+ try {
4388
+ await UtilsContext.waitPropertyByInterval(
4389
+ element,
4390
+ function (targetElement) {
4391
+ if (targetElement == null) {
4392
+ return false;
4393
+ }
4394
+ if (!(vueName in targetElement)) {
4395
+ return false;
4396
+ }
4397
+ if (propertyName == null) {
4398
+ return true;
4399
+ }
4400
+ let vueObject = targetElement[vueName];
4401
+ if (typeof propertyName === "string") {
4402
+ if (propertyName in vueObject) {
4403
+ flag = true;
4404
+ return true;
4405
+ }
4406
+ } else {
4407
+ /* Function */
4408
+ if (propertyName(vueObject)) {
4409
+ flag = true;
4410
+ return true;
4411
+ }
4412
+ }
4413
+ return false;
4414
+ },
4415
+ timer,
4416
+ maxTime
4417
+ );
4418
+ } catch (error) {
4419
+ return flag;
4420
+ }
4421
+ return flag;
4422
+ }
4423
+ /**
4424
+ * 观察对象的set、get
4425
+ * @param target 观察的对象
4426
+ * @param propertyName 观察的对象的属性名
4427
+ * @param getCallBack (可选)触发get的回调,可以自定义返回特定值
4428
+ * @param setCallBack (可选)触发set的回调,参数为将要设置的value
4429
+ * @example
4430
+ * Utils.watchObject(window,"test",()=>{return 111;},(value)=>{console.log("test出现,值是",value)});
4431
+ *
4432
+ * window.test = 1;
4433
+ * > test出现,值是 1
4434
+ * console.log(window.test);
4435
+ * > 111;
4436
+ */
4437
+ watchObject(
4438
+ target: AnyObject,
4439
+ propertyName: string,
4440
+ getCallBack: (value: any) => void,
4441
+ setCallBack: (value: any) => void
4442
+ ): void;
4443
+ watchObject(
4444
+ target: AnyObject,
4445
+ propertyName: string,
4446
+ getCallBack: (value: any) => void,
4447
+ setCallBack: (value: any) => void
4448
+ ): void {
4449
+ if (
4450
+ typeof getCallBack !== "function" &&
4451
+ typeof setCallBack !== "function"
4452
+ ) {
4453
+ return;
4454
+ }
4455
+
4456
+ if (typeof getCallBack === "function") {
4457
+ Object.defineProperty(target, propertyName, {
4458
+ get() {
4459
+ if (typeof getCallBack === "function") {
4460
+ return getCallBack(target[propertyName]);
4461
+ } else {
4462
+ return target[propertyName];
4463
+ }
4464
+ },
4465
+ });
4466
+ } else if (typeof setCallBack === "function") {
4467
+ Object.defineProperty(target, propertyName, {
4468
+ set(value) {
4469
+ if (typeof setCallBack === "function") {
4470
+ setCallBack(value);
4471
+ }
4472
+ },
4473
+ });
4474
+ } else {
4475
+ Object.defineProperty(target, propertyName, {
4476
+ get() {
4477
+ if (typeof getCallBack === "function") {
4478
+ return (getCallBack as any)(target[propertyName]);
4479
+ } else {
4480
+ return target[propertyName];
4481
+ }
4482
+ },
4483
+ set(value) {
4484
+ if (typeof setCallBack === "function") {
4485
+ (setCallBack as any)(value);
4486
+ }
4487
+ },
4488
+ });
4489
+ }
4490
+ }
4491
+ }
4492
+
4493
+ let utils = new Utils();
4494
+
4495
+ export { utils as Utils };