Close

Privileged APIs

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.

unsafeWindow

It’s the original window object of the webpage that allows reading or modifying global variables, necessary when the script is sandboxed, because its window becomes a wrapper that confines modifications like window.foo = 123 to this script’s scope.

Sandboxing is enabled by default and disabled only if @grant none is specified, just like in Tampermonkey. Note that in older versions of Violentmonkey (before v2.32) sandboxing was also disabled when there were no @grant keys.

GM_*

GM_* are a group of special APIs provided by Violentmonkey.

GM_info

const GM_info: {
    uuid: string;
    injectInto: VMScriptInjectInto;
    script: VMScriptGMInfoScriptMeta;
    scriptMetaStr: string;
    scriptWillUpdate: boolean;
    scriptHandler: string;
    version: string;
    downloadMode: "native" | "browser";
    isIncognito: boolean;
    platform: VMScriptGMInfoPlatform;
    userAgent: string;
    userAgentData?: {
        brands: {
            brand: string;
            version: string;
        }[];
        mobile: boolean;
        platform: string;
        getHighEntropyValues(hints: string[]): Promise<UADataValues>;
    } | undefined;
}
GM_info
: {
uuid: string

A unique ID of the script.

uuid
: string;
injectInto: VMScriptInjectInto

The injection mode of current script. See @inject-into for more information.

injectInto
: type VMScriptInjectInto = "auto" | "page" | "content"

Injection mode of a script.

VMScriptInjectInto
;
script: VMScriptGMInfoScriptMeta

Contains structured fields from the Metadata Block.

script
:
interface VMScriptGMInfoScriptMeta {
    antifeature?: string[] | undefined;
    author?: string | undefined;
    compatible?: string[] | undefined;
    connect?: string[] | undefined;
    description: string;
    downloadURL?: string | undefined;
    excludeMatches: string[];
    excludes: string[];
    grant: string[];
    homepage?: string | undefined;
    homepageURL?: string | undefined;
    icon?: string | undefined;
    includes: string[];
    matches: string[];
    options: {
        check_for_updates: boolean;
        inject_into: VMScriptInjectInto | null;
        noframes: boolean | null;
        override: {
            merge_excludes: boolean;
            merge_includes: boolean;
            merge_matches: boolean;
            merge_exclude_matches: boolean;
            merge_tags: boolean;
            use_excludes: string[];
            use_includes: string[];
            use_matches: string[];
            use_exclude_matches: string[];
        };
        run_at: VMScriptRunAt | null;
        tags: string[];
        user_modified: number;
    };
    name: string;
    namespace: string;
    noframes?: boolean | undefined;
    require: string[];
    resources: {
        name: string;
        url: string;
    }[];
    runAt: VMScriptRunAt | '';
    supportURL?: string | undefined;
    tags?: string[];
    unwrap?: boolean | undefined;
    updateURL?: string | undefined;
    version: string;
}

GM_info.script and GM.info.script Non-optional string property will be an empty string '' if omitted.

VMScriptGMInfoScriptMeta
;
scriptMetaStr: string

The meta block of the script.

scriptMetaStr
: string;
scriptWillUpdate: boolean

Whether the script will be updated automatically.

scriptWillUpdate
: boolean;
scriptHandler: string

The name of userscript manager, which should be the string Violentmonkey.

scriptHandler
: string;
version: string

Version of Violentmonkey.

version
: string;
downloadMode: "native" | "browser"

GM_download internal implementation: native - the classic a element's download attribute, used by default. browser - the browser API used if the user enabled it in the extension's options.

@sinceVM2.45.2
downloadMode
: 'native' | 'browser'; // VM2.45.2
isIncognito: boolean

True when this is an incognito profile (Chrome) or private mode (Firefox).

@sinceVM2.15.4
isIncognito
: boolean; // VM2.15.4
platform: VMScriptGMInfoPlatform

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).

platform
:
interface VMScriptGMInfoPlatform {
    arch: 'aarch64' | 'arm' | 'arm64' | 'mips' | 'mips64' | 'ppc64' | 's390x' | 'sparc64' | 'x86-32' | 'x86-64';
    browserName: 'chrome' | 'firefox' | string;
    browserVersion: string;
    fullVersionList?: {
        brand: string;
        version: string;
    }[] | undefined;
    mobile?: boolean | undefined;
    os: 'mac' | 'win' | 'android' | 'cros' | 'linux' | 'openbsd' | 'fuchsia';
}
VMScriptGMInfoPlatform
;
userAgent: string

A safe copy of navigator.userAgent from the content script of the extension, so it cannot be overridden by other extensions/userscripts, but unlike GM_info.platform it can be customized in devtools “device emulation” or “network conditions” for this tab.

