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