The name of the script.
Internationalization is done by adding an appendix naming the locale.
// @name A test
// @name:de Ein Test
The namespace of the script.
A copyright statement shown at the header of the script's editor right below the script name.
The script version. This is used for the update check and needs to be increased at every update.
In this list the next entry is considered to be a higher version number, eg: Alpha-v1
< Alpha-v2
and 16.4
== 16.04
Alpha-v1
Alpha-v2
Alpha-v10
Beta
0.5pre3
0.5prelimiary
0.6pre4
0.6pre5
0.7pre4
0.7pre10
1.-1
1
== 1.
== 1.0
== 1.0.0
1.1a
1.1aa
1.1ab
1.1b
1.1c
1.1.-1
1.1
== 1.1.0
== 1.1.00
1.1.1.1.1
1.1.1.1.2
1.1.1.1
1.10.0-alpha
1.10
== 1.10.0
1.11.0-0.3.7
1.11.0-alpha
1.11.0-alpha.1
1.11.0-alpha+1
1.12+1
== 1.12+1.0
1.12+1.1
== 1.12+1.1.0
1.12+2
1.12+2.1
1.12+3
1.12+4
1.12
2.0
16.4
== 16.04
2023-08-17.alpha
2023-08-17
2023-08-17_14-04
== 2023-08-17_14-04.0
2023-08-17+alpha
2023-09-11_14-0
A short significant description.
Internationalization is done by adding an appendix naming the locale.
// @description This userscript does wonderful things
// @description:de Dieses Userscript tut wundervolle Dinge
The script icon in low res.
This scripts icon in 64x64 pixels. If this tag, but @icon
is given the @icon
image will be scaled at some places at the options page.
@grant
is used to whitelist GM_*
and GM.*
functions, the unsafeWindow
object and some powerful window
functions.
// @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
Since closing and focusing tabs is a powerful feature this needs to be added to the @grant
statements as well.
In case @grant
is followed by none
the sandbox is disabled. In this mode no GM_*
function but the GM_info
property will be available.
// @grant none
If no @grant
tag is given an empty list is assumed. However this different from using none
.
The scripts author.
The authors homepage that is used at the options page to link from the scripts name to the given page. Please note that if the @namespace
tag starts with http://
its content will be used for this too.
This tag allows script developers to disclose whether they monetize their scripts. It is for example required by GreasyFork.
Syntax: <tag> <type> <description>
<type> can have the following values:
// @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
Internationalization is done by adding an appendix naming the locale.
Points to a JavaScript file that is loaded and executed before the script itself starts running.
Note: the scripts loaded via @require
and their "use strict" statements might influence the userscript's strict mode!
// @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
Please check the sub-resource integrity section for more information how to ensure integrity.
Multiple tag instances are allowed.
Preloads resources that can by accessed via GM_getResourceURL
and GM_getResourceText
by the script.
// @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...
Please check the sub-resource integrity section for more information how to ensure integrity.
Multiple tag instances are allowed.
The pages on that a script should run. Multiple tag instances are allowed. @include doesn't support the URL hash parameter. You have to match the path without the hash parameter and make use of window.onurlchange
// @include http://www.tampermonkey.net/*
// @include http://*
// @include https://*
// @include /^https:\/\/www\.tampermonkey\.net\/.*$/
// @include *
Note: When writing something like *://tmnk.net/*
many script developers expect the script to run at tmnk.net
only, but this is not the case.
It also runs at https://example.com/?http://tmnk.net/
as well.
Therefore Tampermonkey interprets @includes
that contain a ://
a little bit like @match
. Every *
before ://
only matches everything except :
characters to makes sure only the URL scheme is matched.
Also, if such an @include
contains a /
after ://
, then everything between those strings is treat as host, matching everything except /
characters. The same applies to *
directly following ://
.
In Tampermonkey, the @match
directive is used to specify the web pages that your script should run on.
The value of @match
should be a URL pattern that matches the pages you want your script to run on. Here are the parts of the URL pattern that you'll need to set:
// @match <protocol>://<domain><path>
http
or https
. *
matches both.tmnk.com
. You can use the wildcard character this way *.tmnk.net
to match tmnk.net
and any sub-domain of it like www.tmnk.net
.*
to match any part of the path.Please check this documentation to get more information about match pattern. Note: the <all_urls>
statement is not yet supported and the scheme part also accepts http*://
.
Multiple tag instances are allowed.
More examples:
// @match *://*/*
// @match https://*/*
// @match http://*/foo*
// @match https://*.tampermonkey.net/foo*bar
Exclude URLs even it they are included by @include
or @match
.
Multiple tag instances are allowed.
Defines the moment the script is injected.
In opposition to other script handlers, @run-at
defines the first possible moment a script wants to run.
This means it may happen, that a script that uses the @require
tag may be executed after the document is already loaded, cause fetching the required script took that long.
Anyhow, all DOMNodeInserted
and DOMContentLoaded
events fired after the given injection moment are cached and delivered to listeners registered via the sandbox's window.addEventListener
method.
// @run-at document-start
The script will be injected as fast as possible.
// @run-at document-body
The script will be injected if the body element exists.
// @run-at document-end
The script will be injected when or after the DOMContentLoaded event was dispatched.
// @run-at document-idle
The script will be injected after the DOMContentLoaded event was dispatched. This is the default value if no @run-at
tag is given.
// @run-at context-menu
The script will be injected if it is clicked at the browser context menu.
Note: all @include
and @exclude
statements will be ignored if this value is used, but this may change in the future.
Defines the type of browser context in which the script is injected. This meta key allows you to control whether the script should run in normal browsing tabs, incognito tabs, or both. This provides flexibility in determining the script's behavior based on the privacy context of the browsing session.
// @run-in normal-tabs
The script will be injected only in normal browsing tabs (non-incognito mode, default container).
// @run-in incognito-tabs
The script will be injected only in incognito browsing tabs (private mode). In Firefox, this means all tabs that don't use the default cookie store.
Firefox supports containers, which allow you to separate your browsing activities into distinct contexts. You can specify the container ID in the @run-in
tag to control the script's behavior based on the container context.
// @run-in container-id-2
// @run-in container-id-3
The script will be injected only in tabs that belong to the specified containers. The container ID can be found by checking GM_info.container
when the script is running in the desired container context.
If no @run-in
tag is specified, the script defaults to being injected in all tabs.
@sandbox
allows Tampermonkey to decide where the userscript is injected:
MAIN_WORLD
- the pageISOLATED_WORLD
- the extension's content scriptUSERSCRIPT_WORLD
- a special context created for userscriptsBut instead of specifying an environment, the userscript can express what exactly it needs access to. @sandbox
supports three possible arguments:
raw
"Raw" access means that a script for compatibility reasons always needs to run in page context, the MAIN_WORLD
.
At the moment this mode is the default if @sandbox
is omitted.
If injection into the MAIN_WORLD
is not possible (e.g. because of a CSP) the userscript will be injected into other (enabled) sandboxes according to the order of this list.
JavaScript
"JavaScript" access mode means that this script needs access to unsafeWindow
.
At Firefox a special context, the USERSCRIPT_WORLD
, is created which also bypasses existing CSPs. It however, might create new issues since now cloneInto
and exportFunction
are necessary to share objects with the page.
raw
mode is used as fallback at other browsers.
DOM
Use this access mode if the script only needs DOM and no direct unsafeWindow
access.
If enabled these scripts are executed inside the extension context, the ISOLATED_WORLD
, or at any other enabled context otherwise, because they all grant DOM access.
// @sandbox JavaScript
You can add tags to your script which will be visible in the script list if this tag is part of your system's tag list. Tags can be useful to categorize your scripts or to mark them as a certain type. The list of tags can be found at the script's settings page.
Example of a script with tags
// ==UserScript==
// @name My Script
// @tag productivity
// ==/UserScript==
This tag defines the domains (no top-level domains) including subdomains which are allowed to be retrieved by GM_xmlhttpRequest
// @connect <value>
<value>
can be:
example.com
(this will also allow all subdomains).subdomain.example.com
.self
to whitelist the domain the script is currently running at.localhost
to access the localhost.1.2.3.4
.*
.If it's not possible to declare all domains a userscript might connect to then it's a good practice to do the following:
@connect *
to the script to allow Tampermonkey to offer an "Always allow all domains" button.Users can also whitelist all requests by adding *
to the user domain whitelist at the script settings tab.
Notes:
@domain
tags are interpreted as well.More examples:
// @connect tmnk.net
// @connect www.tampermonkey.net
// @connect self
// @connect localhost
// @connect 8.8.8.8
// @connect *
This tag makes the script running on the main pages, but not at iframes.
An update URL for the userscript.
Note: a @version
tag is required to make update checks work.
Defines the URL where the script will be downloaded from when an update was detected. If the value none is used, then no update check will be done.
Defines the URL where the user can report issues and get personal support.
@webRequest
takes a JSON document that matches GM_webRequest
's rule
parameter. It allows the rules to apply even before the userscript is loaded.
Injects the userscript without any wrapper and sandbox into the page, which might be useful for Scriptlets.
The unsafeWindow
object provides access to the window
object of the page that Tampermonkey is running on, rather than the window
object of the Tampermonkey extension. This can be useful in some cases, such as when a userscript needs to access a JavaScript library or variable that is defined on the page.
Subresource Integrity (SRI) is a security feature that allows userscript developers to ensure that the external resources (such as JavaScript libraries and CSS files) that they include in their userscript have not been tampered with or modified. This is accomplished by generating a cryptographic hash of the resource and including it in @require
and @resource
tags. When the userscript is installed, Tampermonkey will calculate the hash of the resource and compare it to the included hash. If the two hashes do not match, Tampermonkey will refuse to load the resource, preventing attackers from injecting malicious code into your userscript.
The hash component of the URL of @resource
and @require
tags is used for this purpose.
// @resource SRIsecured1 http://example.com/favicon1.ico#md5=ad34bb...
// @resource SRIsecured2 http://example.com/favicon2.ico#md5=ac3434...,sha256=23fd34...
// @require https://code.jquery.com/jquery-2.1.1.min.js#md5=45eef...
// @require https://code.jquery.com/jquery-2.1.2.min.js#md5-ac56d...,sha256-6e789...
// @require https://code.jquery.com/jquery-3.6.0.min.js#sha256-/xUj+3OJU...ogEvDej/m4=
Tampermonkey supports SHA-256
and MD5
hashes natively, all other (SHA-1
, SHA-384
and SHA-512
) depend on window.crypto.
In case multiple hashes (separated by comma or semicolon) are given the last currently supported one is used by Tampermonkey. All hashes need to be encoded in either hex or Base64 format.
GM_addElement
allows Tampermonkey scripts to add new elements to the page that Tampermonkey is running on. This can be useful for a variety of purposes, such as adding script
and img
tags if the page limits these elements with a content security policy (CSP).
It creates an HTML element specified by "tag_name" and applies all given "attributes" and returns the injected HTML element. If a "parent_node" is given, then it is attached to it or to document head or body otherwise.
For suitable "attributes", please consult the appropriate documentation. For example:
GM_addElement('script', {
textContent: 'window.foo = "bar";'
});
GM_addElement('script', {
src: 'https://example.com/script.js',
type: 'text/javascript'
});
GM_addElement(document.getElementsByTagName('div')[0], 'img', {
src: 'https://example.com/image.png'
});
GM_addElement(shadowDOM, 'style', {
textContent: 'div { color: black; };'
});
Note: this feature is experimental and the API may change.
Adds the given style to the document and returns the injected style element.
GM_download
allows userscripts to download a file from a specified URL and save it to the user's local machine.
The GM_download
function takes the following parameters:
details can have the following attributes:
GM_xmlhttpRequest
for more details.uniquify
, overwrite
and prompt
.
Please check this link for more details.The download argument of the onerror callback can have the following attributes:
Returns an object with the following property:
If GM.download
is used it returns a promise that resolves to the download details and also has an abort
function.
Depending on the download mode GM_info
provides a property called downloadMode
which is set to one of the following values: native, disabled or browser.
GM_download("http://example.com/file.txt", "file.txt");
const download = GM_download({
url: "http://example.com/file.txt",
name: "file.txt",
saveAs: true
});
// cancel download after 5 seconds
window.setTimeout(() => download.abort(), 5000);
Note: The browser might modify the desired filename. Especially a file extension might be added if the browser finds this to be safe to download at the current OS.
Allows userscripts to access the text of a resource (such as a JavaScript or CSS file) that has been included in a userscript via @resource
.
The function takes a single parameter, which is the "name" of the resource to retrieve. It returns the text of the resource as a string.
Here is an example of how the function might be used:
const scriptText = GM_getResourceText("myscript.js");
const scriptText2 = await GM.getResourceText("myscript.js");
const script = document.createElement("script");
script.textContent = scriptText;
document.body.appendChild(script);
GM_getResourceURL
allows userscripts to access the URL of a resource (such as a CSS or image file) that has been included in the userscript via a @resource
tag at the script header.
The function takes a single parameter, which is the "name" of the resource to retrieve. It returns the URL of the resource as a string.
const imageUrl = GM_getResourceURL("myimage.png");
const imageUrl2 = await GM.getResourceUrl("myimage.png");
const image = document.createElement("img");
image.src = imageUrl;
document.body.appendChild(image);
Important:: The promise-based version of this function is called GM.getResourceUrl
(with a lowercase "u" and "l" in "Url").
Get some info about the script and TM. The object might look like this:
type ScriptGetInfo = {
container?: { // 5.3+ | Firefox only
id: string,
name?: string
},
downloadMode: string,
isFirstPartyIsolation?: boolean,
isIncognito: boolean,
sandboxMode: SandboxMode, // 4.18+
scriptHandler: string,
scriptMetaStr: string | null,
scriptUpdateURL: string | null,
scriptWillUpdate: boolean,
userAgentData: UADataValues, // 4.19+
version?: string,
script: {
antifeatures: { [antifeature: string]: { [locale: string]: string } },
author: string | null,
blockers: string[],
connects: string[],
copyright: string | null,
deleted?: number | undefined,
description_i18n: { [locale: string]: string } | null,
description: string,
downloadURL: string | null,
excludes: string[],
fileURL: string | null,
grant: string[],
header: string | null,
homepage: string | null,
icon: string | null,
icon64: string | null,
includes: string[],
lastModified: number,
matches: string[],
name_i18n: { [locale: string]: string } | null,
name: string,
namespace: string | null,
position: number,
resources: Resource[],
supportURL: string | null,
system?: boolean | undefined,
'run-at': string | null,
'run-in': string[] | null, // 5.3+
unwrap: boolean | null,
updateURL: string | null,
version: string,
webRequest: WebRequestRule[] | null,
options: {
check_for_updates: boolean,
comment: string | null,
compatopts_for_requires: boolean,
compat_wrappedjsobject: boolean,
compat_metadata: boolean,
compat_foreach: boolean,
compat_powerful_this: boolean | null,
sandbox: string | null,
noframes: boolean | null,
unwrap: boolean | null,
run_at: string | null,
run_in: string | null, // 5.3+
override: {
use_includes: string[],
orig_includes: string[],
merge_includes: boolean,
use_matches: string[],
orig_matches: string[],
merge_matches: boolean,
use_excludes: string[],
orig_excludes: string[],
merge_excludes: boolean,
use_connects: string[],
orig_connects: string[],
merge_connects: boolean,
use_blockers: string[],
orig_run_at: string | null,
orig_run_in: string[] | null, // 5.3+
orig_noframes: boolean | null
}
}
}
};
type SandboxMode = 'js' | 'raw' | 'dom';
type Resource = {
name: string,
url: string,
error?: string,
content?: string,
meta?: string
};
type WebRequestRule = {
selector: { include?: string | string[], match?: string | string[], exclude?: string | string[] } | string,
action: string | {
cancel?: boolean,
redirect?: {
url: string,
from?: string,
to?: string
} | string
}
};
type UADataValues = {
brands?: {
brand: string;
version: string;
}[],
mobile?: boolean,
platform?: string,
architecture?: string,
bitness?: string
}
Log a message to the console.
GM_notification
allows users to display notifications on the screen, using a provided message and other optional parameters.
The function takes several parameters. Either a details object or multiple parameters.
The details object can have the following attributes, from which some can also be used as direct parameter.
The available options include:
GM_notification
again and using the same tag. If you don't provide a tag, a new notification will be created every time.event.preventDefault()
in the onclick
event handler.The function does not return a value.
If no url
and no tag
is provided the notification will closed when the userscript unloads v5.0+(e.g. when the page is reloaded or the tab is closed).
Here is an example of how the function might be used:
GM_notification({
text: "This is the notification message.",
title: "Notification Title",
url: 'https:/example.com/',
onclick: (event) => {
// The userscript is still running, so don't open example.com
event.preventDefault();
// Display an alert message instead
alert('I was clicked!')
}
});
const clicked = await GM.notification({ text: "Click me." });
GM_openInTab
allows userscripts to open a new tab in the browser and navigate to a specified URL.
The function takes two parameters:
A string names "url" containing the URL of the page to open in the new tab.
An optional options object that can be used to customize the behavior of the new tab. The available options include:
The function returns an object with the function close, the listener onclose and a flag called closed.
Here is an example of how the function might be used:
// Open a new tab and navigate to the specified URL
GM_openInTab("https://www.example.com/");
GM_registerMenuCommand
allows userscripts to add a new entry to the userscript's menu in the browser, and specify a function to be called when the menu item is selected.
Menu items created from different frames are merged into a single menu entry if name, title and accessKey are the same.
The function takes three parameters:
options
or accessKey
can be specified.GM_registerMenuCommand
call. If specified, the according menu item will be updated with the new options. If not specified or the menu item can't be found, a new menu item will be created.chrome://extensions/shortcuts
in Chrome, about:addons
+ "Manage Extension Shortcuts" in Firefox)true
. Please note that this setting has no effect on the menu command section that is added to the page's context menu.The function return a menu entry ID that can be used to unregister the command.
Here is an example of how the function might be used:
const menu_command_id_1 = GM_registerMenuCommand("Show Alert", function(event: MouseEvent | KeyboardEvent) {
alert("Menu item selected");
}, {
accessKey: "a",
autoClose: true
});
const menu_command_id_2 = GM_registerMenuCommand("Log", function(event: MouseEvent | KeyboardEvent) {
console.log("Menu item selected");
}, "l");
GM_unregisterMenuCommand
removes an existing entry from the userscript's menu in the browser.
The function takes a single parameter, which is the ID of the menu item to remove. It does not return a value.
Here is an example of how the function might be used:
const menu_command_id = GM_registerMenuCommand(...);
GM_unregisterMenuCommand(menu_command_id);
GM_setClipboard
sets the text of the clipboard to a specified value.
The function takes a parameter "data", which is the string to set as the clipboard text, a parameter "info" and an optional callback function "cb".
"info" can be just a string expressing the type text
or html
or an object like
"cb" is an optional callback function that is called when the clipboard has been set.
{
type: 'text',
mimetype: 'text/plain'
}
GM_setClipboard("This is the clipboard text.", "text", () => console.log("Clipboard set!"));
await GM.setClipboard("This is the newer clipboard text.", "text");
console.log('Clipboard set again!');
The GM_getTab function takes a single parameter, a callback function that will be called with an object that is persistent as long as this tab is open.
GM_getTab((tab) => console.log(tab));
const t = await GM.getTab();
console.log(t);
The GM_saveTab
function allows a userscript to save information about a tab for later use.
The function takes a "tab" parameter, which is an object containing the information to be saved about the tab and an optional callback function "cb".
The GM_saveTab
function saves the provided tab information, so that it can be retrieved later using the GM_getTab
function.
Here is an example of how the GM_saveTab function might be used in a userscript:
GM_getTab(function(tab) {
tab.newInfo = "new!";
GM_saveTab(tab);
});
await GM.saveTab(tab);
In this example, the GM_saveTab
function is called with the tab object returned by the GM_getTab
function, and a new key called "newInfo".
The GM_getTabs
function takes a single parameter: a callback function that will be called with the information about the tabs.
The "tabs" object that is passed to the callback function contains objects, with each object representing the saved tab information stored by GM_saveTab
.
GM_getTabs((tabs) => {
for (const [tabId, tab] of Object.entries(tabs)) {
console.log(`tab ${tabId}`, tab);
}
});
const tabs = await GM.getTabs();
The GM_setValue
allows a userscript to set the value of a specific key in the userscript's storage.
The GM_setValue
function takes two parameters:
null
or of type "object", "string", "number", "undefined" or "boolean".The GM_setValue
function does not return any value. Instead, it sets the provided value for the specified key in the userscript's storage.
Here is an example of how GM_setValue
and its async pendant GM.setValue
might be used in a userscript:
GM_setValue("someKey", "someData");
await GM.setValue("otherKey", "otherData");
The GM_getValue
function allows a userscript to retrieve the value of a specific key in the extension's storage.
It takes two parameters:
The GM_getValue
function returns the value of the specified key from the extension's storage, or the default value if the key does not exist.
Here is an example of how the GM_getValue
function might be used in a userscript:
const someKey = GM_getValue("someKey", null);
const otherKey = await GM.getValue("otherKey", null);
In this example, the GM_getValue
function is called with the key "someKey" and a default value of null.
If the "someKey" key exists in the extension's storage, its value will be returned and stored in the someKey variable.
If the key does not exist, the default value of null will be returned and stored in the savedTab variable.
Deletes "key" from the userscript's storage.
GM_deleteValue("someKey");
await GM.deleteValue("otherKey");
The GM_listValues
function returns a list of keys of all stored data.
const keys = GM_listValues();
const asyncKeys = await GM.listValues();
The GM_setValues
function allows a userscript to set multiple key-value pairs in the userscript's storage simultaneously.
The GM_setValues
function takes one parameter:
null
or of type "object", "string", "number", "undefined" or "boolean".The GM_setValues
function does not return any value. Instead, it sets the provided values for the specified keys in the userscript's storage.
Here is an example of how GM_setValues
and its async counterpart GM.setValues
might be used in a userscript:
GM_setValues({ foo: 1, bar: 2 });
await GM.setValues({ foo: 1, bar: 2 });
The GM_getValues
function allows a userscript to retrieve the values of multiple keys in the extension's storage. It can also provide default values if the keys do not exist.
The GM_getValues
function takes one parameter:
The GM_getValues
function returns an object containing the values of the specified keys from the extension's storage, or the default values if the keys do not exist.
Here is an example of how the GM_getValues
function might be used in a userscript:
const values = GM_getValues(['foo', 'bar']);
const asyncValues = await GM.getValues(['foo', 'bar']);
const defaultValues = GM_getValues({ foo: 1, bar: 2, baz: 3 });
const asyncDefaultValues = await GM.getValues({ foo: 1, bar: 2, baz: 3 });
In this example, the GM_getValues
function is called with an array of keys or an object of default values. It returns an object with the values of the specified keys or the default values if the keys do not exist.
The GM_deleteValues
function allows a userscript to delete multiple keys from the userscript's storage simultaneously.
The GM_deleteValues
function takes one parameter:
The GM_deleteValues
function does not return any value. Instead, it deletes the specified keys from the userscript's storage.
Here is an example of how GM_deleteValues
and its async counterpart GM.deleteValues might be used in a userscript:
GM_deleteValues(['foo', 'bar']);
await GM.deleteValues(['foo', 'bar']);
The GM_addValueChangeListener
function allows a userscript to add a listener for changes to the value of a specific key in the userscript's storage.
The function takes two parameters:
function(key, oldValue, newValue, remote) {
// key is the key whose value has changed
// oldValue is the previous value of the key
// newValue is the new value of the key
// remote is a boolean indicating whether the change originated from a different userscript instance
}
The GM_addValueChangeListener
function returns a "listenerId" value that can be used to remove the listener later using the GM_removeValueChangeListener
function.
The very same applies to GM.addValueChangeListener
and GM.removeValueChangeListener
with the only difference that both return a promise;
Here is an example of how the GM_addValueChangeListener
function might be used in a userscript:
// Add a listener for changes to the "savedTab" key
var listenerId = GM_addValueChangeListener("savedTab", function(key, oldValue, newValue, remote) {
// Print a message to the console when the value of the "savedTab" key changes
console.log("The value of the '" + key + "' key has changed from '" + oldValue + "' to '" + newValue + "'");
});
GM_addValueChangeListener
can be used by userscripts to communicate with other userscript instances at other tabs.
GM_removeValueChangeListener
and GM.removeValueChangeListener
both get one argument called "listenerId" and remove the change listener with this ID.
The GM_xmlhttpRequest
allows a userscripts to send an HTTP request and handle the response.
The function takes a single parameter: an object containing the details of the request to be sent and the callback functions to be called when the response is received.
The object can have the following properties:
user-agent
, referer
, ...
(some special headers are not supported by Safari and Android browsers)follow
, error
or manual
; controls what to happen when a redirect is detected (build 6180+, enforces fetch
mode)arraybuffer
, blob
, json
or stream
fetch
mode)fetch
instead of a XMLHttpRequest
request
(at Chrome this causes details.timeout
and xhr.onprogress
to not work and makes xhr.onreadystatechange
receive only readyState
DONE
(==4) events)stream
readyState
changed function(response) {
// response is an object containing the details of the response
}
response has the following attributes:readyState
details.responseType
was setGM_xmlhttpRequest
returns an object with the following property:
GM.xmlHttpRequest
returns a promise that resolves to the response and also has an abort
function.
Here is an example of how the GM_xmlhttpRequest
function might be used in a userscript:
GM_xmlhttpRequest({
method: "GET",
url: "https://example.com/",
headers: {
"Content-Type": "application/json"
},
onload: function(response) {
console.log(response.responseText);
}
});
const r = await GM.xmlHttpRequest({ url: "https://example.com/" }).catch(e => console.error(e));
console.log(r.responseText);
Note: the synchronous
flag at details
is not supported
Important::
@connect
GM.xmlHttpRequest
(with a uppercase "h" in "http")Note: this API is experimental and might change at any time. It is also not available anymore at Tampermonkey 5.2 and above.
GM_webRequest
(re-)registers rules for web request manipulations and the listener of triggered rules.
If you need to just register rules it's better to use @webRequest
header.
Note, webRequest proceeds only requests with types sub_frame
, script
, xhr
and websocket
.
{ include: [selector] }
, object properties:"cancel"
is shortening for { cancel: true }
, object properties:"([^:]+)://match.me/(.*)"
;"$1://redirected.to/$2"
;"cancel"
, "redirect"
;"ok"
or "error"
;GM_webRequest([
{ selector: '*cancel.me/*', action: 'cancel' },
{ selector: { include: '*', exclude: 'http://exclude.me/*' }, action: { redirect: 'http://new_static.url' } },
{ selector: { match: '*://match.me/*' }, action: { redirect: { from: '([^:]+)://match.me/(.*)', to: '$1://redirected.to/$2' } } }
], function(info, message, details) {
console.log(info, message, details);
});
Note: httpOnly
cookies are supported at the BETA versions of Tampermonkey only for now
Tampermonkey checks if the script has @include
or @match
access to given details.url
arguments!
The cookie objects have the following properties:
// Retrieve all cookies with name "mycookie"
GM_cookie.list({ name: "mycookie" }, function(cookies, error) {
if (!error) {
console.log(cookies);
} else {
console.error(error);
}
});
// Retrieve all cookies for the current domain
const cookies = await GM.cookie.list()
console.log(cookies);
Sets a cookie with the given details. Supported properties are defined here.
undefined
.GM_cookie.set({
url: 'https://example.com',
name: 'name',
value: 'value',
domain: '.example.com',
path: '/',
secure: true,
httpOnly: true,
expirationDate: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30) // Expires in 30 days
}, function(error) {
if (error) {
console.error(error);
} else {
console.log('Cookie set successfully.');
}
});
GM.cookie.set({
name: 'name',
value: 'value'
})
.then(() => {
console.log('Cookie set successfully.');
})
.catch((error) => {
console.error(error);
});
Deletes a cookie.
The details
object must contain at least one of the following properties:
url
is not specified, the current document's URL will be used.The callback
function is optional and will be called when the cookie has been deleted or an error has occurred. It takes one argument:
undefined
if the cookie was deleted successfully.GM_cookie.delete({ name: 'cookie_name' }, function(error) {
if (error) {
console.error(error);
} else {
console.log('Cookie deleted successfully');
}
});
If a script runs on a single-page application, then it can use window.onurlchange
to listen for URL changes:
// ==UserScript==
...
// @grant window.onurlchange
// ==/UserScript==
if (window.onurlchange === null) {
// feature is supported
window.addEventListener('urlchange', (info) => ...);
}
Usually JavaScript is not allowed to close tabs via window.close
.
Userscripts, however, can do this if the permission is requested via @grant
.
Note: for security reasons it is not allowed to close the last tab of a window.
// ==UserScript==
...
// @grant window.close
// ==/UserScript==
if (condition) {
window.close();
}
window.focus
brings the window to the front, while unsafeWindow.focus
may fail due to user settings.
// ==UserScript==
...
// @grant window.focus
// ==/UserScript==
if (condition) {
window.focus();
}
CDATA-based way of storing meta data is supported via compatibility option. Tampermonkey tries to automatically detect whether a script needs this option to be enabled.
var inline_src = (<><![CDATA[
console.log('Hello World!');
]]></>).toString();
eval(inline_src);