@sinceVM2.20.2
userAgent
: string; // VM2.20.2
userAgentData?: {
    brands: {
        brand: string;
        version: string;
    }[];
    mobile: boolean;
    platform: string;
    getHighEntropyValues(hints: string[]): Promise<UADataValues>;
} | undefined

A safe copy of navigator.userAgentData from the content script of the extension, so it cannot be overridden by other extensions/userscripts, but unlike GM_info.platform it can be customized in devtools "device emulation" or "network conditions" for this tab.

Only present if the browser actually implements it (currently Chromium-based 90+), because there's no reliable/official polyfill.

Violentmonkey implements the official API, including getHighEntropyValues function to obtain the extra info asynchronously.

@sinceVM2.20.2
userAgentData
?: // VM2.20.2
| { brands: { brand: string; version: string }[]; mobile: boolean; platform: string; getHighEntropyValues(hints: string[]): Promise<UADataValues>; } | undefined; };

View source on GitHub

const GM_cookie: {
    delete: (opts: chrome.cookies.CookieDetails, callback?: (error?: string) => any) => void;
    list: (opts: Parameters<typeof chrome.cookies.getAll>[0], callback?: (cookies?: chrome.cookies.Cookie, error?: string) => any) => void;
    set: (opts: Parameters<typeof chrome.cookies.set>[0], callback?: (error?: string) => any) => void;
}
@sinceVM2.35.1
GM_cookie
: { // VM2.35.1
delete: ( opts: chrome.cookies.CookieDetailsopts: chrome.cookies.
interface CookieDetails {
    url: string;
    name: string;
    storeId?: string;
    partitionKey?: CookiePartitionKey;
}

Details to identify the cookie.

@sinceChrome 88
CookieDetails
,
callback?: (error?: string) => any, ) => void; list: (opts: Parameters<typeof chrome.cookies.getAll>[0], callback?: (cookies?: chrome.cookies.Cookie, error?: string) => any) => void

httpOnly cookies are listed only when the HTTP-only option is enabled for the script and globally in the extension

list
: (
opts: {
    url?: string;
    name?: string;
    domain?: string;
    path?: string;
    secure?: boolean;
    session?: boolean;
    storeId?: string;
    partitionKey?: chrome.cookies.CookiePartitionKey;
}
opts
: Parameters<typeof chrome.cookies.
function chrome.cookies.getAll(details: {
    url?: string;
    name?: string;
    domain?: string;
    path?: string;
    secure?: boolean;
    session?: boolean;
    storeId?: string;
    partitionKey?: chrome.cookies.CookiePartitionKey;
}): Promise<chrome.cookies.Cookie[]> (+1 overload)

Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first. This method only retrieves cookies for domains that the extension has host permissions to.

@chrome-returns-extrasince Chrome 88
getAll
>[0],
callback?: ( cookies: chrome.cookies.Cookie | undefinedcookies?: chrome.cookies.
interface Cookie {
    name: string;
    value: string;
    domain: string;
    hostOnly: boolean;
    path: string;
    secure: boolean;
    httpOnly: boolean;
    sameSite: SameSiteStatus;
    session: boolean;
    expirationDate?: number;
    storeId: string;
    partitionKey?: CookiePartitionKey;
}

Represents information about an HTTP cookie.

Cookie
,
error?: string, ) => any, ) => void; set: (opts: Parameters<typeof chrome.cookies.set>[0], callback?: (error?: string) => any) => void

httpOnly cookies are allowed only when the HTTP-only option is enabled for the script and globally in the extension

set
: (
opts: {
    url: string;
    name?: string;
    value?: string;
    domain?: string;
    path?: string;
    secure?: boolean;
    httpOnly?: boolean;
    sameSite?: chrome.cookies.SameSiteStatus;
    expirationDate?: number;
    storeId?: string;
    partitionKey?: chrome.cookies.CookiePartitionKey;
}
opts
: Parameters<typeof chrome.cookies.
function chrome.cookies.set(details: {
    url: string;
    name?: string;
    value?: string;
    domain?: string;
    path?: string;
    secure?: boolean;
    httpOnly?: boolean;
    sameSite?: chrome.cookies.SameSiteStatus;
    expirationDate?: number;
    storeId?: string;
    partitionKey?: chrome.cookies.CookiePartitionKey;
}): Promise<chrome.cookies.Cookie | undefined> (+1 overload)

Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.

@chrome-returns-extrasince Chrome 88
set
>[0],
callback?: (error?: string) => any, ) => void; };
const GM_cookie: {
    delete: (opts: browser.cookies._RemoveDetails, callback?: (error?: string) => any) => void;
    list: (opts: browser.cookies._GetAllDetails, callback?: (cookies?: browser.cookies.Cookie, error?: string) => any) => void;
    set: (opts: browser.cookies._SetDetails, callback?: (error?: string) => any) => void;
}
@sinceVM2.35.1
GM_cookie
: { // VM2.35.1
delete: ( opts: browser.cookies._RemoveDetailsopts: browser.cookies.
interface _RemoveDetails {
    url: string;
    name: string;
    storeId?: string | undefined;
    firstPartyDomain?: string | undefined;
    partitionKey?: PartitionKey | undefined;
}

Information to identify the cookie to remove.

_RemoveDetails
,
callback?: (error?: string) => any, ) => void; list: (opts: browser.cookies._GetAllDetails, callback?: (cookies?: browser.cookies.Cookie, error?: string) => any) => void

httpOnly cookies are listed only when the HTTP-only option is enabled for the script and globally in the extension

list
: (
opts: browser.cookies._GetAllDetailsopts: browser.cookies.
interface _GetAllDetails {
    url?: string | undefined;
    name?: string | undefined;
    domain?: string | undefined;
    path?: string | undefined;
    secure?: boolean | undefined;
    session?: boolean | undefined;
    storeId?: string | undefined;
    firstPartyDomain?: string | undefined;
    partitionKey?: PartitionKey | undefined;
}

Information to filter the cookies being retrieved.

_GetAllDetails
,
callback?: ( cookies: browser.cookies.Cookie | undefinedcookies?: browser.cookies.
interface Cookie {
    name: string;
    value: string;
    domain: string;
    hostOnly: boolean;
    path: string;
    secure: boolean;
    httpOnly: boolean;
    sameSite: SameSiteStatus;
    session: boolean;
    expirationDate?: number | undefined;
    storeId: string;
    firstPartyDomain: string;
    partitionKey?: PartitionKey | undefined;
}

Represents information about an HTTP cookie.

Cookie
,
error?: string, ) => any, ) => void; set: (opts: browser.cookies._SetDetails, callback?: (error?: string) => any) => void

httpOnly cookies are allowed only when the HTTP-only option is enabled for the script and globally in the extension

set
: (
opts: browser.cookies._SetDetailsopts: browser.cookies.
interface _SetDetails {
    url: string;
    name?: string | undefined;
    value?: string | undefined;
    domain?: string | undefined;
    path?: string | undefined;
    secure?: boolean | undefined;
    httpOnly?: boolean | undefined;
    sameSite?: SameSiteStatus | undefined;
    expirationDate?: number | undefined;
    storeId?: string | undefined;
    firstPartyDomain?: string | undefined;
    partitionKey?: PartitionKey | undefined;
}

Details about the cookie being set.

_SetDetails
,
callback?: (error?: string) => any, ) => void; };

