Skip to content

Commit c8dd6a7

Browse files
committed
feat: 添加油猴API使用示例
1. 创建src/gm_api_example/gm_api_usage.ts,提供常用油猴API的使用示例\n2. 更新入口文件,展示如何在实际项目中使用油猴API
1 parent dd97be0 commit c8dd6a7

File tree

2 files changed

+163
-0
lines changed

2 files changed

+163
-0
lines changed

src/gm_api_example/gm_api_usage.ts

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/**
2+
* 油猴API使用示例
3+
* 这个文件展示了如何使用油猴API及其TypeScript类型定义
4+
*/
5+
6+
// 存储数据示例
7+
export function storeData(key: string, value: any): void {
8+
// 使用GM.setValue或GM_setValue (根据你的@grant声明)
9+
if (typeof GM !== 'undefined' && GM.setValue) {
10+
// GM.setValue是Promise形式的API
11+
GM.setValue(key, value)
12+
.then(() => console.log(`数据 ${key} 已保存`))
13+
.catch(err => console.error('保存数据失败:', err));
14+
} else if (typeof GM_setValue !== 'undefined') {
15+
// GM_setValue是同步API
16+
GM_setValue(key, value);
17+
console.log(`数据 ${key} 已保存`);
18+
} else {
19+
console.warn('GM存储API不可用,请检查@grant声明');
20+
}
21+
}
22+
23+
// 读取数据示例
24+
export async function retrieveData<T>(key: string, defaultValue: T): Promise<T> {
25+
try {
26+
// 使用GM.getValue (Promise形式)
27+
if (typeof GM !== 'undefined' && GM.getValue) {
28+
return await GM.getValue(key, defaultValue);
29+
}
30+
// 使用GM_getValue (同步形式)
31+
else if (typeof GM_getValue !== 'undefined') {
32+
return GM_getValue(key, defaultValue);
33+
}
34+
// 如果API不可用,返回默认值
35+
return defaultValue;
36+
} catch (error) {
37+
console.error(`读取数据 ${key} 失败:`, error);
38+
return defaultValue;
39+
}
40+
}
41+
42+
// 注册菜单示例
43+
export function registerMenuCommands(): void {
44+
// 检查API可用性
45+
if (typeof GM_registerMenuCommand !== 'undefined') {
46+
// 注册菜单项
47+
GM_registerMenuCommand('设置', () => {
48+
showSettings();
49+
});
50+
51+
GM_registerMenuCommand('重置', () => {
52+
resetSettings();
53+
});
54+
} else if (typeof GM !== 'undefined' && GM.registerMenuCommand) {
55+
GM.registerMenuCommand('设置', () => {
56+
showSettings();
57+
});
58+
59+
GM.registerMenuCommand('重置', () => {
60+
resetSettings();
61+
});
62+
} else {
63+
console.warn('菜单注册API不可用,请检查@grant声明');
64+
}
65+
}
66+
67+
// XHR请求示例
68+
export async function makeRequest(url: string): Promise<any> {
69+
return new Promise((resolve, reject) => {
70+
if (typeof GM_xmlhttpRequest !== 'undefined') {
71+
GM_xmlhttpRequest({
72+
method: 'GET',
73+
url: url,
74+
onload: (response) => {
75+
if (response.status >= 200 && response.status < 300) {
76+
try {
77+
const data = JSON.parse(response.responseText);
78+
resolve(data);
79+
} catch (error) {
80+
resolve(response.responseText);
81+
}
82+
} else {
83+
reject(new Error(`请求失败: ${response.status} ${response.statusText}`));
84+
}
85+
},
86+
onerror: (error) => {
87+
reject(error);
88+
}
89+
});
90+
} else if (typeof GM !== 'undefined' && GM.xmlHttpRequest) {
91+
GM.xmlHttpRequest({
92+
method: 'GET',
93+
url: url,
94+
onload: (response) => {
95+
if (response.status >= 200 && response.status < 300) {
96+
try {
97+
const data = JSON.parse(response.responseText);
98+
resolve(data);
99+
} catch (error) {
100+
resolve(response.responseText);
101+
}
102+
} else {
103+
reject(new Error(`请求失败: ${response.status} ${response.statusText}`));
104+
}
105+
},
106+
onerror: (error) => {
107+
reject(error);
108+
}
109+
});
110+
} else {
111+
// 回退到普通fetch
112+
fetch(url)
113+
.then(response => {
114+
if (!response.ok) {
115+
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
116+
}
117+
return response.json();
118+
})
119+
.then(resolve)
120+
.catch(reject);
121+
}
122+
});
123+
}
124+
125+
// 辅助函数
126+
function showSettings(): void {
127+
console.log('显示设置面板');
128+
// 在这里实现显示设置面板的逻辑
129+
}
130+
131+
function resetSettings(): void {
132+
console.log('重置设置');
133+
// 在这里实现重置设置的逻辑
134+
}

src/index.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,36 @@
11
import bar from "./bar_module/bar";
22
import foo from "./foo_module/foo";
3+
import { storeData, retrieveData, registerMenuCommands, makeRequest } from "./gm_api_example/gm_api_usage";
34

5+
// 基本示例函数
46
foo();
57
bar();
68

9+
// 油猴API使用示例
10+
async function main() {
11+
console.log("油猴脚本开始运行...");
12+
13+
// 注册菜单命令
14+
registerMenuCommands();
15+
16+
// 存储数据示例
17+
storeData("lastRun", new Date().toISOString());
18+
19+
// 读取数据示例
20+
const lastRun = await retrieveData<string>("lastRun", "从未运行");
21+
console.log(`上次运行时间: ${lastRun}`);
22+
23+
// API请求示例 (注意:只有在添加了相应的@grant权限后才能工作)
24+
try {
25+
// 这里使用一个公开API作为示例
26+
const data = await makeRequest("https://jsonplaceholder.typicode.com/todos/1");
27+
console.log("API请求结果:", data);
28+
} catch (error) {
29+
console.error("API请求失败:", error);
30+
}
31+
}
32+
33+
// 运行主函数
34+
main().catch(error => console.error("脚本运行出错:", error));
35+
736

0 commit comments

Comments
 (0)