Tampermonkey Userscript Development
Expert guidance for writing Tampermonkey userscripts - browser scripts that modify web pages, automate tasks, and enhance browsing experience.
Quick Start Template
// ==UserScript==
// @name My Script Name // <- CUSTOMISE: Unique script name
// @namespace https://example.com/scripts/ // <- CUSTOMISE: Your unique namespace
// @version 1.0.0 // <- INCREMENT on updates
// @description Brief description of the script // <- CUSTOMISE: What it does
// @author Your Name // <- CUSTOMISE: Your name
// @match https://example.com/* // <- CUSTOMISE: Target URL pattern
// @grant none // <- ADD permissions as needed
// @run-at document-idle // <- ADJUST timing if needed
// ==/UserScript==
(function() {
'use strict';
// Your code here
console.log('Script loaded!');
})();
Essential Header Tags
| Tag |
Required |
Purpose |
Example |
@name |
Yes |
Script name (supports i18n with :locale) |
@name My Script |
@namespace |
Recommended |
Unique identifier namespace |
@namespace https://yoursite.com/ |
@version |
Yes* |
Version for updates (*required for auto-update) |
@version 1.2.3 |
@description |
Recommended |
What the script does |
@description Enhances page layout |
@match |
Yes** |
URLs to run on (**or @include) |
@match https://example.com/* |
@grant |
Situational |
API permissions (use none for no GM_* APIs) |
@grant GM_setValue |
@run-at |
Optional |
When to inject (default: document-idle) |
@run-at document-start |
For complete header documentation, see: header-reference.md
URL Matching Quick Reference
// Exact domain // @match https://example.com/*
// All subdomains // @match https://*.example.com/*
// HTTP and HTTPS // @match *://example.com/*
// Exclude paths (with @match) // @exclude https://example.com/admin/*
For advanced patterns (regex, @include, specific paths), see: url-matching.md
@grant Permissions Quick Reference
| You Need To... |
Grant This |
| Store persistent data |
@grant GM_setValue + @grant GM_getValue |
| Make cross-origin requests |
@grant GM_xmlhttpRequest + @connect domain |
| Add custom CSS |
@grant GM_addStyle |
| Access page's window |
@grant unsafeWindow |
| Show notifications |
@grant GM_notification |
| Add menu commands |
@grant GM_registerMenuCommand |
| Detect URL changes (SPA) |
@grant window.onurlchange |
// Disable sandbox (no GM_* except GM_info)
// @grant none
// Cross-origin requests require @connect
// @grant GM_xmlhttpRequest
// @connect api.example.com
// @connect *.googleapis.com
For complete permissions guide, see: header-reference.md
@run-at Injection Timing
| Value |
When Script Runs |
Use Case |
document-start |
Before DOM exists |
Block resources, modify globals early |
document-body |
When body exists |
Early DOM manipulation |
document-end |
At DOMContentLoaded |
Most scripts - DOM ready |
document-idle |
After DOMContentLoaded (default) |
Safe default |
context-menu |
On right-click menu |
User-triggered actions |
Common Patterns
These patterns are used frequently. Brief summaries are below - load patterns.md for full implementations with code examples.
- Wait for Element - Promise-based MutationObserver that resolves when a CSS selector appears in the DOM, with configurable timeout
- SPA URL Change Detection - Detect navigation in single-page apps using
window.onurlchange grant or History API interception
- Cross-Origin Request - Fetch data from external APIs using
GM_xmlhttpRequest with @connect domain whitelisting. See also http-requests.md
- Add Custom Styles - Inject CSS with
GM_addStyle to restyle pages or hide elements. See also api-dom-ui.md
- Persistent Settings - Store user preferences with
GM_setValue/GM_getValue and expose toggle via GM_registerMenuCommand. See also api-storage.md
- DOM Mutation Observation - Watch for dynamically added content with MutationObserver (debounced variant included)
- Element Manipulation - Inject HTML, remove/hide elements, replace text across the page
- Keyboard Shortcuts - Simple handlers and a shortcut manager with modifier key support
- Data Extraction - Extract table data to arrays/objects, collect and filter page links
- Error Handling - Safe wrapper for try/catch and async retry with exponential backoff
External Resources
// @require - Load external scripts
// @require https://code.jquery.com/jquery-3.6.0.min.js#sha256-/xUj+3OJU...
// @require tampermonkey://vendor/jquery.js // Built-in library
// @resource - Preload and inject external CSS
// @resource myCSS https://example.com/style.css // Then: GM_addStyle(GM_getResourceText('myCSS'))
// @grant GM_getResourceText
// @grant GM_addStyle
What Tampermonkey Cannot Do
Userscripts have limitations:
- Access local files - Cannot read/write files on your computer
- Run before page scripts - In isolated sandbox mode, page scripts run first
- Access cross-origin iframes - Browser security prevents this
- Persist across machines - GM storage is local to each browser
- Bypass all CSP - Some very strict CSP cannot be bypassed
Most limitations have workarounds - see common-pitfalls.md.
When Generating Userscripts
Always include in your response:
- Explanation - What the script does (1-2 sentences)
- Complete userscript - Full code with all headers in a code block
- Installation - "Copy/paste into Tampermonkey dashboard" or "Save as .user.js"
- Customisation points - What the user can safely modify (selectors, timeouts, etc.)
- Permissions used - Which @grants and why they're needed
- Browser support - If Chrome-only, Firefox-only, or universal
Pre-Delivery Checklist
Before returning a userscript, verify:
Critical (Must Pass)
Important (Should Pass)
Recommended
For complete security checklist, see: security-checklist.md
Reference Files Guide
Load these on-demand based on user needs:
| File |
When to Load |
| Core |
|
| header-reference.md |
Header syntax - all @tags with examples |
| url-matching.md |
@match, @include, @exclude patterns |
| patterns.md |
Common implementation patterns with code |
| sandbox-modes.md |
Security/isolation execution contexts |
| API |
|
| api-sync.md |
GM_* synchronous function usage |
| api-async.md |
GM.* promise-based API usage |
| api-storage.md |
GM_setValue, GM_getValue, listeners |
| http-requests.md |
GM_xmlhttpRequest cross-origin |
| web-requests.md |
GM_webRequest interception (Firefox) |
| api-cookies.md |
GM_cookie manipulation |
| api-dom-ui.md |
addElement, addStyle, unsafeWindow |
| api-tabs.md |
getTab, saveTab, openInTab |
| api-audio.md |
Mute/unmute tabs |
| Quality |
|
| common-pitfalls.md |
What breaks scripts and workarounds |
| debugging.md |
How to debug userscripts |
| browser-compatibility.md |
Chrome vs Firefox differences |
| security-checklist.md |
Pre-delivery security validation |
| version-numbering.md |
Version string comparison rules |
1---2name: tampermonkey3description: Write Tampermonkey userscripts for browser automation, page modification, and web enhancement. Use when creating browser scripts, writing greasemonkey scripts, automating user interactions, injecting CSS or JavaScript into web pages, modifying website behaviour, building browser extensions, hiding unwanted page elements, adding form auto-fill, scraping website data, intercepting requests, detecting URL changes in SPAs, or storing persistent user preferences. Covers userscript headers (@match, @grant, @require), synchronous and async GM_* API functions, common patterns (DOM mutation, URL change detection, element waiting), security sandboxing, and cross-browser compatibility (Chrome, Firefox, Edge).4---5
6# Tampermonkey Userscript Development
7
8Expert guidance for writing Tampermonkey userscripts - browser scripts that modify web pages, automate tasks, and enhance browsing experience.
9
10## Quick Start Template
11
12```javascript
13// ==UserScript==
14// @name My Script Name // <- CUSTOMISE: Unique script name
15// @namespace https://example.com/scripts/ // <- CUSTOMISE: Your unique namespace
16// @version 1.0.0 // <- INCREMENT on updates
17// @description Brief description of the script // <- CUSTOMISE: What it does
18// @author Your Name // <- CUSTOMISE: Your name
19// @match https://example.com/* // <- CUSTOMISE: Target URL pattern
20// @grant none // <- ADD permissions as needed
21// @run-at document-idle // <- ADJUST timing if needed
22// ==/UserScript==
23
24(function() {
25 'use strict';
26
27 // Your code here
28 console.log('Script loaded!');
29})();
30```
31
32---
33
34## Essential Header Tags
35
36| Tag | Required | Purpose | Example |
37|-----|----------|---------|---------|
38| `@name` | Yes | Script name (supports i18n with `:locale`) | `@name My Script` |
39| `@namespace` | Recommended | Unique identifier namespace | `@namespace https://yoursite.com/` |
40| `@version` | Yes* | Version for updates (*required for auto-update) | `@version 1.2.3` |
41| `@description` | Recommended | What the script does | `@description Enhances page layout` |
42| `@match` | Yes** | URLs to run on (**or @include) | `@match https://example.com/*` |
43| `@grant` | Situational | API permissions (use `none` for no GM_* APIs) | `@grant GM_setValue` |
44| `@run-at` | Optional | When to inject (default: `document-idle`) | `@run-at document-start` |
45
46**For complete header documentation, see:** [header-reference.md](references/header-reference.md)
47
48---
49
50## URL Matching Quick Reference
51
52```javascript
53// Exact domain // @match https://example.com/*
54// All subdomains // @match https://*.example.com/*
55// HTTP and HTTPS // @match *://example.com/*
56// Exclude paths (with @match) // @exclude https://example.com/admin/*
57```
58
59**For advanced patterns (regex, @include, specific paths), see:** [url-matching.md](references/url-matching.md)
60
61---
62
63## @grant Permissions Quick Reference
64
65| You Need To... | Grant This |
66|----------------|------------|
67| Store persistent data | `@grant GM_setValue` + `@grant GM_getValue` |
68| Make cross-origin requests | `@grant GM_xmlhttpRequest` + `@connect domain` |
69| Add custom CSS | `@grant GM_addStyle` |
70| Access page's window | `@grant unsafeWindow` |
71| Show notifications | `@grant GM_notification` |
72| Add menu commands | `@grant GM_registerMenuCommand` |
73| Detect URL changes (SPA) | `@grant window.onurlchange` |
74
75```javascript
76// Disable sandbox (no GM_* except GM_info)
77// @grant none
78
79// Cross-origin requests require @connect
80// @grant GM_xmlhttpRequest
81// @connect api.example.com
82// @connect *.googleapis.com
83```
84
85**For complete permissions guide, see:** [header-reference.md](references/header-reference.md)
86
87---
88
89## @run-at Injection Timing
90
91| Value | When Script Runs | Use Case |
92|-------|------------------|----------|
93| `document-start` | Before DOM exists | Block resources, modify globals early |
94| `document-body` | When body exists | Early DOM manipulation |
95| `document-end` | At DOMContentLoaded | Most scripts - DOM ready |
96| `document-idle` | After DOMContentLoaded (default) | Safe default |
97| `context-menu` | On right-click menu | User-triggered actions |
98
99---
100
101## Common Patterns
102
103These patterns are used frequently. Brief summaries are below - load [patterns.md](references/patterns.md) for full implementations with code examples.
104
105- **Wait for Element** - Promise-based MutationObserver that resolves when a CSS selector appears in the DOM, with configurable timeout
106- **SPA URL Change Detection** - Detect navigation in single-page apps using `window.onurlchange` grant or History API interception
107- **Cross-Origin Request** - Fetch data from external APIs using `GM_xmlhttpRequest` with `@connect` domain whitelisting. See also [http-requests.md](references/http-requests.md)
108- **Add Custom Styles** - Inject CSS with `GM_addStyle` to restyle pages or hide elements. See also [api-dom-ui.md](references/api-dom-ui.md)
109- **Persistent Settings** - Store user preferences with `GM_setValue`/`GM_getValue` and expose toggle via `GM_registerMenuCommand`. See also [api-storage.md](references/api-storage.md)
110- **DOM Mutation Observation** - Watch for dynamically added content with MutationObserver (debounced variant included)
111- **Element Manipulation** - Inject HTML, remove/hide elements, replace text across the page
112- **Keyboard Shortcuts** - Simple handlers and a shortcut manager with modifier key support
113- **Data Extraction** - Extract table data to arrays/objects, collect and filter page links
114- **Error Handling** - Safe wrapper for try/catch and async retry with exponential backoff
115
116---
117
118## External Resources
119
120```javascript
121// @require - Load external scripts
122// @require https://code.jquery.com/jquery-3.6.0.min.js#sha256-/xUj+3OJU...
123// @require tampermonkey://vendor/jquery.js // Built-in library
124
125// @resource - Preload and inject external CSS
126// @resource myCSS https://example.com/style.css // Then: GM_addStyle(GM_getResourceText('myCSS'))
127// @grant GM_getResourceText
128// @grant GM_addStyle
129```
130
131---
132
133## What Tampermonkey Cannot Do
134
135Userscripts have limitations:
136
137- **Access local files** - Cannot read/write files on your computer
138- **Run before page scripts** - In isolated sandbox mode, page scripts run first
139- **Access cross-origin iframes** - Browser security prevents this
140- **Persist across machines** - GM storage is local to each browser
141- **Bypass all CSP** - Some very strict CSP cannot be bypassed
142
143Most limitations have **workarounds** - see [common-pitfalls.md](references/common-pitfalls.md).
144
145---
146
147## When Generating Userscripts
148
149Always include in your response:
150
1511. **Explanation** - What the script does (1-2 sentences)
1522. **Complete userscript** - Full code with all headers in a code block
1533. **Installation** - "Copy/paste into Tampermonkey dashboard" or "Save as .user.js"
1544. **Customisation points** - What the user can safely modify (selectors, timeouts, etc.)
1555. **Permissions used** - Which @grants and why they're needed
1566. **Browser support** - If Chrome-only, Firefox-only, or universal
157
158---
159
160## Pre-Delivery Checklist
161
162Before returning a userscript, verify:
163
164### Critical (Must Pass)
165
166- [ ] No hardcoded API keys, tokens, or passwords
167- [ ] @match is specific (not `*://*/*`)
168- [ ] All external URLs use HTTPS
169- [ ] User input sanitised before DOM insertion
170
171### Important (Should Pass)
172
173- [ ] Wrapped in IIFE with 'use strict'
174- [ ] All @grant statements are necessary
175- [ ] @connect includes all external domains
176- [ ] Error handling for async operations
177- [ ] Null checks before DOM manipulation
178
179### Recommended
180
181- [ ] @version follows semantic versioning (X.Y.Z)
182- [ ] Works in both Chrome and Firefox
183- [ ] Comments explain non-obvious code
184
185**For complete security checklist, see:** [security-checklist.md](references/security-checklist.md)
186
187---
188
189## Reference Files Guide
190
191Load these on-demand based on user needs:
192
193| File | When to Load |
194|------|--------------|
195| **Core** | |
196| [header-reference.md](references/header-reference.md) | Header syntax - all @tags with examples |
197| [url-matching.md](references/url-matching.md) | @match, @include, @exclude patterns |
198| [patterns.md](references/patterns.md) | Common implementation patterns with code |
199| [sandbox-modes.md](references/sandbox-modes.md) | Security/isolation execution contexts |
200| **API** | |
201| [api-sync.md](references/api-sync.md) | GM_* synchronous function usage |
202| [api-async.md](references/api-async.md) | GM.* promise-based API usage |
203| [api-storage.md](references/api-storage.md) | GM_setValue, GM_getValue, listeners |
204| [http-requests.md](references/http-requests.md) | GM_xmlhttpRequest cross-origin |
205| [web-requests.md](references/web-requests.md) | GM_webRequest interception (Firefox) |
206| [api-cookies.md](references/api-cookies.md) | GM_cookie manipulation |
207| [api-dom-ui.md](references/api-dom-ui.md) | addElement, addStyle, unsafeWindow |
208| [api-tabs.md](references/api-tabs.md) | getTab, saveTab, openInTab |
209| [api-audio.md](references/api-audio.md) | Mute/unmute tabs |
210| **Quality** | |
211| [common-pitfalls.md](references/common-pitfalls.md) | What breaks scripts and workarounds |
212| [debugging.md](references/debugging.md) | How to debug userscripts |
213| [browser-compatibility.md](references/browser-compatibility.md) | Chrome vs Firefox differences |
214| [security-checklist.md](references/security-checklist.md) | Pre-delivery security validation |
215| [version-numbering.md](references/version-numbering.md) | Version string comparison rules |