View source on GitHub

GM_getValue

Retrieves a value for current script from storage.

function GM_getValue<T>(name: string, defaultValue?: T | undefined): T

Retrieves a value for current script from storage.

GM_getValue
<T>(
name: string

The name for value to load.

name
: string,
defaultValue: T | undefined

The default value to return if no value exists in the storage.

defaultValue
?: T | undefined,
): T;

View source on GitHub

GM_getValues

Since VM2.19.1

Retrieves multiple values for current script from storage.

GM_getValues( // VM2.19.1
  names: string[]

Names of the values to read, missing ones are left out of the result.

names
: string[],
):
type GenericObject = {
    [x: string]: unknown;
}
GenericObject
;
GM_getValues( // VM2.19.1 namesWithDefaults: GenericObject

Each key is a name to read from storage, the value is the default to be used in the result if the key was not in storage.

namesWithDefaults
:
type GenericObject = {
    [x: string]: unknown;
}
GenericObject
,
):
type GenericObject = {
    [x: string]: unknown;
}
GenericObject
;

View source on GitHub

  1. Using an array of keys.

    let values = GM_getValues(['foo', 'bar'])
    Keys in storageResult
    foo, bar{ foo: 123, bar: [1, 2, 3] }
    foo{ foo: 123 }
  2. Using an object.

    let values = GM_getValues({ foo: 1, bar: [2] })
    Keys in storageResult
    foo, bar{ foo: 123, bar: [1, 2, 3] }
    foo{ foo: 123, bar: [2] }

GM_setValue

Sets a key / value pair for current script to storage.

function GM_setValue<T>(name: string, value: T): void

Sets a key / value pair for current script to storage.

GM_setValue
<T>(
name: string

The unique name for value within this script.

name
: string,
value: T

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.

value
: T,
): void;

View source on GitHub

GM_setValues

Since VM2.19.1

Writes multiple values to current script’s storage.

