Loading...
Loading...
Compare original and translation side by side
// ==UserScript==
// @name My Script Name // ← CUSTOMISE: Unique script name
// @namespace https://example.com/scripts/ // ← CUSTOMISE: Your unique namespace
// @version 1.0.0 // ← INCREMENT on updates
// @description Brief description of the script // ← CUSTOMISE: What it does
// @author Your Name // ← CUSTOMISE: Your name
// @match https://example.com/* // ← CUSTOMISE: Target URL pattern
// @grant none // ← ADD permissions as needed
// @run-at document-idle // ← ADJUST timing if needed
// ==/UserScript==
(function() {
'use strict';
// Your code here
console.log('Script loaded!');
})();// ==UserScript==
// @name My Script Name // ← 自定义:唯一的脚本名称
// @namespace https://example.com/scripts/ // ← 自定义:你的唯一命名空间
// @version 1.0.0 // ← 更新时递增版本号
// @description Brief description of the script // ← 自定义:脚本功能简介
// @author Your Name // ← 自定义:你的姓名
// @match https://example.com/* // ← 自定义:目标URL匹配规则
// @grant none // ← 根据需要添加权限
// @run-at document-idle // ← 根据需要调整注入时机
// ==/UserScript==
(function() {
'use strict';
// 你的代码写在这里
console.log('Script loaded!');
})();| Tag | Required | Purpose | Example |
|---|---|---|---|
| Yes | Script name (supports i18n with | |
| Recommended | Unique identifier namespace | |
| Yes* | Version for updates (*required for auto-update) | |
| Recommended | What the script does | |
| Yes** | URLs to run on (**or @include) | |
| Situational | API permissions (use | |
| Optional | When to inject (default: | |
| 标签 | 是否必填 | 用途 | 示例 |
|---|---|---|---|
| 是 | 脚本名称(支持通过 | |
| 推荐 | 唯一标识符命名空间 | |
| 是* | 版本号(*自动更新必填) | |
| 推荐 | 脚本功能说明 | |
| 是** | 脚本运行的URL(**或使用@include) | |
| 按需 | API权限(使用 | |
| 可选 | 脚本注入时机(默认: | |
// Exact domain
// @match https://example.com/*
// All subdomains
// @match https://*.example.com/*
// HTTP and HTTPS
// @match *://example.com/*
// Specific path
// @match https://example.com/app/*
// Exclude paths (use with @match)
// @exclude https://example.com/admin/*// 精确匹配域名
// @match https://example.com/*
// 匹配所有子域名
// @match https://*.example.com/*
// 匹配HTTP和HTTPS协议
// @match *://example.com/*
// 匹配特定路径
// @match https://example.com/app/*
// 排除特定路径(需与@match配合使用)
// @exclude https://example.com/admin/*| You Need To... | Grant This |
|---|---|
| Store persistent data | |
| Make cross-origin requests | |
| Add custom CSS | |
| Access page's window | |
| Show notifications | |
| Add menu commands | |
| Detect URL changes (SPA) | |
// Disable sandbox (no GM_* except GM_info)
// @grant none
// Cross-origin requests require @connect
// @grant GM_xmlhttpRequest
// @connect api.example.com
// @connect *.googleapis.com| 你需要... | 需授权 |
|---|---|
| 存储持久化数据 | |
| 发起跨域请求 | |
| 添加自定义CSS | |
| 访问页面的window对象 | |
| 显示通知 | |
| 添加菜单命令 | |
| 检测SPA的URL变化 | |
// 禁用沙箱(仅可使用GM_info,不可用其他GM_* API)
// @grant none
// 跨域请求需配合@connect
// @grant GM_xmlhttpRequest
// @connect api.example.com
// @connect *.googleapis.com| Value | When Script Runs | Use Case |
|---|---|---|
| Before DOM exists | Block resources, modify globals early |
| When body exists | Early DOM manipulation |
| At DOMContentLoaded | Most scripts - DOM ready |
| After DOMContentLoaded (default) | Safe default |
| On right-click menu | User-triggered actions |
| 值 | 脚本运行时机 | 适用场景 |
|---|---|---|
| DOM创建前 | 阻止资源加载、提前修改全局变量 |
| body标签存在时 | 早期DOM操作 |
| DOMContentLoaded事件触发时 | 大多数脚本——DOM已就绪 |
| DOMContentLoaded事件后(默认) | 安全的默认选项 |
| 右键菜单触发时 | 用户触发的操作 |
function waitForElement(selector, timeout = 10000) {
return new Promise((resolve, reject) => {
const element = document.querySelector(selector);
if (element) return resolve(element);
const observer = new MutationObserver((mutations, obs) => {
const el = document.querySelector(selector);
if (el) {
obs.disconnect();
resolve(el);
}
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(() => {
observer.disconnect();
reject(new Error(`Element ${selector} not found`));
}, timeout);
});
}
// Usage
waitForElement('#my-element').then(el => {
console.log('Found:', el);
});function waitForElement(selector, timeout = 10000) {
return new Promise((resolve, reject) => {
const element = document.querySelector(selector);
if (element) return resolve(element);
const observer = new MutationObserver((mutations, obs) => {
const el = document.querySelector(selector);
if (el) {
obs.disconnect();
resolve(el);
}
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(() => {
observer.disconnect();
reject(new Error(`Element ${selector} not found`));
}, timeout);
});
}
// 使用示例
waitForElement('#my-element').then(el => {
console.log('找到元素:', el);
});// @grant window.onurlchange
if (window.onurlchange === null) {
window.addEventListener('urlchange', (info) => {
console.log('URL changed to:', info.url);
// Re-run your modifications
});
}// @grant window.onurlchange
if (window.onurlchange === null) {
window.addEventListener('urlchange', (info) => {
console.log('URL已变更为:', info.url);
// 重新执行你的修改逻辑
});
}// @grant GM_xmlhttpRequest
// @connect api.example.com
GM_xmlhttpRequest({
method: 'GET',
url: 'https://api.example.com/data',
headers: { 'Content-Type': 'application/json' },
onload: function(response) {
const data = JSON.parse(response.responseText);
console.log(data);
},
onerror: function(error) {
console.error('Request failed:', error);
}
});// @grant GM_xmlhttpRequest
// @connect api.example.com
GM_xmlhttpRequest({
method: 'GET',
url: 'https://api.example.com/data',
headers: { 'Content-Type': 'application/json' },
onload: function(response) {
const data = JSON.parse(response.responseText);
console.log(data);
},
onerror: function(error) {
console.error('请求失败:', error);
}
});// @grant GM_addStyle
GM_addStyle(`
.my-custom-class {
background: #f0f0f0;
padding: 10px;
border-radius: 5px;
}
#hide-this-element {
display: none !important;
}
`);// @grant GM_addStyle
GM_addStyle(`
.my-custom-class {
background: #f0f0f0;
padding: 10px;
border-radius: 5px;
}
#hide-this-element {
display: none !important;
}
`);// @grant GM_setValue
// @grant GM_getValue
// @grant GM_registerMenuCommand
const settings = {
enabled: GM_getValue('enabled', true),
theme: GM_getValue('theme', 'dark')
};
GM_registerMenuCommand('Toggle Enabled', () => {
settings.enabled = !settings.enabled;
GM_setValue('enabled', settings.enabled);
location.reload();
});// @grant GM_setValue
// @grant GM_getValue
// @grant GM_registerMenuCommand
const settings = {
enabled: GM_getValue('enabled', true),
theme: GM_getValue('theme', 'dark')
};
GM_registerMenuCommand('切换启用状态', () => {
settings.enabled = !settings.enabled;
GM_setValue('enabled', settings.enabled);
location.reload();
});// @require https://code.jquery.com/jquery-3.6.0.min.js
// With integrity hash (recommended)
// @require https://code.jquery.com/jquery-3.6.0.min.js#sha256-/xUj+3OJU...
// Built-in libraries
// @require tampermonkey://vendor/jquery.js// @require https://code.jquery.com/jquery-3.6.0.min.js
// 带完整性哈希(推荐)
// @require https://code.jquery.com/jquery-3.6.0.min.js#sha256-/xUj+3OJU...
// 内置库
// @require tampermonkey://vendor/jquery.js// @resource myCSS https://example.com/style.css
// @grant GM_getResourceText
// @grant GM_addStyle
const css = GM_getResourceText('myCSS');
GM_addStyle(css);// @resource myCSS https://example.com/style.css
// @grant GM_getResourceText
// @grant GM_addStyle
const css = GM_getResourceText('myCSS');
GM_addStyle(css);This script adds a dark mode toggle to Example.com and remembers the user's preference.
// ==UserScript==
// @name Example.com Dark Mode
// ...
// ==/UserScript==Installation: Copy/paste into Tampermonkey dashboard Customisation: Changeto adjust the background colour Permissions: UsesDARK_BG_COLOR/GM_setValueto remember preference Browsers: Chrome and FirefoxGM_getValue
该脚本为Example.com添加深色模式切换功能,并记住用户的偏好设置。
// ==UserScript==
// @name Example.com Dark Mode
// ...
// ==/UserScript==安装方法: 复制粘贴到Tampermonkey控制台 可自定义项: 修改变量调整背景颜色 使用的权限: 使用DARK_BG_COLOR/GM_setValue保存用户偏好 支持浏览器: Chrome和FirefoxGM_getValue
*://*/**://*/*| File | When to Load | Content |
|---|---|---|
| header-reference.md | Header syntax questions | All @tags with examples |
| url-matching.md | URL pattern questions | @match, @include, @exclude |
| patterns.md | Implementation patterns | Common script patterns |
| sandbox-modes.md | Security/isolation | Execution contexts |
| 文件 | 加载场景 | 内容 |
|---|---|---|
| header-reference.md | 头部语法问题 | 所有@标签及示例 |
| url-matching.md | URL规则问题 | @match、@include、@exclude |
| patterns.md | 实现模式问题 | 常见脚本模式 |
| sandbox-modes.md | 安全/隔离问题 | 执行上下文 |
| File | When to Load | Content |
|---|---|---|
| api-sync.md | GM_* function usage | Sync API documentation |
| api-async.md | GM.* promise usage | Async API documentation |
| api-storage.md | Data persistence | setValue, getValue, listeners |
| http-requests.md | HTTP requests | GM_xmlhttpRequest |
| web-requests.md | Request interception | GM_webRequest (Firefox) |
| api-cookies.md | Cookie manipulation | GM_cookie |
| api-dom-ui.md | DOM/UI manipulation | addElement, addStyle, unsafeWindow |
| api-tabs.md | Tab management | getTab, saveTab, openInTab |
| api-audio.md | Audio control | Mute/unmute tabs |
| 文件 | 加载场景 | 内容 |
|---|---|---|
| api-sync.md | GM_*函数使用问题 | 同步API文档 |
| api-async.md | GM.* promise使用问题 | 异步API文档 |
| api-storage.md | 数据持久化问题 | setValue、getValue、监听器 |
| http-requests.md | HTTP请求问题 | GM_xmlhttpRequest |
| web-requests.md | 请求拦截问题 | GM_webRequest(Firefox) |
| api-cookies.md | Cookie操作问题 | GM_cookie |
| api-dom-ui.md | DOM/UI操作问题 | addElement、addStyle、unsafeWindow |
| api-tabs.md | 标签页管理问题 | getTab、saveTab、openInTab |
| api-audio.md | 音频控制问题 | 标签页静音/取消静音 |
| File | When to Load | Content |
|---|---|---|
| common-pitfalls.md | Script issues | What breaks scripts |
| debugging.md | Troubleshooting | How to debug |
| browser-compatibility.md | Cross-browser | Chrome vs Firefox |
| security-checklist.md | Pre-delivery | Security validation |
| version-numbering.md | Version strings | Comparison rules |
| 文件 | 加载场景 | 内容 |
|---|---|---|
| common-pitfalls.md | 脚本问题 | 导致脚本失效的原因 |
| debugging.md | 故障排查 | 调试方法 |
| browser-compatibility.md | 跨浏览器问题 | Chrome与Firefox差异 |
| security-checklist.md | 交付前检查 | 安全验证 |
| version-numbering.md | 版本字符串问题 | 版本比较规则 |