Repository navigation
Expand file tree
/
Copy pathgm_api_sync_test.js
More file actions
711 lines (659 loc) · 18.1 KB
/
Copy pathgm_api_sync_test.js
File metadata and controls
711 lines (659 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// ==UserScript==
// @name GM API 完整测试 (同步版本)
// @namespace https://docs.scriptcat.org/
// @version 1.1.1
// @description 全面测试ScriptCat的所有GM API功能
// @author ScriptCat
// @match https://content-security-policy.com/?gm_api_sync
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_addValueChangeListener
// @grant GM_removeValueChangeListener
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @grant GM_addStyle
// @grant GM_addElement
// @grant GM_xmlhttpRequest
// @grant GM_download
// @grant GM_notification
// @grant GM_setClipboard
// @grant GM_info
// @grant GM_openInTab
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_cookie
// @grant GM.setValue
// @grant unsafeWindow
// @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js#sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK
// @require https://cdn.jsdelivr.net/gh/scriptscat/scriptcat@36ab4ce5ff23c820a32cd13ac5a04d8834ab4d82/example/tests/lib/sctest.js
// @resource testCSS https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css#sha256=62f74b1cf824a89f03554c638e719594c309b4d8a627a758928c0516fa7890ab
// @connect httpbingo.org
// @connect example.com
// @run-at document-start
// ==/UserScript==
(async function () {
"use strict";
const { describe, check, expect, run } = SCTest.create({ name: "GM API 完整测试(同步)" });
describe("GM_info", () => {
check(
"自动断言",
"GM_info 存在",
() => {
expect(GM_info).toBeTypeOf("object");
expect(GM_info.script).toBeTruthy();
expect(GM_info.scriptMetaStr).toBeTruthy();
},
null,
null,
null
);
});
describe("GM 存储 API", () => {
check(
"自动断言",
"GM_setValue - 字符串",
() => {
GM_setValue("test_string", "Hello ScriptCat");
const value = GM_getValue("test_string");
expect(value).toBe("Hello ScriptCat");
},
null,
null,
null
);
check(
"自动断言",
"GM_setValue - 数字",
() => {
GM_setValue("test_number", 42);
const value = GM_getValue("test_number");
expect(value).toBe(42);
},
null,
null,
null
);
check(
"自动断言",
"GM_setValue - 布尔值",
() => {
GM_setValue("test_boolean", true);
const value = GM_getValue("test_boolean");
expect(value).toBe(true);
},
null,
null,
null
);
check(
"自动断言",
"GM_setValue - 对象",
() => {
const obj = { name: "ScriptCat", version: "1.2.0", features: ["GM API", "Background"] };
GM_setValue("test_object", obj);
const value = GM_getValue("test_object");
expect(value).toEqual(obj);
},
null,
null,
null
);
check(
"自动断言",
"GM_setValue - 数组",
() => {
const arr = [1, 2, 3, "test", { key: "value" }];
GM_setValue("test_array", arr);
const value = GM_getValue("test_array");
expect(value).toEqual(arr);
},
null,
null,
null
);
check(
"自动断言",
"GM_getValue - 默认值",
() => {
const value = GM_getValue("non_existent_key", "default_value");
expect(value).toBe("default_value");
},
null,
null,
null
);
check(
"自动断言",
"GM_listValues",
() => {
const values = GM_listValues();
expect(Array.isArray(values)).toBeTruthy();
expect(values.includes("test_string")).toBeTruthy();
},
null,
null,
null
);
check(
"自动断言",
"GM_deleteValue",
() => {
GM_setValue("test_delete", "to be deleted");
expect(GM_getValue("test_delete")).toBe("to be deleted");
GM_deleteValue("test_delete");
expect(GM_getValue("test_delete", "not_found")).toBe("not_found");
},
null,
null,
null
);
check(
"自动断言",
"GM_addValueChangeListener",
() => {
return new Promise(async (resolve, reject) => {
let listenerId = null;
let timeoutId = null;
// 设置 2 秒超时
timeoutId = setTimeout(() => {
if (listenerId && typeof GM_removeValueChangeListener === "function") {
GM_removeValueChangeListener(listenerId);
}
reject(new Error("监听器超时:2秒内未触发值变化事件"));
}, 2000);
// 先设置初始值,然后再添加监听器
await GM.setValue("test_listener", "initial");
console.log("已设置初始值: initial");
// 使用 setTimeout 确保初始值已完全设置
setTimeout(() => {
// 添加监听器
listenerId = GM_addValueChangeListener("test_listener", (name, oldValue, newValue, remote) => {
// 清除超时
if (timeoutId) {
clearTimeout(timeoutId);
}
// 验证参数
try {
expect(name).toBe("test_listener");
expect(oldValue).toBe("initial");
expect(newValue).toBe("changed");
expect(remote).toBe(false);
// 清理监听器
if (typeof GM_removeValueChangeListener === "function") {
GM_removeValueChangeListener(listenerId);
}
resolve();
} catch (error) {
// 清理监听器
if (typeof GM_removeValueChangeListener === "function") {
GM_removeValueChangeListener(listenerId);
}
reject(error);
}
});
// 验证返回的监听器 ID
const idType = typeof listenerId;
if (idType !== "number" && idType !== "string") {
clearTimeout(timeoutId);
reject(new Error(`监听器ID类型错误: 期望 number 或 string, 实际 ${idType}`));
return;
}
console.log("监听器已注册,ID:", listenerId);
// 延迟后修改值触发监听器
setTimeout(() => {
GM_setValue("test_listener", "changed");
console.log("已修改值为: changed");
}, 100);
}, 50);
});
},
null,
null,
null
);
});
describe("GM 样式 API", () => {
check(
"自动断言",
"GM_addStyle - CSS字符串",
() => {
const css = `
.scriptcat-test {
color: red;
font-weight: bold;
}
`;
const element = GM_addStyle(css);
expect(element && element.tagName === "STYLE").toBeTruthy();
},
null,
null,
null
);
});
describe("GM_addElement", () => {
check(
"自动断言",
"GM_addElement - 创建元素",
async () => {
expect(GM_addElement).toBeTypeOf("function");
const div = GM_addElement("div", {
textContent: "ScriptCat GM_addElement 测试",
style: "position: fixed; top: 10px; right: 10px; background: yellow; padding: 10px; z-index: 9999;",
});
expect(div && div.tagName === "DIV").toBeTruthy();
console.log("添加的元素:", div);
// 创建脚本元素测试
const script = GM_addElement("script", {
textContent: 'window.foo = "bar";',
});
expect(script && script.tagName === "SCRIPT").toBeTruthy();
expect(unsafeWindow.foo).toBe("bar");
console.log("添加的脚本元素:", script);
document.querySelector(".container").insertBefore(script, document.querySelector(".masthead"));
// onload 和 onerror 测试 - 插入图片元素
let img;
await new Promise((resolve, reject) => {
img = GM_addElement(document.body, "img", {
src: "https://www.tampermonkey.net/favicon.ico",
onload: () => {
resolve();
},
onerror: (error) => {
reject(new Error("图片加载失败: " + error));
},
});
});
expect(img && img.tagName === "IMG").toBeTruthy();
// 3秒后移除
setTimeout(() => {
script.remove();
div.remove();
img.remove();
}, 3000);
},
null,
null,
null
);
});
describe("GM 资源 API", () => {
check(
"自动断言",
"GM_getResourceText",
() => {
expect(GM_getResourceText).toBeTypeOf("function");
const css = GM_getResourceText("testCSS");
expect(css).toBeTypeOf("string");
expect(css.length).toBe(163870);
},
null,
null,
null
);
check(
"自动断言",
"GM_getResourceURL",
() => {
expect(GM_getResourceURL).toBeTypeOf("function");
const url = GM_getResourceURL("testCSS");
expect(url).toBeTypeOf("string");
expect(url.startsWith("data:") || url.startsWith("blob:")).toBeTruthy();
},
null,
null,
null
);
});
describe("GM 网络请求 API", () => {
check(
"自动断言",
"GM_xmlhttpRequest - GET 请求",
() => {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: "https://httpbingo.org/get",
timeout: 10000,
onload: (response) => {
try {
expect(response.status).toBe(200);
expect(response.responseText).toBeTruthy();
const data = JSON.parse(response.responseText);
expect(data).toBeTypeOf("object");
expect(data.url).toBe("https://httpbingo.org/get");
resolve();
} catch (error) {
reject(error);
}
},
onerror: (error) => {
reject(new Error("请求失败: " + error));
},
ontimeout: () => {
reject(new Error("请求超时"));
},
});
});
},
null,
null,
null
);
});
describe("GM 通知 API", () => {
check(
"自动断言",
"GM_notification",
() => {
expect(GM_notification).toBeTypeOf("function");
GM_notification({
text: "ScriptCat GM API 测试通知",
title: "ScriptCat 测试",
image: "https://scriptcat.org/logo.png",
onclick: () => {
console.log("通知被点击");
},
});
console.log("通知已发送(请检查系统通知)");
},
null,
null,
null
);
});
describe("GM 剪贴板 API", () => {
check(
"自动断言",
"GM_setClipboard",
() => {
expect(GM_setClipboard).toBeTypeOf("function");
GM_setClipboard("ScriptCat GM API 测试文本 - " + new Date().toLocaleString());
console.log("文本已复制到剪贴板(可以尝试粘贴验证)");
},
null,
null,
null
);
});
describe("GM 标签页 API", () => {
check(
"自动断言",
"GM_openInTab (不执行)",
() => {
// 不实际打开标签页,只测试函数是否存在
expect(GM_openInTab).toBeTypeOf("function");
},
null,
null,
null
);
});
describe("GM 菜单 API", () => {
check(
"自动断言",
"GM_registerMenuCommand",
() => {
const menuId = GM_registerMenuCommand("ScriptCat 测试菜单", () => {
alert("测试菜单被点击!");
});
expect(menuId !== undefined).toBeTruthy();
},
null,
null,
null
);
});
describe("GM Cookie API", () => {
check(
"自动断言",
"GM_cookie 函数存在",
() => {
expect(GM_cookie).toBeTypeOf("function");
},
null,
null,
null
);
// 测试 GM_cookie(action, details, callback)
check(
"自动断言",
"GM_cookie - 回调风格 set",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"set",
{
url: "http://example.com/cookie",
name: "scriptcat_test1",
value: "test_value_1",
},
(error) => {
if (error) {
reject(new Error("设置 cookie 失败: " + error));
} else {
resolve();
}
}
);
});
},
null,
null,
null
);
check(
"自动断言",
"GM_cookie - 回调风格 set (带 domain 和 path)",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"set",
{
url: "http://www.example.com/",
domain: ".example.com",
path: "/path",
name: "scriptcat_test2",
value: "test_value_2",
},
(error) => {
if (error) {
reject(new Error("设置 cookie 失败: " + error));
} else {
resolve();
}
}
);
});
},
null,
null,
null
);
check(
"自动断言",
"GM_cookie - 回调风格 list (by domain)",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"list",
{
domain: "example.com",
},
(cookies, error) => {
if (error) {
reject(new Error("列出 cookies 失败: " + error));
} else {
try {
expect(Array.isArray(cookies)).toBeTruthy();
expect(cookies.length >= 1).toBeTruthy();
resolve();
} catch (err) {
reject(err);
}
}
}
);
});
},
null,
null,
null
);
check(
"自动断言",
"GM_cookie - 回调风格 list (by url)",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"list",
{
url: "http://example.com/cookie",
},
(cookies, error) => {
if (error) {
reject(new Error("列出 cookies 失败: " + error));
} else {
try {
expect(Array.isArray(cookies)).toBeTruthy();
resolve();
} catch (err) {
reject(err);
}
}
}
);
});
},
null,
null,
null
);
check(
"自动断言",
"GM_cookie - 回调风格 delete",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"delete",
{
url: "http://www.example.com/path",
name: "scriptcat_test2",
},
(error) => {
if (error) {
reject(new Error("删除 cookie 失败: " + error));
} else {
resolve();
}
}
);
});
},
null,
null,
null
);
check(
"自动断言",
"GM_cookie - 验证删除后",
() => {
return new Promise((resolve, reject) => {
GM_cookie(
"list",
{
domain: "example.com",
},
(cookies, error) => {
if (error) {
reject(new Error("列出 cookies 失败: " + error));
} else {
try {
const test2Cookie = cookies.find((c) => c.name === "scriptcat_test2");
expect(!test2Cookie).toBeTruthy();
resolve();
} catch (err) {
reject(err);
}
}
}
);
});
},
null,
null,
null
);
// 清理所有测试 cookies
check(
"自动断言",
"清理测试 cookies",
() => {
return new Promise((resolve, reject) => {
GM_cookie("list", { domain: "example.com" }, (cookies, error) => {
if (error) {
reject(new Error("列出 cookies 失败: " + error));
return;
}
const testCookies = cookies.filter((c) => c.name.startsWith("scriptcat_test"));
if (testCookies.length === 0) {
resolve();
return;
}
let deleteCount = 0;
testCookies.forEach((cookie, index) => {
GM_cookie(
"delete",
{
url: `http://${cookie.domain}${cookie.path}`,
name: cookie.name,
},
(error) => {
deleteCount++;
if (error) {
console.warn(`删除 cookie ${cookie.name} 失败:`, error);
}
if (deleteCount === testCookies.length) {
resolve();
}
}
);
});
});
});
},
null,
null,
null
);
});
describe("unsafeWindow", () => {
check(
"自动断言",
"unsafeWindow",
() => {
expect(unsafeWindow).toBeTypeOf("object");
expect(unsafeWindow.document).toBe(document);
},
null,
null,
null
);
});
describe("@require", () => {
check(
"自动断言",
"jQuery 加载 (@require)",
() => {
expect(jQuery).toBeTypeOf("function");
expect($).toBeTypeOf("function");
},
null,
null,
null
);
});
await run();
})();