📢 Try installing a desktop browser extension and synchronize bookmarks with your XBrowser.

Tampermonkey Script API Reference

Series Navigation

TL;DR (Quick Start)

  • Learn Metadata First: Determines which websites/when scripts execute (@match/@run-at).
  • Then Learn APIs: GM APIs are used for storage, notifications, cross-domain requests, downloads, etc.
  • Practice with Example Scripts: Install Tampermonkey Script API Example Script to see effects while running.

Quick Navigation

This document organizes the usage methods of most Tampermonkey script APIs and provides code examples for each method. In addition, you can install the Tampermonkey Script API Example Script to test in browsers that support user scripts.

Tip: The API support and parameters described in the documentation are based on X Browser‘s built-in script manager. Other script managers may have slight differences.

Metadata

Metadata is usually placed at the beginning of the entire script, mainly serving to describe the script, set parameters, and make declarations, including script name, description, author, version number, execution method, dependent library file declarations, etc.

Below is an example of a script’s metadata declaration.

// ==UserScript==
// @name Say hello
// @namespace com.example.hello
// @version 0.1
// @description When you open the site example.com it says "HELLO"
// @author You
// @match www.example.com
// ==/UserScript==
Metadata Tag Description
@name The name of the script
@namespace The namespace of the script, can be a unique identifier or URL
@description Script description, describing the usage and functionality of the script
@icon Customize an icon for the script, displayed in the script list and browser extension menu. Can be a URL icon resource or Base64-encoded Data URI.
@author The author’s name or nickname
@version The current version number of the script
@match Defines the scope of the script, only executes the script on matching URLs or domains. This tag can have multiple declarations in metadata
@include Similar to @match, used to describe the scope of the script, can have multiple declarations in metadata.
@exclude Used to exclude some URLs, even if @match and @include have specified matches, can have multiple declarations in metadata.
@require Third-party libraries that the script depends on before execution, can have multiple declarations in metadata
@resource Resource files that the script depends on for execution, such as CSS, text, image resources, etc., can have multiple declarations in metadata
@run-at Specifies the execution timing of the script. Different application scenarios may require different execution timings. The values of @run-at can be found in the table below
@grant Declare which API functions to use in metadata

The values of metadata tag @run-at are as follows:

Value Description
document-start Specifies that the script executes when the DOM tree starts. Add this declaration when the script needs to execute as early as possible.
document-end Specifies that the script executes when DOM data loading is complete
document-idle Executes when page loading is complete. When metadata has no @run-at declaration, the script executes at this timing by default
main-menu X Browser extension declaration, indicating that this script does not execute automatically, users execute it manually through the main menu extension option.
context-menu X Browser extension declaration, indicating that this script does not execute automatically, users execute it through the long-press menu extension option
tool-menu X Browser extension declaration, indicating that this script does not execute automatically, users execute it through the page tools menu extension option

Tampermonkey APIs

GM_addStyle

Description

Add a CSS style to the page.

Syntax

function GM_addStyle (cssString)

Parameters

Name Type Description
cssString String String stylesheet

Example

GM_addStyle('#note{color: white; background: #3385ff!important;border-bottom: 1px solid #2d7}');

GM_addElement

Description

Add a page element. You can specify a parent node. If no parent node is specified, its node is the root element.

Syntax

function GM_addElement(tagName, attributes)

Or

function GM_addElement(parentNode,tagName, attributes)

Parameters

Name Type Description
tagName String Element name
attributes Object Attribute name/value pairs
parentNode Object Parent node of new element

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; };'
});

GM_setValue

Description

Save data to browser local storage through the specified key.

Syntax

function GM_setValue(name,value)

Parameters

Name Type Description
name String String key
value Any type Can be integer, string, boolean, object, or any data

Example

GM_setValue("foo", "bar");
GM_setValue("count", 100);
GM_setValue("active", true);
GM_setValue("data", {
name: 'Andy',
age: 18
});

GM_getValue

Description

Get a value from browser local storage.

Syntax

function GM_getValue(name, defaultValue)

Parameters

Name Type Description
name String String key
defaultValue Any type Optional, returns default value if key has never been set

Return Value

If the key has been set, returns the data type that was originally set.

Example

GM_setValue("foo", "bar");
GM_setValue("count", 100);
GM_setValue("active", true);
GM_setValue("data", {
name: 'Andy',
age: 18
});

var info = `foo = ${GM_getValue("foo")}
count = ${GM_getValue("count")}
active = ${GM_getValue("active")}
data.name = ${GM_getValue("data").name}`;
alert(info);

GM_listValues

Description

Returns a list of all keys set using GM_setValue.

Syntax

function GM_listValues()

Example