GM_setValues( // VM2.19.1
  values: GenericObject

Each key:value pair in the object will be stored individually. Must be JSON serializable (see GM_setValue).

values
:
type GenericObject = {
    [x: string]: unknown;
}
GenericObject
,
): void;

View source on GitHub

GM_deleteValue

Deletes an existing key / value pair for current script from storage.

function GM_deleteValue(name: string): void

Deletes an existing key / value pair for current script from storage.

GM_deleteValue
(
name: string

The unique name for value within this script.

name
: string,
): void;

View source on GitHub

GM_deleteValues

Since VM2.19.1

Deletes values with the specified keys in current script’s storage.

GM_deleteValues( // VM2.19.1
  names: string[]

Array of keys to delete.

names
: string[],
): void;

View source on GitHub

GM_listValues

Returns an array of keys of all available values within this script.

function GM_listValues(): string[]

Returns an array of keys of all available values within this script.

GM_listValues
(): string[];

View source on GitHub

GM_addValueChangeListener

Adds a change listener to the storage and returns the listener ID.

function GM_addValueChangeListener<T>(name: string, callback: (name: string, oldValue: T, newValue: T, remote: boolean) => void): string

Adds a change listener to the storage and returns the listener ID.

GM_addValueChangeListener
<T>(
name: string

The name of the observed variable.

name
: string,
callback: (name: string, oldValue: T, newValue: T, remote: boolean) => void

Called when the value changes.

callback
: (
name: string

The name of the observed variable

name
: string,
oldValue: T

The old value of the observed variable (undefined if it was created)

oldValue
: T,
newValue: T

The new value of the observed variable (undefined if it was deleted)

newValue
: T,
remote: boolean

true if modified by the userscript instance of another tab or false for this script instance. Can be used by scripts of different browser tabs to communicate with each other.

remote
: boolean,
) => void, ): string;

View source on GitHub

GM_removeValueChangeListener

Removes a change listener by its ID.

function GM_removeValueChangeListener(listenerId: string): void

Removes a change listener by its ID.

GM_removeValueChangeListener
(
listenerId: string

The listener ID returned by GM_addValueChangeListener.

listenerId
: string,
): void;

View source on GitHub

GM_getResourceText

Retrieves a text resource from the metadata block.

function GM_getResourceText(name: string): string

Retrieves a text resource from the Metadata Block.

GM_getResourceText
(
name: string

Name of a resource defined in the Metadata Block.

name
: string,
): string;

View source on GitHub

GM_getResourceURL

Retrieves a blob: or data: URL of a resource from the metadata block.

function GM_getResourceURL(name: string, isBlobUrl?: boolean | undefined): string

Retrieves a blob: or data: URL of a resource from the Metadata Block.

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_getResourceURL
(
name: string

Name of a resource defined in the Metadata Block.

name
: string,
isBlobUrl: boolean | undefined
  • If true, returns a blob: URL. It's short and cacheable, so it's good for reusing in multiple DOM elements.
  • If false, returns a data: 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 fetching blob: in their CSP.

Default as true.

@sinceVM2.13.1
isBlobUrl
?: boolean | undefined, // VM2.13.1
): string;

View source on GitHub

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 with the primary purpose of circumventing a strict Content-Security-Policy that forbids adding inline code or style.

function GM_addElement(tagName: string, attributes?: Record<string, string> | undefined): HTMLElement (+1 overload)

Appends and returns an element with the specified attributes.

@sinceVM2.13.1
GM_addElement
( // VM2.13.1
tagName: string

A tag name like script. Any valid HTML tag can be used, but the only motivation for this API was to add script, link, style elements when they are disallowed by a strict Content-Security-Policy of the site e.g. github.com, twitter.com.

tagName
: string,
attributes: Record<string, string> | undefined

The keys are HTML attributes, not DOM properties, except textContent which sets DOM property textContent. The values are strings so if you want to assign a private function to onload you can do it after the element is created.

attributes
?: Record<string, string> | undefined,
): HTMLElement; function GM_addElement(parentNode: HTMLElement, tagName: string, attributes?: Record<string, string> | undefined): HTMLElement (+1 overload)

Appends and returns an element with the specified attributes.

@sinceVM2.13.1
GM_addElement
(
parentNode: HTMLElement

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>) for script, 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.
parentNode
: HTMLElement,
tagName: string

A tag name like script. Any valid HTML tag can be used, but the only motivation for this API was to add script, link, style elements when they are disallowed by a strict Content-Security-Policy of the site e.g. github.com, twitter.com.

tagName
: string,
attributes: Record<string, string> | undefined

The keys are HTML attributes, not DOM properties, except textContent which sets DOM property textContent. The values are strings so if you want to assign a private function to onload you can do it after the element is created.

