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
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
functionGM_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
functionGM_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
functionGM_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
// 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
functionGM_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
functionGM_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
functionGM_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
functionGM_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); });
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