Violentmonkey APIs are derived from those in Greasemonkey v3, and most of them work the same way, GM.*
Greasemonkey v4-compatible aliases were added in VM2.12.0.
GM_*
GM_*
are a group of special APIs provided by Violentmonkey.
GM_info
An object that exposes information about the current userscript. It has following properties:
-
uuid: string
A unique ID of the script.
-
scriptMetaStr: string
The meta block of the script.
-
scriptWillUpdate: boolean
Whether the script will be updated automatically.
-
scriptHandler: string
The name of userscript manager, which should be the string
Violentmonkey
. -
version: string
Version of Violentmonkey.
-
platform: object- since VM2.12.4
Unlike
navigator.userAgent
, which can be overriden by other extensions/userscripts or by devtools in device-emulation mode,GM_info.platform
is more reliable as the data is obtained in the background page of Violentmonkey using a specialized extension API (browser.runtime.getPlatformInfo and getBrowserInfo).-
arch: string
One of "arm", "mips", "mips64", "x86-32", "x86-64".
-
browserName: string
"chrome", "firefox" or whatever was returned by the API.
- browserVersion: string
-
os: string
One of "android", "cros", "linux", "mac", "openbsd", "win".
-
arch: string
-
script: object
Contains structured fields from the Metadata Block:
- description: string
- excludes: string[]
- includes: string[]
- matches: string[]
- name: string
- namespace: string
- resources: Array<{name, url}>
- runAt: string
- version: string
-
injectInto: string- since VM2.10.0
The injection mode of current script. See
@inject-mode
for more information.
GM_getValue
Retrieves a value for current script from storage.
let value = GM_getValue(key, defaultValue)
-
key: string
The name for
value
to load. -
defaultValue: any
The default value to return if no value exists in the storage.
GM_setValue
Sets a key / value pair for current script to storage.
GM_setValue(key, value)
-
key: string
The unique name for
value
within this script. -
value: any
The value to be stored, which must be JSON serializable (string, number, boolean, null, or an array/object consisting of these types) so for example you can't store DOM elements or objects with cyclic dependencies.
GM_deleteValue
Deletes an existing key / value pair for current script from storage.
GM_deleteValue(key)
-
key: string
The unique name for
value
within this script.
GM_listValues
Returns an array of keys of all available values within this script.
let arrayOfKeys = GM_listValues()
GM_addValueChangeListener
Adds a change listener to the storage and returns the listener ID.
let listenerId = GM_addValueChangeListener(name, callback)
-
name: string
The name of the observed variable
-
callback: (name, oldValue, newValue, remote) => void
-
name: string
The name of the observed variable
-
oldValue: any
The old value of the observed variable (
undefined
if it was created) -
newValue: any
The new value of the observed variable (
undefined
if it was deleted) -
remote: boolean
true
if modified by the userscript instance of another tab orfalse
for this script instance. Can be used by scripts of different browser tabs to communicate with each other.
-
name: string
GM_removeValueChangeListener
Removes a change listener by its ID.
GM_removeValueChangeListener(listenerId)
- listenerId: string
GM_getResourceText
Retrieves a text resource from the metadata block.
let text = GM_getResourceText(name)
-
name: string
Name of a resource defined in the metadata block.
GM_getResourceURL
Retrieves a blob:
or data:
URL of a resource from the metadata block.
let blobUrl = GM_getResourceURL(name);
let blobOrDataUrl = GM_getResourceURL(name, isBlobUrl);
-
name: string
Name of a resource defined in the metadata block.
-
isBlobUrl: boolean = true- since VM2.13.1
-
true
returns ablob:
URL. It's short and cacheable, so it's good for reusing in multiple DOM elements. -
false
returns adata:
URL. It's long so reusing it in DOM may be less performant due to the lack of caching, but it's particularly handy for direct synchronous decoding of the data on sites that forbid fetchingblob:
in their CSP.
-
Note: when setting this URL as src
or href
of a DOM element, it may fail on some sites with a particularly strict CSP that forbids blob:
or data:
URLs. Such sites are rare though. The workaround in Chrome is to use GM_addElement
, whereas in Firefox you'll have to disable CSP either globally via about:config
or by using an additional extension that modifies HTTP headers selectively.
GM_addElement
Since VM2.13.1
Appends and returns an element with the specified attributes.
let element1 = GM_addElement(tagName, attributes);
let element2 = GM_addElement(parentNode, tagName, attributes);
-
parentNode?: Node | Element | ShadowRoot
The parent node to which the new node will be appended.
It can be inside ShadowDOM:
someElement.shadowRoot
.When omitted, it'll be determined automatically:
document.head
(<head>
) forscript
,link
,style
,meta
tags.document.body
(<body>
) for other tags or when there's no<head>
.document.documentElement
(<html>
or an XML root node) otherwise.
-
tagName: string
A tag name like
'script'
. Any valid HTML tag can be used, but the only motivation for this API was to addscript
,link
,style
elements when they are disallowed by a strictContent-Security-Policy
of the site e.g. github.com, twitter.com. -
attributes?: object
The keys are HTML attributes, not DOM properties, except
textContent
which sets DOM propertytextContent
. The values are strings so if you want to assign a private function toonload
you can do it after the element is created.
Examples:
// using a private function in `onload`
let el = GM_addElement('script', { src: 'https://....' });
el.onload = () => console.log('loaded', el);
// same as GM_addStyle('a { color:red }')
let el = GM_addElement('style', { textContent: 'a { color:red }' });
// appending to an arbitrary node
let el = GM_addElement(parentElement.shadowRoot, 'iframe', { src: url });
Notes:
- The element is returned immediately (synchronously) even with
GM.addElement
, no need for.then()
, but you can use it if you want, just once though as it's auto-removed to avoid recursion. The API is synchronous because Violentmonkey runs scripts only when the root element appears, so there's always a node to serve as a parent. - Invalid arguments will raise an exception, which can be caught using
try {} catch (e) {}
, just like standard DOM APIdocument.createElement
. - This API is experimental in Tampermonkey, and hence subject to change.
GM_addStyle
Appends and returns a <style>
element with the specified CSS.
let styleElement = GM_addStyle(css);
-
css: string
The CSS code to inject.
Older versions of Violentmonkey (prior to 2.12.0) returned an imitation of Promise,
which is still maintained for compatibility, so don't be surprised if you see code like
GM_addStyle(css).then(el => { /* whatever */ });
GM_openInTab
Opens URL in a new tab.
-
using an object
let tabControl = GM_openInTab(url, options)
-
url: string
The URL to open in a new tab. URL relative to current page is also allowed. Note: Firefox does not support data URLs.
-
options?: object
-
active: boolean = true
Make the new tab active (i.e. open in foreground).
-
container?: number- since VM2.12.5, Firefox-only
Set tab's container in Firefox:
- not specified = reuse script's tab container
0
= default (main) container1
,2
, etc. = internal container index
-
insert: boolean = true- since VM2.11.0
Insert the new tab next to the current tab and set its "openerTab" so when it's closed the original tab will be focused automatically. When
false
or not specified, the usual browser behavior is to open the tab at the end of the tab list. -
pinned: boolean = false- since VM2.12.5
Pin the tab (i.e. show without a title at the beginning of the tab list).
-
active: boolean = true
-
url: string
-
Using a boolean, compatible with Greasemonkey:
let tabControl = GM_openInTab(url, openInBackground)
-
openInBackground: boolean
Open the tab in background. Note, this is a reverse of the first usage method so for example
true
is the same as{ active: false }
.
-
openInBackground: boolean
Returns an object with following properties:
-
onclose?: () => void
Сan be assigned to a function. If provided, it will be called when the opened tab is closed.
-
closed: boolean
Whether the opened tab is closed.
-
close: () => void
A function to explicitly close the opened tab.
let tabControl = GM_openInTab(url);
tabControl.onclose = () => console.log('tab is closed');
tabControl.close();
GM_registerMenuCommand
Registers a command in Violentmonkey popup menu.
GM_registerMenuCommand(caption, onClick)
// v2.12.5 and newer return an `id` equal to `caption` for compatibility with TM
const id = GM_registerMenuCommand(caption, onClick)
-
caption: string
The name to show in the popup menu.
-
onClick: () => void
When the command is clicked in the menu, this function will run with the following parameter:
- event: MouseEvent | KeyboardEvent- since VM2.13.1 is the event that activated the command so you can check
event.button
,event.shiftKey
,event.key
, and so on.
- event: MouseEvent | KeyboardEvent- since VM2.13.1 is the event that activated the command so you can check
If you want to add a shortcut, please see vm.shortcut.
GM_unregisterMenuCommand
Unregisters a command which has been registered to Violentmonkey popup menu.
GM_unregisterMenuCommand(caption)
-
caption: string
The name of command to unregister.
GM_notification
Shows an HTML5 desktop notification.
-
using an object:
let control = GM_notification(options)
-
options: object
-
text: string
Main text of the notification.
-
title?: string
Title of the notification.
-
image?: string
URL of an image to show in the notification.
-
onclick?: () => void
Callback when the notification is clicked by user.
-
ondone?: () => void
Callback when the notification is closed, either by user or by system.
-
text: string
-
options: object
-
Using separate parameters, compatible with Greasemonkey:
GM_notification(text, title, image, onclick)
-
text: string
Main text of the notification.
-
title?: string
Title of the notification.
-
image?: string
URL of an image to show in the notification.
-
onclick?: () => void
Callback when the notification is clicked by user.
-
text: string
As of VM2.12.8 returns a control object with the following properties:
-
remove: () => Promise<void>
A function to remove the notification.
GM_setClipboard
Sets data to system clipboard.
GM_setClipboard(data, type)
-
data: string
The data to be copied to system clipboard.
-
type: string = 'text/plain'
The MIME type of data to copy.
GM_xmlhttpRequest
Makes a request like XMLHttpRequest, with some special capabilities, not restricted by same-origin policy.
Note: h
is lowercase (the historical spelling).
let control = GM_xmlhttpRequest(details)
-
details: object
-
url: string
URL relative to current page is also allowed.
-
method?: string
Usually
GET
. -
user?: string
User for authentication.
-
password?: string
Password for authentication.
-
overrideMimeType?: string
A MIME type to specify with the request.
-
headers?: object
For example
{ 'name1': 'value1', 'name2': 'value2' }
.Some special headers are also allowed:
'Cookie'
'Host'
'Origin'
'Referer'
'User-Agent'
-
responseType?: string
One of the following:
'text'
👈 default'json'
'blob'
'arraybuffer'
'document'
(since VM2.12.0)
-
timeout?: number- since VM2.9.5
Time to wait for the request, none by default.
-
data?: string | ArrayBuffer | Blob | DataView | FormData | ReadableStream | TypedArray | URLSearchParams
Data to send with the request, usually for
POST
andPUT
requests. -
binary?: boolean- since VM2.12.2
Send the
data
string as ablob
. This is for compatibility with Tampermonkey/Greasemonkey, where onlystring
type is allowed indata
. -
context?: any
Can be an object and will be assigned to
context
of the response object. -
anonymous?: boolean = false- since VM2.10.1
When set to
true
, no cookie will be sent with the request and since VM2.12.5 the response cookies will be ignored.When absent, an inverted value of Greasemonkey4-compatible
withCredentials
is used. Note that Violentmonkey sends cookies by default, like Tampermonkey, but unlike Greasemonkey4 (same-originurl
only).
Event handlers:
- onabort?: () => void
- onerror?: () => void
- onload?: () => void
- onloadend?: () => void
- onloadstart?: () => void- since VM2.12.5
- onprogress?: () => void
- onreadystatechange?: () => void
- ontimeout?: () => void
Each event handler is a function that accepts one argument
responseObject
-
url: string
Note:
synchronous
is not supported.
Returns a control object with the following properties:
-
abort: () => void
A function to abort the request.
The response object is passed to each event handler with the following properties, most of which are identical to those provided by the standard XMLHttpRequest:
- status: number
- statusText: string
- readyState: number
- responseHeaders: string
- response: string | Blob | ArrayBuffer | Document | object | null
- responseText: string | undefined, only provided when available
- responseXML: Document | null- since VM2.13.4, only provided when available
- lengthComputable: boolean, only provided when available
- loaded: number, only provided when available
- total: number, only provided when available
- finalUrl: string, the final URL after redirection
- context: any, the same
context
object you specified indetails
GM_download
Since VM2.9.5
Downloads a URL to a local file.
-
using an object:
GM_download(options)
-
options: object:
-
url: string
The URL to download.
-
name: string
The filename to save to. Folders/subpaths aren't supported yet.
Most GM_xmlhttpRequest options are supported.
- headers?: object
- timeout?: number- since VM2.9.5
- context?: any- since VM2.13.4
- user?: string- since VM2.13.4
- password?: string- since VM2.13.4
- anonymous?: boolean = false- since VM2.13.4
- onabort?: () => void- since VM2.13.4
- onerror?: () => void
- onload?: () => void
- onloadend?: () => void- since VM2.13.4
- onloadstart?: () => void- since VM2.13.4
- onprogress?: () => void
- onreadystatechange?: () => void- since VM2.13.4
- ontimeout?: () => void
The
onload
event handler is called after the data is downloaded from URL, before writing the file. -
url: string
-
-
using separate parameters:
GM_download(url, name)
-
url: string
The URL to download.
-
name: string
The filename to save to. Folders/subpaths aren't supported yet.
-
url: string
Returns a control object with the following properties, same as GM_xmlhttpRequest:
-
abort: () => void
A function to abort the request.
GM.*
GM
(since VM2.12.0) is a single variable with Greasemonkey4-compatible aliases:
- GM.addStyle
- GM.addElement - since VM2.13.1
- GM.registerMenuCommand - since VM2.12.10, GM4.11
- GM.deleteValue (async)
- GM.getResourceUrl (async) - in VM2.12.0...2.13.0 it was misspelled as
GM.getResourceURL
- GM.getValue (async)
- GM.info
- GM.listValues (async)
- GM.notification
- GM.openInTab
- GM.setClipboard
- GM.setValue (async)
- GM.xmlHttpRequest - note
H
is uppercase
The async
functions return a Promise
that's resolved with the returned value.