GM_setValue("foo", "bar");
GM_setValue("count", 100);
GM_setValue("active", true);
GM_setValue("data", {
name: 'Andy',
age: 18
});
alert(GM_listValues());

GM_deleteValue

Description

Delete a key set through the GM_setValue method.

Syntax

function GM_deleteValue(name)

Parameters

Name Type Description
name String String key

Example

GM_deleteValue("foo");
let keys =  GM_listValues();
for (let key of keys) {
GM_deleteValue(key);
}

GM_notification

Description

Display a notification message

Syntax

function GM_notification(details)

Or

function GM_notification(text, title, image, onclick )

Parameters

Name Type Description
details Object An object containing text field and ondone, onclick callback function fields
text String Text content
title String Parameter for compatibility, not currently implemented on mobile
Image Object Parameter for compatibility, not currently implemented on mobile
onclick Function Callback function when user clicks the OK button

Example

GM_notification("Hello!");

GM_notification({
text: 'This is a message with callback',
onclick: function() {
alert("you click message ok button");
},
ondone: function() {
alert("message bar closed");
}
});

GM_notification("Hello","","",function() {
alert("you click message ok button");
})

GM_setClipboard

Description

Write string data to clipboard

Syntax

function GM_setClipboard(data)

Parameters

Name Type Description
data String String content

Example

GM_setClipboard('this is test data');

GM_registerMenuCommand

Description

Register a menu option that will be displayed in X Browser’s page tools menu.

Syntax

function GM_registerMenuCommand(title,callback) 

Parameters

Name Type Description
title String Menu name
callback Function Callback function executed when menu item is clicked

Return Value

Returns the command ID of the menu item, used when unregistering the menu

Example

GM_registerMenuCommand("click me",function() {
alert("You click menu item");
});

GM_unregisterMenuCommand

Description

Unregister a previously registered menu item

Syntax

function GM_unregisterMenuCommand(commandId) 

Parameters

Name Type Description
commandId String Command ID of menu item

Example

GM_unregisterMenuCommand(commandId);

GM_openInTab

Description

Open a page in a new tab

Syntax

function GM_openInTab(url,background) 

Parameters

Name Type Description
url String URL of the new tab page
background Boolean Whether to open tab in background, default is false

Example

GM_openInTab("https://www.example.com");
GM_openInTab("https://www.example.com",true);

GM_download

Description

Invoke the browser’s default downloader to download

Syntax

function GM_download(url,name) 

Or

function GM_download(detail) 

Parameters

Name Type Description
url String URL of the resource to download
name String Name to save the downloaded file
detail Object Configure download parameters through object
detail Parameter Properties List
  • url - String type, URL of the resource to download
  • name - String type, name to save the downloaded file
  • headers - Object type, HTTP request headers
  • onload - Callback function, download completed
  • onerror - Callback function, download error
  • tag - String, tag the download file. X Browser’s implementation saves resources with the same tag in a directory named after the tag.

Example

GM_download("https://www.xbext.com/download/xbrowser-release.apk") 
// Specify download save file name
GM_download("https://www.xbext.com/download/xbrowser-release.apk","xbrowser.apk");
let urls = ["https://www.dundeecity.gov.uk/sites/default/files/publications/civic_renewal_forms.zip",
"https://www.dundeecity.gov.uk/sites/default/files/publications/civic_renewal_forms.zip",
"https://www.dundeecity.gov.uk/sites/default/files/publications/civic_renewal_forms.zip",
];
var i = 0;
for (let url of urls) {
GM_download({
url: `${url}`,
name: `test-file${++i}.zip`,
headers:{
Referer:"https://www.example.com/"
},
onload: function() {
console.log("download completed !");
},
tag: "test-file" /* This property is an X Browser extension, creates a subdirectory named after the tag in the download directory to save files uniformly */
});
}

GM_getResourceText

Description

Get the text content of the resource pointed to by the metadata tag @resource.

Syntax

function GM_getResourceText(name)

Parameters

Name Type Description
name String Key name defined by @resource tag for referencing resources

Example

// @resource     main-content https://www.example.com/res/main-content.txt
var text = GM_getResourceText("main-content");

Return Value

Returns the text content of the resource URL.

GM_getResourceURL

Description

Get the content of the resource pointed to by the metadata tag @resource. The content is Base64 encoded in Data URI format.

Syntax

function GM_getResourceURL(name)

Parameters

Name Type Description
name String Key name defined by @resource tag for referencing resources

Example

var img = document.querySelector("#avatar")
//@resource avatar01 https://api.multiavatar.com/avatar01.svg
img.src = GM_getResourceURL("avatar01");

Return Value

Returns a Base64-encoded Data URI.

GM_xmlhttpRequest

Description