attributes
?: Record<string, string> | undefined,
): HTMLElement;

View source on GitHub

Examples:

// using a private function in `onload`
const script = GM_addElement('script', { src: 'https://....' });
script.onload = () => console.log('loaded', script);
 
// same as GM_addStyle('a { color:red }')
const style = GM_addElement('style', { textContent: 'a { color:red }' });
 
// appending to an arbitrary node
const iframe = 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 API document.createElement.

GM_addStyle

Appends and returns a <style> element with the specified CSS.

function GM_addStyle(css: string): HTMLStyleElement

Appends and returns a <style> element with the specified CSS.

GM_addStyle
(
css: string

The CSS code to inject.

css
: string,
): HTMLStyleElement;

View source on GitHub

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.

function GM_openInTab(url: string, options?: {
    active?: boolean | undefined;
    container?: number | undefined;
    insert?: boolean | undefined;
    pinned?: boolean | undefined;
} | undefined): {
    onclose?: (() => void) | undefined;
    closed: boolean;
    close: () => void;
} (+1 overload)

Opens URL in a new tab.

GM_openInTab
(
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.

url
: string,
options: {
    active?: boolean | undefined;
    container?: number | undefined;
    insert?: boolean | undefined;
    pinned?: boolean | undefined;
} | undefined
options
?: {
active?: boolean | undefined

Make the new tab active (i.e. open in foreground). Default as true.

active
?: boolean | undefined;
container?: number | undefined

Firefox only.

  • not specified = reuse script's tab container
  • 0 = default (main) container
  • 1, 2, etc. = internal container index
@sinceVM2.12.5
container
?: number | undefined; // VM2.12.5
insert?: boolean | undefined

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. Default as true.

@sinceVM2.11.0
insert
?: boolean | undefined; // VM2.11.0
pinned?: boolean | undefined

Pin the tab (i.e. show without a title at the beginning of the tab list). Default as false.

@sinceVM2.12.5
pinned
?: boolean | undefined; // VM2.12.5
} | undefined, ): { onclose?: (() => void) | undefined

Сan be assigned to a function. If provided, it will be called when the opened tab is closed.

onclose
?: (() => void) | undefined;
closed: boolean

Whether the opened tab is closed.

closed
: boolean;
close: () => void

A function to explicitly close the opened tab.

close
: () => void;
};
function GM_openInTab(url: string, openInBackground?: boolean | undefined): {
    onclose?: (() => void) | undefined;
    closed: boolean;
    close: () => void;
} (+1 overload)

Opens URL in a new tab.

GM_openInTab
(
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.

url
: string,
openInBackground: boolean | undefined

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 | undefined,
): { onclose?: (() => void) | undefined

Сan be assigned to a function. If provided, it will be called when the opened tab is closed.

onclose
?: (() => void) | undefined;
closed: boolean

Whether the opened tab is closed.

closed
: boolean;
close: () => void

A function to explicitly close the opened tab.

close
: () => void;
};

View source on GitHub

let tabControl = GM_openInTab(url);
tabControl.onclose = () => console.log('tab is closed');
tabControl.close();

GM_registerMenuCommand

Registers a command in Violentmonkey popup menu.

function GM_registerMenuCommand(caption: string, onClick: (event: MouseEvent | KeyboardEvent) => void, options?: {
    id?: string | undefined;
    icon?: string | undefined;
    title?: string | undefined;
    autoClose?: boolean | undefined;
} | undefined): string

Registers a command in Violentmonkey popup menu. Returns the command's id since VM2.12.5, see description of the id parameter. If you want to add a shortcut, please see @violentmonkey/shortcut.

GM_registerMenuCommand
(
caption: string

The name to show in the popup menu.

caption
: string,
onClick: (event: MouseEvent | KeyboardEvent) => void

Callback function when the command is clicked in the menu. It receives the event that activated the command (since VM2.13.1) so you can check event.button, event.shiftKey, event.key, and so on.

onClick
: (event: MouseEvent | KeyboardEventevent: MouseEvent | KeyboardEvent) => void,
options: {
    id?: string | undefined;
    icon?: string | undefined;
    title?: string | undefined;
    autoClose?: boolean | undefined;
} | undefined
@sinceVM2.15.9
options
?: // VM2.15.9
| { id?: string | undefined

Default: the caption parameter. In 2.15.9-2.16.1 the default was a randomly generated string.

id
?: string | undefined;
icon?: string | undefined; // VM2.31.1 title?: string | undefined

A hint shown in the status bar when hovering the command.

title
?: string | undefined;
autoClose?: boolean | undefined

Default: true. Whether to auto-close the popup after the user invoked the command.

autoClose
?: boolean | undefined;
} | undefined, ): string;

