This article organizes most of the Tampermonkey user script API usage and includes code examples for each method. In addition you can install Tampermonkey user script API example to test them in a browser that supports Tampermonkey user scripts.
Tip: The API support and parameters described in the documentation are based on the built-in script manager of XBrowser, other script managers may have slight differences.
Meta data
Metadata is usually placed at the beginning of a script, and its main function is to declare, set, and describe the script, including the script name, introduction, author, version number, third-party library dependencies, and which APIs are used, etc.
The following 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==
The following are the metadata definition specifications supported by the Browser
Tag
Description
@name
Name of the script
@namespace
The namespace of the script, either as a unique identifier or as a URL
@description
Introduction to the script describing the usage and functions of the script, etc.
@icon
Customize an icon for the script to be displayed in the script manager as well as in the browser extension menu. This can be a url icon resource or a Base64 encoded Data URI.
@author
Name or nickname of the author of the script
@version
Current script version number
@match
Define the scope of the script to execute the script only at the matching URL or domain, this tag can have multiple lines declared in the metadata
@include
Similar to @match, it is used to describe the scope of a script and can have multiple lines of declaration in the metadata.
@exclude
Used to exclude some URLs, even if @match and @include have specified a match, there can be a multi-line declaration in the metadata.
@require
Specify third-party libraries that the script needs to depend on before it can be executed, and there can be a multi-line declaration in the metadata
@resource
The script execution needs to depend on some resource files, such as css, text, image resources, etc., which can be declared on multiple lines in the metadata
@run-at
Specify the timing of script execution, different scenarios may require different execution timing, where the value of @run-at can be found in the following table
@grant
Declare which API functions are used , there can be multiple lines in the metadata.
The metadata tag @run-at has the following attribute values.
Value
Description
document-start
Specify that the script is executed at the beginning of the DOM tree, add this statement if you need the script to be executed early.
document-end
Specify that the script is executed when the DOM data is loaded
document-idle
Execute when the page is loaded. When the metadata does not have a @run-at declaration, the script is executed at this time by default.
main-menu
Extension tag declaration for XBrowser, means that the script is not executed automatically but through the extended main menu option
context-menu
Extension tag declaration for XBrowser, means that the script is not executed automatically but through the extended long press menu option
tool-menu
Extension tag declaration for XBrowser, means that the script is not executed automatically but through the extended tools menu option
An object containing a text field and ondone, onclick callback function fields
text
String
Text Content
title
String
Parameters are not currently implemented on the mobile side for compatibility
Image
Object
Parameters are not currently implemented on the mobile side for compatibility
onclick
Callback function
Callback function when the user has clicked 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 the clipboard
Syntax
function GM_setClipboard(data)
Parameters
Name
Type
Description
data
String
Text content
Example
GM_setClipboard('this is test data');
GM_registerMenuCommand
Description
Register a menu option, which will be displayed in the XBrowser’s Page Tools menu.
Syntax
functionGM_registerMenuCommand(title,callback)
Parameters
Name
Type
Description
title
String
Menu item name
callback
Callback function
Callback functions executed by clicking on menu items
Return Value
Returns the command ID of the menu item, which is used when un register of the menu
Example
GM_registerMenuCommand("click me",function() { alert("You click menu item"); });
GM_unregisterMenuCommand
Description
Unregister previously registered menu items
Syntax
functionGM_unregisterMenuCommand(commandId)
Parameters
Name
Type
Description
commandId
String
Command id of the 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
background
Boolean
Whether to open the tab in the background, default is false
//Specify the name of the download file GM_download("https://www.xbext.com/download/xbrowser-release.apk,"xbrowser.apk");
//Batch downloads, the files are saved in a subdirectory named "test-file" in the download directory. 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`, confirm: false, tag: "test-file" }); }
GM_getResourceText
Description
Get the content of the URL resource defined by the metadata tag @resource
Syntax
functionGM_getResourceText(name)
Parameters
Name
Type
Description
name
String
The name of the key defined by the @resource tag to refer to the resource
Example
// @resource main-content https://www.example.com/res/main-content.txt var text = GM_getResourceText("main-content");
Retun value
Returns the text content of the resource URL.
GM_getResourceURL
Description
Gets the content of the resource the metadata tag @resource referring , which is encoded in Base64 and formatted as a Data URI.
Syntax
functionGM_getResourceURL(name)
Parameters
Name
Type
Description
name
String
The name of the key defined by the @resource tag to refer to the resource
Example
var img = document.querySelector("#avatar") //@resource avatar01 https://api.multiavatar.com/avatar01.svg img.src = GM_getResourceURL("avatar01");
Return value
Returns the Data URI encoded in Base64.
GM_xmlhttpRequest
Description
This method is similar to the XMLHttpRequest object, the difference is that this method supports cross-domain requests, breaking the Same-origin policy, more flexible to use.
Syntax
functionGM_xmlhttpRequest(details)
Parameters
This method has only one parameter of object type ,The list of properties of the object and their meanings are as follows.
Name
Type
Description
details
Object
Contains a series of properties as control parameters
details properties
method - Http request method, GET, POST, HEAD, etc.,GET、POST、HEAD etc.
url - String,Target request URL.
headers - Optional, String, HTTP protocol header, User-Agent, Referer, etc.
data - Optional, string, data sent via POST method
responseType - Optional, string, the response type, which can be one of arraybuffer, blob, json and stream.
onabort- Optionally, a callback function when the HTTP request is abort.
onerror- Optional, callback function that is called when an exception occurs on an HTTP request
onloadstart - Optional, callback function where the HTTP request starts to be called
onreadystatechange - Optional, callback function that is called when the status of an HTTP request changes
onload - Optional, callback function that is called when the HTTP request is completed, the callback function parameter carries several properties as follows
finalUrl - The URL address of the final HTTP request, such as the URL after a redirect.
readyState - Integer type, request status
status - HTTP Response Status
statusText - The text corresponding to the HTTP response status
responseHeaders - HTTP response headers
response - The response object returned by the HTTP response,object type data, depending on the setting of the responseType field.
responseText - The text content returned by the HTTP response
示例
//Start a HTTP get request GM_xmlhttpRequest({ method: "GET", url: "http://www.example.com/", onload: function(response) { alert(response.responseText); } });
//Start a HTTP 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"; } } });
GM_info
This is an object that holds the environment variables associated with each script, such as the script’s version, author, introduction, etc. The list of object properties is as follows.
script - Object type, contains some of the following properties.
author - Author of this script
name - Name of this script
description - Script Description
version - Version
copyright - Copyright Information
includes - Array type, list of matching pages
matches - Array type, similar to includes, matching the list of pages