文档 | Tampermonkey

shenhuanjie
shenhuanjie
Published on 2025-04-23 / 20 Visits
0
0

2025-04-23-obtc.jpg

2025-04-22 16:00:17

原文链接https://www.tampermonkey.net/documentation.php

用户脚本头部

@name

脚本名称。通过添加语言环境后缀实现国际化。

// @name    A test
// @name:de  Ein Test

@namespace

脚本的命名空间。

版权声明,显示在脚本编辑器头部(脚本名称正下方)。

@version

脚本版本号,用于更新检查,每次更新需递增。
版本号按顺序比较优先级,例如:

  • Alpha-v1 < Alpha-v2
  • 16.4 == 16.04
  • 2023-08-17_14-04 == 2023-08-17_14-04.0

@description

简短核心描述。通过添加语言环境后缀实现国际化。

// @description    This userscript does wonderful things
// @description:de  Dieses Userscript tut wundervolle Dinge

@icon, @iconURL, @defaulticon

低分辨率脚本图标。

@icon64, @icon64URL

64x64像素脚本图标。若同时存在@icon@icon图片会在选项页部分位置缩放显示。

@grant

用于白名单GM_*/GM.*函数、unsafeWindow对象及部分window功能函数。

// @grant GM_setValue    // @grant GM_getValue
// @grant GM.setValue    // @grant GM.getValue
// @grant GM_setClipboard  // @grant unsafeWindow
// @grant window.close     // @grant window.focus
// @grant window.onurlchange

关闭/聚焦标签页功能需显式声明。若@grant none,则禁用沙盒模式(仅GM_info可用,无GM_*函数)。

// @grant none

未声明@grant时默认空列表(与none模式不同)。

@author

脚本作者信息。

@homepage, @homepageURL, @website, @source

作者主页链接,用于选项页脚本名称跳转。若@namespacehttp://开头,其值会被优先使用。

@antifeature

用于披露脚本是否包含盈利功能(如GreasFork要求)。
语法:<tag> <type> <description>
<type>可选值:ads(广告)、tracking(追踪)、miner(挖矿)。

// @antifeature       ads         We show you ads
// @antifeature:fr    ads         Nous vous montrons des publicités
// @antifeature       tracking    We have some sort of analytics included
// @antifeature       miner       We use your computer's resources to mine a crypto currency

通过语言环境后缀实现国际化。

@require

指定在脚本运行前加载执行的JavaScript文件。
注意@require加载的脚本及其"use strict"会影响用户脚本的严格模式!

// @require https://code.jquery.com/jquery-2.1.4.min.js
// @require https://code.jquery.com/jquery-2.1.3.min.js#sha256=23456...
// @require https://code.jquery.com/jquery-2.1.2.min.js#md5=34567...,sha256=6789...
// @require tampermonkey://vendor/jquery.js
// @require tampermonkey://vendor/jszip/jszip.js

支持子资源完整性(SRI)校验,允许多个标签。

@resource

预加载资源,可通过GM_getResourceURL/GM_getResourceText访问。

// @resource icon1       http://www.tampermonkey.net/favicon.ico
// @resource icon2       /images/icon.png
// @resource html        http://www.tampermonkey.net/index.html
// @resource xml         http://www.tampermonkey.net/crx/tampermonkey.xml
// @resource SRIsecured1 http://www.tampermonkey.net/favicon.ico#md5=123434...
// @resource SRIsecured2 http://www.tampermonkey.net/favicon.ico#md5=123434...;sha256=234234...

支持SRI校验,允许多个标签。

@include

指定脚本运行的页面,允许多个标签。不支持URL哈希参数,需通过window.onurlchange匹配无哈希路径。

// @include http://www.tampermonkey.net/*
// @include http://*
// @include https://*
// @include /^https:\/\/www\.tampermonkey\.net\/.*$/
// @include *

注意*://tmnk.net/*会匹配包含tmnk.net的所有URL(如https://example.com/?http://tmnk.net/)。Tampermonkey对含://@include@match逻辑解析,://前的*仅匹配非:字符,确保正确识别协议。

@match

定义脚本运行的URL模式,格式为:

// @match <protocol>://<domain><path>
  • protocol:协议(http/https),*匹配两者
  • domain:域名,支持通配符(如*.tmnk.net匹配子域名)
  • path:路径,*匹配任意内容
    示例:
// @match *://*/*          // 所有协议、域名、路径
// @match https://*/*       // 仅HTTPS协议
// @match http://*/foo*     // 以/foo开头的路径
// @match https://*.tampermonkey.net/foo*bar  // 特定子域名和路径

不支持<all_urls>,协议部分接受http*://,允许多标签。

@exclude

排除@include/@match匹配的URL,允许多标签。

@run-at