View source on GitHub

GM_registerMenuCommand('Text', onClick)
const id2 = GM_registerMenuCommand('Text2', onClick, { title: 'Two' })
const id3 = GM_registerMenuCommand('Text3', onClick, { autoClose: false })

Returns the command’s caption since VM2.12.5 or id since VM2.15.9.

TIP

If you want to add a shortcut, please refer to keyboard shortcut.

Here’s how you can change the command in-place, thus preserving its relative position in the list of multiple commands:

const id = 'status';
const inplace = id === GM_registerMenuCommand('Enabled', onClick, { id });
if (inplace) {
  // supported: change the command in-place using the same `id`
  GM_registerMenuCommand('Disabled', onClick, { id, title: 'Status' });
} else {
  // not supported: recreate the commands
  GM_unregisterMenuCommand('Enabled');
  GM_unregisterMenuCommand('Foo');
  GM_unregisterMenuCommand('Bar');
  GM_registerMenuCommand('Disabled', onClick);
  GM_registerMenuCommand('Foo', onClick2);
  GM_registerMenuCommand('Bar', onClick3);
}

GM_unregisterMenuCommand

Unregisters a command which has been registered to Violentmonkey popup menu.

function GM_unregisterMenuCommand(caption: string): void

Unregisters a command which has been registered to Violentmonkey popup menu.

GM_unregisterMenuCommand
(
caption: string

The name of command to unregister.

caption
: string,
): void;

View source on GitHub

GM_notification

Shows a desktop notification using the browser.notifications API.

function GM_notification(options: {
    text: string;
    title?: string | undefined;
    image?: string | undefined;
    silent?: boolean | undefined;
    tag?: string | undefined;
    zombieTimeout?: number | undefined;
    zombieUrl?: string | undefined;
    onclick?: (() => void) | undefined;
    ondone?: (() => void) | undefined;
}): {
    remove: () => Promise<void>;
} (+1 overload)

Shows an HTML5 desktop notification. Since VM2.12.8 it returns a control object with a function to remove the notification.

GM_notification
(
options: {
    text: string;
    title?: string | undefined;
    image?: string | undefined;
    silent?: boolean | undefined;
    tag?: string | undefined;
    zombieTimeout?: number | undefined;
    zombieUrl?: string | undefined;
    onclick?: (() => void) | undefined;
    ondone?: (() => void) | undefined;
}
options
: {
text: string

Main text of the notification.

text
: string;
title?: string | undefined

Title of the notification.

title
?: string | undefined;
image?: string | undefined

URL of an image to show in the notification.

image
?: string | undefined;
silent?: boolean | undefined

No sounds/vibrations when showing the notification. Only for Chromium-based browsers as of Aug 2023. Default as false.

@sinceVM2.15.2, Chrome 70.
silent
?: boolean | undefined; // VM2.15.2
tag?: string | undefined

Unique name of the notification, e.g. 'abc', same as the web Notification API. Names are scoped to each userscript i.e. your tag won't clash with another script's tag. The purpose of a tagged notification is to replace an older notification with the same tag, even if it was shown in another tab (or before this tab was navigated elsewhere and your notification had zombieTimeout).

@sinceVM2.15.4
tag
?: string | undefined; // VM2.15.4
zombieTimeout?: number | undefined

Number of milliseconds to keep the notification after the userscript "dies", i.e. when its tab or frame is reloaded/closed/navigated. If not specified or invalid, the default behavior is to immediately remove the notifications.

@sinceVM2.15.4
zombieTimeout
?: number | undefined; // VM2.15.4
zombieUrl?: string | undefined

URL to open when a zombie notification is clicked, see zombieTimeout for more info.

@sinceVM2.16.1
zombieUrl
?: string | undefined; // VM2.16.1
onclick?: (() => void) | undefined

Callback when the notification is clicked by user. As of VM2.15.2 it also forces the notification to be visible until clicked in Chrome which by default hides the notification after a few seconds.

onclick
?: (() => void) | undefined;
ondone?: (() => void) | undefined

Callback when the notification is closed, either by user or by system.

ondone
?: (() => void) | undefined;
}, ): { remove: () => Promise<void>

Remove the notification immediately.

remove
: () => Promise<void>;
};
function GM_notification(text: string, title?: string | undefined, image?: string | undefined, onclick?: (() => void) | undefined): {
    remove: () => Promise<void>;
} (+1 overload)

Shows an HTML5 desktop notification. Since VM2.12.8 it returns a control object with a function to remove the notification.

