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: stringA unique ID of the script.
uuid: string;
injectInto: VMScriptInjectIntoThe injection mode of current script. See @inject-into for more information.
injectInto: type VMScriptInjectInto = "auto" | "page" | "content"Injection mode of a script.
VMScriptInjectInto;
script: VMScriptGMInfoScriptMetaContains 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: stringThe meta block of the script.
scriptMetaStr: string;
scriptWillUpdate: booleanWhether the script will be updated automatically.
scriptWillUpdate: boolean;
scriptHandler: stringThe name of userscript manager, which should be the string Violentmonkey.
scriptHandler: string;
version: stringVersion 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.
downloadMode: 'native' | 'browser'; // VM2.45.2
isIncognito: booleanTrue when this is an incognito profile (Chrome) or private mode (Firefox).
isIncognito: boolean; // VM2.15.4
platform: VMScriptGMInfoPlatformUnlike 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: stringA 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.
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.
userAgentData?: // VM2.20.2
| {
brands: { brand: string; version: string }[];
mobile: boolean;
platform: string;
getHighEntropyValues(hints: string[]): Promise<UADataValues>;
}
| undefined;
};
GM_cookie
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;
}
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.
CookieDetails,
callback?: (error?: string) => any,
) => void;
list: (opts: Parameters<typeof chrome.cookies.getAll>[0], callback?: (cookies?: chrome.cookies.Cookie, error?: string) => any) => voidhttpOnly 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.
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) => voidhttpOnly 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.
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;
}
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) => voidhttpOnly 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) => voidhttpOnly 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;
};
GM_getValue
Retrieves a value for current script from storage.
function GM_getValue<T>(name: string, defaultValue?: T | undefined): TRetrieves a value for current script from storage.
GM_getValue<T>(
name: stringThe name for value to load.
name: string,
defaultValue: T | undefinedThe default value to return if no value exists in the storage.
defaultValue?: T | undefined,
): T;
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: GenericObjectEach 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;
-
Using an array of keys.
let values = GM_getValues(['foo', 'bar'])Keys in storage Result foo, bar { foo: 123, bar: [1, 2, 3] }foo { foo: 123 } -
Using an object.
let values = GM_getValues({ foo: 1, bar: [2] })Keys in storage Result 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): voidSets a key / value pair for current script to storage.
GM_setValue<T>(
name: stringThe unique name for value within this script.
name: string,
value: TThe 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;
GM_setValues
Since VM2.19.1
Writes multiple values to current script’s storage.
GM_setValues( // VM2.19.1
values: GenericObjectEach 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;
GM_deleteValue
Deletes an existing key / value pair for current script from storage.
function GM_deleteValue(name: string): voidDeletes an existing key / value pair for current script from storage.
GM_deleteValue(
name: stringThe unique name for value within this script.
name: string,
): void;
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;
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[];
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): stringAdds a change listener to the storage and returns the listener ID.
GM_addValueChangeListener<T>(
name: stringThe name of the observed variable.
name: string,
callback: (name: string, oldValue: T, newValue: T, remote: boolean) => voidCalled when the value changes.
callback: (
name: stringThe name of the observed variable
name: string,
oldValue: TThe old value of the observed variable (undefined if it was created)
oldValue: T,
newValue: TThe new value of the observed variable (undefined if it was deleted)
newValue: T,
remote: booleantrue 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;
GM_removeValueChangeListener
Removes a change listener by its ID.
function GM_removeValueChangeListener(listenerId: string): voidRemoves a change listener by its ID.
GM_removeValueChangeListener(
listenerId: stringThe listener ID returned by GM_addValueChangeListener.
listenerId: string,
): void;
GM_getResourceText
Retrieves a text resource from the metadata block.
function GM_getResourceText(name: string): stringRetrieves a text resource from the Metadata Block.
GM_getResourceText(
name: stringName of a resource defined in the Metadata Block.
name: string,
): string;
GM_getResourceURL
Retrieves a blob: or data: URL of a resource from the metadata block.
function GM_getResourceURL(name: string, isBlobUrl?: boolean | undefined): stringRetrieves 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: stringName 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.
isBlobUrl?: boolean | undefined, // VM2.13.1
): string;
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.
GM_addElement( // VM2.13.1
tagName: stringA 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> | undefinedThe 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.
GM_addElement(
parentNode: HTMLElementThe 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: stringA 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> | undefinedThe 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;
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 APIdocument.createElement.
GM_addStyle
Appends and returns a <style> element with the specified CSS.
function GM_addStyle(css: string): HTMLStyleElementAppends and returns a <style> element with the specified CSS.
GM_addStyle(
css: stringThe CSS code to inject.
css: string,
): HTMLStyleElement;
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: stringThe 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 | undefinedMake the new tab active (i.e. open in foreground). Default as true.
active?: boolean | undefined;
container?: number | undefinedFirefox only.
- not specified = reuse script's tab container
0 = default (main) container
1, 2, etc. = internal container index
container?: number | undefined; // VM2.12.5
insert?: boolean | undefinedInsert 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.
insert?: boolean | undefined; // VM2.11.0
pinned?: boolean | undefinedPin the tab (i.e. show without a title at the beginning of the tab list). Default as false.
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: booleanWhether the opened tab is closed.
closed: boolean;
close: () => voidA 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: stringThe 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 | undefinedOpen 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: booleanWhether the opened tab is closed.
closed: boolean;
close: () => voidA function to explicitly close the opened tab.
close: () => void;
};
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: stringThe name to show in the popup menu.
caption: string,
onClick: (event: MouseEvent | KeyboardEvent) => voidCallback 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
options?: // VM2.15.9
| {
id?: string | undefinedDefault: 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 | undefinedA hint shown in the status bar when hovering the command.
title?: string | undefined;
autoClose?: boolean | undefinedDefault: true.
Whether to auto-close the popup after the user invoked the command.
autoClose?: boolean | undefined;
}
| undefined,
): string;
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): voidUnregisters a command which has been registered to Violentmonkey popup menu.
GM_unregisterMenuCommand(
caption: stringThe name of command to unregister.
caption: string,
): void;
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: stringMain text of the notification.
text: string;
title?: string | undefinedTitle of the notification.
title?: string | undefined;
image?: string | undefinedURL of an image to show in the notification.
image?: string | undefined;
silent?: boolean | undefinedNo sounds/vibrations when showing the notification. Only for Chromium-based browsers as of Aug 2023. Default as false.
silent?: boolean | undefined; // VM2.15.2
tag?: string | undefinedUnique 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).
tag?: string | undefined; // VM2.15.4
zombieTimeout?: number | undefinedNumber 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.
zombieTimeout?: number | undefined; // VM2.15.4
zombieUrl?: string | undefinedURL to open when a zombie notification is clicked, see zombieTimeout for more info.
zombieUrl?: string | undefined; // VM2.16.1
onclick?: (() => void) | undefinedCallback 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) | undefinedCallback 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: stringMain text of the notification.
text: string,
title: string | undefinedTitle of the notification.
title?: string | undefined,
image: string | undefinedURL of an image to show in the notification.
image?: string | undefined,
onclick: (() => void) | undefinedCallback when the notification is clicked by user.
onclick?: (() => void) | undefined,
): {
remove: () => Promise<void>Remove the notification immediately.
remove: () => Promise<void>;
};
GM_setClipboard
Sets data to system clipboard.
function GM_setClipboard(data: string, type?: string | undefined): voidSets data to system clipboard.
GM_setClipboard(
data: stringThe data to be copied to system clipboard.
data: string,
type: string | undefinedThe MIME type of data to copy. Default as text/plain.
type?: string | undefined,
): void;
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: stringURL relative to current page is also allowed.
url: string;
user?: string | undefinedUser for authentication.
user?: string | undefined;
password?: string | undefinedPassword for authentication.
password?: string | undefined;
headers?: Record<string, string> | undefinedSome special headers are also allowed:
Cookie
Host
Origin
Referer
User-Agent
headers?: Record<string, string> | undefined;
timeout?: number | undefinedTime to wait for the request, none by default.
timeout?: number | undefined; // VM2.9.5
context?: unknownCan be an object and will be assigned to context of the response object.
context?: unknown | undefined;
anonymous?: boolean | undefinedWhen set to true, no cookie will be sent with the request and the response cookies will be ignored. The default value is false.
anonymous?: boolean | undefined; // VM2.10.1
method?: string | undefinedHTTP method, default as GET.
method?: string | undefined;
overrideMimeType?: string | undefinedA MIME type to specify with the request.
overrideMimeType?: string | undefined;
responseType?: VMScriptResponseType | undefinedOne 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 | undefinedData 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 | undefinedSend the data string as a blob. This is for compatibility with Tampermonkey/Greasemonkey, where only string type is allowed in data.
binary?: boolean | undefined; // VM2.12.2
upload?: GMRequestBaseEvents<T> | undefinedupload?: GMRequestBaseEvents<T>; // VM2.32.0
}): {
abort: () => void;
};
Event handlers are functions that receive the response object detailed further down below.
NOTE
synchronousis 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 | undefinedOnly provided when available.
responseText: string | undefined;
VMScriptResponseObject<T>.responseXML: Document | nullOnly provided when available.
responseXML: Document | null; // VM2.13.4
VMScriptResponseObject<T>.finalUrl: stringThe final URL after redirection.
finalUrl: string;
VMScriptResponseObject<T>.lengthComputable?: boolean | undefinedOnly provided when available.
lengthComputable?: boolean | undefined;
VMScriptResponseObject<T>.loaded?: number | undefinedOnly provided when available.
loaded?: number | undefined;
VMScriptResponseObject<T>.total?: number | undefinedOnly provided when available.
total?: number | undefined;
VMScriptResponseObject<T>.context?: unknownThe same context object you specified in details.
context?: unknown | undefined;
}
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: stringURL relative to current page is also allowed.
url: string;
user?: string | undefinedUser for authentication.
user?: string | undefined;
password?: string | undefinedPassword for authentication.
password?: string | undefined;
headers?: Record<string, string> | undefinedSome special headers are also allowed:
Cookie
Host
Origin
Referer
User-Agent
headers?: Record<string, string> | undefined;
timeout?: number | undefinedTime to wait for the request, none by default.
timeout?: number | undefined; // VM2.9.5
context?: unknownCan be an object and will be assigned to context of the response object.
context?: unknown | undefined;
anonymous?: boolean | undefinedWhen set to true, no cookie will be sent with the request and the response cookies will be ignored. The default value is false.
anonymous?: boolean | undefined; // VM2.10.1
name: stringThe filename to save as.
name: string;
conflictAction?: browser.downloads.FilenameConflictAction | undefinedUsed only when GM_info.downloadMode === 'browser'
conflictAction?: browser.downloads.type browser.downloads.FilenameConflictAction = "uniquify" | "overwrite" | "prompt"FilenameConflictAction;
saveAs?: boolean | undefinedShows 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: stringThe URL to download.
url: string,
name: stringThe filename to save as.
name: string,
): {
abort: () => void;
};
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.
-
GM.addElement - since VM2.13.1
-
GM.cookie - since VM2.35.1
-
GM.registerMenuCommand - since VM2.12.10, GM4.11
-
GM.deleteValue (async)
-
GM.deleteValues since VM2.19.1 (async)
-
GM.download (async since VM2.18.3)
-
GM.getResourceUrl (async) - in VM2.12.0…2.13.0 it was misspelled as
GM.getResourceURL -
GM.getValue (async)
-
GM.getValues since VM2.19.1 (async)
-
GM.listValues (async)
-
GM.setValue (async)
-
GM.setValues since VM2.19.1 (async)
-
GM.xmlHttpRequest (async since VM2.18.3),
His uppercase// compatible with multiple userscript managers GM.xmlHttpRequest({ url, onload: res => {/*....*/} });// compatible with multiple userscript managers const res = await new Promise((resolve, reject) => { GM.xmlHttpRequest({ url, onload: resolve, onerror: reject }); });// VM2.18.3+, TM const res = await GM.xmlHttpRequest({ url });// VM2.18.3+, TM const control = GM.xmlHttpRequest({ url }); myButton.addEventListener('click', control.abort, { once: true }); const res = await control;