This method is similar to the XMLHttpRequest object, except that this method supports cross-domain requests, breaking through the same-origin access policy and making it more flexible to use.

Syntax

function GM_xmlhttpRequest(details)

Parameters

This method only has an object type parameter details. The property list and meaning of the object are as follows:

Name Type Description
details Object Contains a series of properties as control parameters
details Property Description
  • method - HTTP request method, GET, POST, HEAD, etc.
  • url - String, target request URL.
  • headers - Optional, string, HTTP protocol headers, User-Agent, Referer, etc.
  • data - Optional, string, data sent via POST method
  • responseType - Optional, string, set response type, can be one of arraybuffer, blob, json, and stream.
  • onabort - Optional, callback function, called when HTTP request is aborted.
  • onerror - Optional, callback function, called when HTTP request has an exception
  • onloadstart - Optional, callback function, called when HTTP request starts
  • onreadystatechange - Optional, callback function, called when HTTP request state changes
  • onload - Optional, callback function, called when HTTP request completes. The callback function parameter carries the following properties:
    • finalUrl - The final URL address of the HTTP request, such as the final redirected URL.
    • readyState - Data state
    • status - HTTP request status
    • statusText - HTTP request status text
    • responseHeaders - HTTP response headers
    • response - Object type data returned by HTTP response. When details.responseType is set, returns the corresponding type of object.
    • responseText - Returns text type data

Example

// Initiate a GET request
GM_xmlhttpRequest({
method: "GET",
url: "http://www.example.com/",
onload: function(response) {
alert(response.responseText);
}
});
// Initiate a POST request
GM_xmlhttpRequest({
method: "POST",
url: "https://www.example.net/login",
data: "username=johndoe&password=xyz123",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
if (response.responseText.indexOf("Logged in as") > -1) {
location.href = "http://www.example.net/dashboard";
}
}
});

urlchange

This is an extended event function, commonly used in single-page applications to listen for browser URL changes.

Example

 window.addEventListener('urlchange', () => {
alert("urlchange");
});
// When the page jumps to a new anchor, it triggers the urlchange event
window.location = "#test"

GM_cookie

Description

This method can break through the browser’s cross-domain restrictions on Cookies, and operate on Cookies under a certain website, including getting, setting, and deleting Cookies. This method has security risks and may lead to user privacy information leakage. Currently, it mainly supports this method for compatibility with some scripts, and may restrict the use of this method in the future.

Syntax

function GM_cookie(action,details,callback)

Parameters

Name Type Description
action String Cookie operation method [list, set, delete]
details Object Contains a series of properties as parameters
callback Function Returns the result of Cookie operation
action Options
  • list - Get the list of Cookies under a certain domain
  • set - Set a Cookie under a certain domain
  • delete - Delete a Cookie under a certain domain
details Property Description
  • url - Page URL
  • domain - Cookie domain.
  • name - String, Cookie key
  • value - String, Cookie content.

Example

Get the list of Cookies under a certain domain

GM_cookie('list', {
url: "https://www.example.com",
}, function (result) {
console.log(result);
});

Delete a Cookie under a certain domain

GM_cookie('delete', {
url: "https://www.example.com",
name: "test"

}, function (result) {
console.log(result);
});

Set a Cookie under a certain domain

GM_cookie('set', {
url: "https://www.example.com",
name: "test",
value: "test",
}, function (result) {
console.log(result);
});

For compatibility with some other scripts, the GM_cookie function also supports the following calling methods

// Get cookies under a certain domain
GM_cookie.list({
url: "https://www.example.com",
}, function (result) {
console.log(result);
});

// Set a Cookie under a certain domain
GM_cookie.set({
url: "https://www.example.com",
name: "test",
value: "test",
}, function (result) {
console.log(result);
});

// Delete a Cookie under a certain domain
GM_cookie.delete({
url: "https://www.example.com",
name: "test"

}, function (result) {
console.log(result);
});

GM_info

This is an object used to save relevant environment variables for each script, such as the script’s version, author, description, etc. The object property list is as follows:

  • script - Object type, contains the following properties.

    • author - Script author
    • name - Script name
    • description - Script description
    • version - Version
    • copyright - Copyright information
    • includes - Array type, list of matching pages
    • matches - Array type, similar to includes, list of matching pages
    • excludes - Array type, list of excluded matching URLs
    • resources - Array type, list of all resources
  • version - Version of the script manager

  • scriptHandler - Name of the script manager

  • scriptMetaStr - Script manager metadata string

Example

var info = "Script Name: "  + GM_info.script.name + 
"\nVersion: " + GM_info.script.version +
"\nVersion: " + GM_info.script.version +
"\nScriptHandler: " + GM_info.scriptHandler +
"\nScript Handler Version : " + GM_info.version ;

alert(info);

References