GM_notification
(
text: string

Main text of the notification.

text
: string,
title: string | undefined

Title of the notification.

title
?: string | undefined,
image: string | undefined

URL of an image to show in the notification.

image
?: string | undefined,
onclick: (() => void) | undefined

Callback when the notification is clicked by user.

onclick
?: (() => void) | undefined,
): { remove: () => Promise<void>

Remove the notification immediately.

remove
: () => Promise<void>;
};

View source on GitHub

GM_setClipboard

Sets data to system clipboard.

function GM_setClipboard(data: string, type?: string | undefined): void

Sets data to system clipboard.

GM_setClipboard
(
data: string

The data to be copied to system clipboard.

data
: string,
type: string | undefined

The MIME type of data to copy. Default as text/plain.

type
?: string | undefined,
): void;

View source on GitHub

GM_xmlhttpRequest

Makes a request like XMLHttpRequest, with some special capabilities, not restricted by same-origin policy.

Note: h is lowercase (the historical spelling).

function GM_xmlhttpRequest<T = string | object | Blob | ArrayBuffer | Document>(details: {
    onabort?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onerror?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onload?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onloadend?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onloadstart?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onprogress?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onreadystatechange?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    ontimeout?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    url: string;
    user?: string | undefined;
    password?: string | undefined;
    headers?: Record<string, string> | undefined;
    timeout?: number | undefined;
    context?: unknown | undefined;
    anonymous?: boolean | undefined;
    method?: string | undefined;
    overrideMimeType?: string | undefined;
    responseType?: VMScriptResponseType | undefined;
    data?: string | ArrayBuffer | Blob | DataView | FormData | ReadableStream | TypedArray | URLSearchParams | undefined;
    binary?: boolean | undefined;
    upload?: GMRequestBaseEvents<T>;
}): {
    abort: () => void;
}

Makes a request like XMLHttpRequest, with some special capabilities, not restricted by same-origin policy.

GM_xmlhttpRequest
<
T = string | Blob | ArrayBuffer | Document | object, >(
details: {
    onabort?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onerror?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onload?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onloadend?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onloadstart?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onprogress?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    onreadystatechange?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    ontimeout?: ((resp: VMScriptResponseObject<T>) => void) | undefined;
    ... 12 more ...;
    upload?: GMRequestBaseEvents<T>;
}
details
: {
onabort?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
onerror?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
onload?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
onloadend?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
onloadstart?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined; // VM2.12.5
onprogress?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
onreadystatechange?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
ontimeout?: ((resp: VMScriptResponseObject<T>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T>) => void) | undefined;
url: string

URL relative to current page is also allowed.

url
: string;
user?: string | undefined

User for authentication.

user
?: string | undefined;
password?: string | undefined

Password for authentication.

password
?: string | undefined;
headers?: Record<string, string> | undefined

Some special headers are also allowed:

  • Cookie
  • Host
  • Origin
  • Referer
  • User-Agent
headers
?: Record<string, string> | undefined;
timeout?: number | undefined

Time to wait for the request, none by default.

@sinceVM2.9.5
timeout
?: number | undefined; // VM2.9.5
context?: unknown

Can be an object and will be assigned to context of the response object.

context
?: unknown | undefined;
anonymous?: boolean | undefined

When set to true, no cookie will be sent with the request and the response cookies will be ignored. The default value is false.

@sinceVM2.10.1
anonymous
?: boolean | undefined; // VM2.10.1
method?: string | undefined

HTTP method, default as GET.

method
?: string | undefined;
overrideMimeType?: string | undefined

A MIME type to specify with the request.

overrideMimeType
?: string | undefined;
responseType?: VMScriptResponseType | undefined

One of the following:

  • text (default value)
  • json
  • blob
  • arraybuffer
  • document
responseType
?: type VMScriptResponseType = "text" | "json" | "blob" | "arraybuffer" | "document"VMScriptResponseType | undefined;
data?: string | Blob | ArrayBuffer | DataView<ArrayBufferLike> | FormData | ReadableStream<any> | TypedArray | URLSearchParams | undefined

Data to send with the request, usually for POST and PUT requests.

data
?:
| string | ArrayBuffer | Blob | DataView | FormData | ReadableStream | type TypedArray = Uint8Array<ArrayBufferLike> | Uint8ClampedArray<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Int8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike> | BigInt64Array<ArrayBufferLike> | Float32Array<...> | Float64Array<...>TypedArray | URLSearchParams | undefined; binary?: boolean | undefined

Send the data string as a blob. This is for compatibility with Tampermonkey/Greasemonkey, where only string type is allowed in data.

@sinceVM2.12.2
binary
?: boolean | undefined; // VM2.12.2
upload?: GMRequestBaseEvents<T> | undefined
@sinceVM2.32.0
upload
?: GMRequestBaseEvents<T>; // VM2.32.0
}): { abort: () => void; };

View source on GitHub