定义脚本注入时机(首次可能执行时间)。依赖@require的脚本可能因加载延迟在文档加载后执行。

  • document-start:尽快注入
  • document-bodybody元素存在时注入
  • document-endDOMContentLoaded事件后注入
  • document-idle:默认值,DOMContentLoaded后注入
  • context-menu:上下文菜单点击时注入(忽略@include/@exclude,未来可能调整)

@run-in v5.3+

控制脚本注入的浏览器上下文:

  • normal-tabs:仅普通标签页(默认)
  • incognito-tabs:仅无痕标签页(Firefox中为非默认cookie存储标签)
  • container-id-XX:指定容器ID的标签页(通过GM_info.container获取容器ID)
    未声明时默认注入所有标签页。

@sandbox 4.18+

指定脚本运行环境(优先级:MAIN_WORLD > USERSCRIPT_WORLD > ISOLATED_WORLD):

  • raw:兼容模式,强制注入页面上下文(MAIN_WORLD),CSP限制时回退其他环境
  • JavaScript:需访问unsafeWindow,Firefox中创建USERSCRIPT_WORLD绕过CSP,其他浏览器回退raw
  • DOM:仅需DOM访问,注入扩展上下文(ISOLATED_WORLD
// @sandbox JavaScript

@tag

添加脚本标签(显示在脚本列表,需系统标签列表包含),用于分类或标记脚本类型。

// ==UserScript==
// @name         My Script
// @tag          productivity
// ==/UserScript==

@connect

白名单GM_xmlhttpRequest允许访问的域名(含子域名),<value>支持:

  • 域名(如example.com,含子域名)
  • self(当前页面域名)
  • localhost(本地主机)
  • IP地址(如1.2.3.4
  • *(所有域名)
    最佳实践:声明已知域名 + @connect *,避免用户频繁确认。
// @connect tmnk.net       // @connect www.tampermonkey.net
// @connect self           // @connect localhost
// @connect 8.8.8.8        // @connect *

兼容@domain标签,允许多标签。

@noframes

脚本在主页面运行,不在iframe中执行。

@updateURL

脚本更新地址(需配合@version启用更新检查)。

@downloadURL

检测到更新时的下载地址,none表示禁用更新检查。

@supportURL

用户反馈问题和获取支持的链接。

@webRequest 实验性API,可能变更

(Manifest v3版本Tampermonkey 5.2+及Chrome衍生版不再支持)
通过JSON规则预处理网络请求,支持在脚本加载前生效。

@unwrap

无沙盒和包装器注入脚本(适用于Scriptlets)。

应用程序编程接口

unsafeWindow

访问页面的window对象(而非Tampermonkey扩展的window),用于获取页面定义的库或变量。

子资源完整性(SRI)

通过哈希校验确保@require/@resource加载的外部资源未被篡改。支持MD5/SHA-256(其他哈希依赖window.crypto),多哈希时取最后一个支持的格式(逗号/分号分隔)。

// @resource SRIsecured1 http://example.com/favicon1.ico#md5=ad34bb...
// @require  https://code.jquery.com/jquery-3.6.0.min.js#sha256=/xUj+3OJU...ogEvDej/m4=

GM_addElement(tag_name, attributes)

创建并注入HTML元素,支持CSP受限场景。

GM_addElement('script', { textContent: 'window.foo = "bar";' }); // 注入脚本
GM_addElement(document.body, 'img', { src: 'image.png' });       // 插入图片

GM_addStyle(css)

向文档添加样式,返回注入的<style>元素。

GM_download(details)

下载文件,支持URL/Blob/File对象,配置项包括:

  • url:文件地址
  • name:文件名(需白名单扩展名)
  • headers:请求头
  • saveAs:是否提示保存路径
  • conflictAction:文件冲突处理(uniquify/overwrite/prompt
GM_download("http://example.com/file.txt", "file.txt"); // 简单下载
const download = GM_download({ url: "file.txt", saveAs: true });
setTimeout(() => download.abort(), 5000); // 5秒后取消下载

GM_getResourceText(name)

获取@resource预加载的文本资源(如JS/CSS)。

const scriptText = GM_getResourceText("myscript.js");
const script = document.createElement("script");
script.textContent = scriptText;
document.body.appendChild(script);

GM_getResourceURL(name)

获取@resource预加载资源的URL(如图片/CSS)。

const imageUrl = GM_getResourceURL("myimage.png");
const image = document.createElement("img");
image.src = imageUrl;
document.body.appendChild(image);

注意:Promise版本为GM.getResourceUrl(小写url)。

GM_info

获取脚本和Tampermonkey信息,包含:

  • container:容器ID(Firefox专用)
  • downloadMode:下载模式(native/disabled/browser
  • script:脚本元数据(名称、版本、匹配规则等)

GM_log(message)

向控制台输出日志。

GM_notification(details)

显示通知,支持配置:

  • text:通知内容
  • title:标题
  • image:图标URL
  • url:点击跳转地址
  • timeout:自动关闭时间(毫秒)
GM_notification({
  text: "通知内容",
  title: "标题",
  url: "https://example.com",
  onclick: (event) => event.preventDefault() // 阻止默认跳转
});

GM_openInTab(url, options)

打开新标签页,支持参数:

  • active:是否激活新标签(默认false
  • incognito:是否无痕模式
  • insert:标签位置(默认末尾)
GM_openInTab("https://www.example.com/"); // 简单打开

GM_registerMenuCommand(name, callback, options)

添加浏览器菜单命令,支持快捷键和配置:

const menuId = GM_registerMenuCommand("显示提示", () => alert("点击"), {
  accessKey: "a", // 快捷键
  autoClose: true // 点击后关闭菜单
});

GM_unregisterMenuCommand(menuCmdId)

移除已注册的菜单命令。

GM_setClipboard(data, info, cb)

设置剪贴板内容,支持text/html类型:

GM_setClipboard("剪贴板文本", "text", () => console.log("设置成功"));

GM_getTab(callback)

获取当前标签页持久化数据,支持回调或Promise:

GM_getTab((tab) => tab.newInfo = "数据"); // 存储数据

GM_saveTab(tab, cb)

保存标签页数据,配合GM_getTab使用。

GM_getTabs(callback)

获取所有保存的标签页数据。

GM_setValue(key, value)

存储键值对(支持对象/数组/基本类型):

GM_setValue("theme", "dark"); // 同步存储
await GM.setValue("lang", "zh-CN"); // 异步存储

GM_getValue(key, defaultValue)

获取存储值,不存在时返回默认值:

const theme = GM_getValue("theme", "light");

GM_deleteValue(key)

删除指定键。

GM_listValues()

获取所有存储的键名:

const keys = GM_listValues(); // 同步获取
const asyncKeys = await GM.listValues(); // 异步获取

GM_setValues(values) v5.3+

批量设置多个键值对:

GM_setValues({ theme: "dark", lang: "zh" });

GM_getValues(keysOrDefaults) v5.3+

批量获取值,支持键数组或默认值对象:

const values = GM_getValues(["theme", "lang"]); // 获取指定键
const defaults = GM_getValues({ theme: "light", lang: "en" }); // 带默认值

GM_deleteValues(keys) v5.3+

批量删除键:

GM_deleteValues(["theme", "lang"]);

GM_addValueChangeListener(key, callback)

监听存储值变化,回调参数:(key, oldValue, newValue, remote)remote表示是否来自其他标签页)。

GM_removeValueChangeListener(listenerId)

移除值变化监听器。

GM_xmlhttpRequest(details)

发送HTTP请求,支持配置:

  • method:请求方法(GET/POST等)
  • url:目标地址(支持Blob/File)
  • headers:请求头
  • responseType:响应类型(arraybuffer/blob/json/stream
GM_xmlhttpRequest({
  method: "GET",
  url: "https://example.com",
  onload: (response) => console.log(response.responseText)
});

Promise版本为GM.xmlHttpRequest(大写H)。

GM_webRequest(rules, listener) 实验性API

注册网络请求规则(如拦截/重定向),Manifest v3不支持。

GM_cookie.list(details, callback)

获取Cookie,支持过滤条件(URL/域名/名称等):

GM_cookie.list({ name: "mycookie" }, (cookies, error) => {
  if (!error) console.log(cookies);
});

GM_cookie.set(details, callback)

设置Cookie,支持完整属性(过期时间/路径/安全标志等):

GM_cookie.set({
  url: "https://example.com",
  name: "session",
  value: "token",
  expirationDate: Date.now() / 1000 + 86400 // 24小时后过期
});

GM_cookie.delete(details, callback)

删除指定Cookie:

GM_cookie.delete({ name: "cookie_name" }, (error) => {
  if (!error) console.log("删除成功");
});

window.onurlchange

监听单页应用(SPA)的URL变化,需在@grant中声明:

// @grant window.onurlchange
window.addEventListener("urlchange", (info) => {
  // 处理URL变化
});

window.close

关闭标签页(需@grant window.close,无法关闭最后一个标签页):

// @grant window.close
if (condition) window.close();

window.focus

聚焦窗口(unsafeWindow.focus可能因用户设置失败,需@grant window.focus):

// @grant window.focus
if (condition) window.focus();

CDATA元数据存储

通过兼容性选项支持CDATA格式存储元数据,Tampermonkey自动检测是否启用:

var inline_src = (
  <![CDATA[
    console.log('Hello World!');
  ]]>
).toString();
eval(inline_src);

Comment