Event handlers are functions that receive the response object detailed further down below.

NOTE

  • synchronous is not supported.

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:

declare interface 
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<T> {
status: number; statusText: string; readyState: number; responseHeaders: string; VMScriptResponseObject<T>.response: T | nullresponse: T | null; VMScriptResponseObject<T>.responseText: string | undefined

Only provided when available.

responseText
: string | undefined;
VMScriptResponseObject<T>.responseXML: Document | null

Only provided when available.

@sinceVM2.13.4
responseXML
: Document | null; // VM2.13.4
VMScriptResponseObject<T>.finalUrl: string

The final URL after redirection.

finalUrl
: string;
VMScriptResponseObject<T>.lengthComputable?: boolean | undefined

Only provided when available.

lengthComputable
?: boolean | undefined;
VMScriptResponseObject<T>.loaded?: number | undefined

Only provided when available.

loaded
?: number | undefined;
VMScriptResponseObject<T>.total?: number | undefined

Only provided when available.

total
?: number | undefined;
VMScriptResponseObject<T>.context?: unknown

The same context object you specified in details.

context
?: unknown | undefined;
}

View source on GitHub

GM_download

Since VM2.9.5

Downloads a URL to a local file.

function GM_download(options: {
    onabort?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onerror?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onload?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onloadend?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onloadstart?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onprogress?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onreadystatechange?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    ontimeout?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    url: string;
    user?: string | undefined;
    password?: string | undefined;
    headers?: Record<string, string> | undefined;
    timeout?: number | undefined;
    context?: unknown | undefined;
    anonymous?: boolean | undefined;
    name: string;
    conflictAction?: browser.downloads.FilenameConflictAction;
    saveAs?: boolean;
}): {
    abort: () => void;
} (+1 overload)

Downloads a URL to a local file. Returns a control object with a function to abort the request, same as GM_xmlhttpRequest.

GM_download
(
options: {
    onabort?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onerror?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onload?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onloadend?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onloadstart?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onprogress?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    onreadystatechange?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    ontimeout?: ((resp: VMScriptResponseObject<Blob>) => void) | undefined;
    ... 9 more ...;
    saveAs?: boolean;
}
options
: {
onabort?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
onerror?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
onload?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
onloadend?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
onloadstart?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined; // VM2.12.5
onprogress?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
onreadystatechange?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
ontimeout?: ((resp: VMScriptResponseObject<Blob>resp:
interface VMScriptResponseObject<T> {
    status: number;
    statusText: string;
    readyState: number;
    responseHeaders: string;
    response: T | null;
    responseText: string | undefined;
    responseXML: Document | null;
    finalUrl: string;
    lengthComputable?: boolean | undefined;
    loaded?: number | undefined;
    total?: number | undefined;
    context?: unknown | undefined;
}
VMScriptResponseObject
<Blob>) => void) | undefined;
url: string

URL relative to current page is also allowed.

url
: string;
user?: string | undefined

User for authentication.

user
?: string | undefined;
password?: string | undefined

Password for authentication.

password
?: string | undefined;
headers?: Record<string, string> | undefined

Some special headers are also allowed:

  • Cookie
  • Host
  • Origin
  • Referer
  • User-Agent
headers
?: Record<string, string> | undefined;
timeout?: number | undefined

Time to wait for the request, none by default.

@sinceVM2.9.5
timeout
?: number | undefined; // VM2.9.5
context?: unknown

Can be an object and will be assigned to context of the response object.

context
?: unknown | undefined;
anonymous?: boolean | undefined

When set to true, no cookie will be sent with the request and the response cookies will be ignored. The default value is false.

@sinceVM2.10.1
anonymous
?: boolean | undefined; // VM2.10.1
name: string

The filename to save as.

name
: string;
conflictAction?: browser.downloads.FilenameConflictAction | undefined

Used only when GM_info.downloadMode === 'browser'

conflictAction
?: browser.downloads.type browser.downloads.FilenameConflictAction = "uniquify" | "overwrite" | "prompt"FilenameConflictAction;
saveAs?: boolean | undefined

Shows the dialog. Used only when GM_info.downloadMode === 'browser'

saveAs
?: boolean;
}, ): { abort: () => void; };
function GM_download(url: string, name: string): {
    abort: () => void;
} (+1 overload)

Downloads a URL to a local file. Returns a control object with a function to abort the request, same as GM_xmlhttpRequest.

GM_download
(
url: string

The URL to download.

url
: string,
name: string

The filename to save as.

name
: string,
): { abort: () => void; };

View source on GitHub

GM.*

GM (since VM2.12.0) is a single variable with Greasemonkey4-compatible aliases, the async functions return a Promise that’s resolved with the returned value.