home / skills / henkisdabro / wookstar-claude-plugins / tampermonkey

This skill helps you generate and tailor Tampermonkey userscripts for browser automation, page modification, and persistent user preferences across sites.

npx playbooks add skill henkisdabro/wookstar-claude-plugins --skill tampermonkey

Review the files below or copy the command above to add this skill to your agents.

Files (19)
SKILL.md
9.5 KB
---
name: tampermonkey
description: 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).
allowed-tools: Read, Glob, Grep, Write, Edit
---

# Tampermonkey Userscript Development

Expert guidance for writing Tampermonkey userscripts - browser scripts that modify web pages, automate tasks, and enhance browsing experience.

## Quick Start Template

```javascript
// ==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](references/header-reference.md)

---

## URL Matching Quick Reference

```javascript
// 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](references/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` |

```javascript
// 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](references/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](references/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](references/http-requests.md)
- **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)
- **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)
- **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

```javascript
// @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](references/common-pitfalls.md).

---

## When Generating Userscripts

Always include in your response:

1. **Explanation** - What the script does (1-2 sentences)
2. **Complete userscript** - Full code with all headers in a code block
3. **Installation** - "Copy/paste into Tampermonkey dashboard" or "Save as .user.js"
4. **Customisation points** - What the user can safely modify (selectors, timeouts, etc.)
5. **Permissions used** - Which @grants and why they're needed
6. **Browser support** - If Chrome-only, Firefox-only, or universal

---

## Pre-Delivery Checklist

Before returning a userscript, verify:

### Critical (Must Pass)

- [ ] No hardcoded API keys, tokens, or passwords
- [ ] @match is specific (not `*://*/*`)
- [ ] All external URLs use HTTPS
- [ ] User input sanitised before DOM insertion

### Important (Should Pass)

- [ ] Wrapped in IIFE with 'use strict'
- [ ] All @grant statements are necessary
- [ ] @connect includes all external domains
- [ ] Error handling for async operations
- [ ] Null checks before DOM manipulation

### Recommended

- [ ] @version follows semantic versioning (X.Y.Z)
- [ ] Works in both Chrome and Firefox
- [ ] Comments explain non-obvious code

**For complete security checklist, see:** [security-checklist.md](references/security-checklist.md)

---

## Reference Files Guide

Load these on-demand based on user needs:

| File | When to Load |
|------|--------------|
| **Core** | |
| [header-reference.md](references/header-reference.md) | Header syntax - all @tags with examples |
| [url-matching.md](references/url-matching.md) | @match, @include, @exclude patterns |
| [patterns.md](references/patterns.md) | Common implementation patterns with code |
| [sandbox-modes.md](references/sandbox-modes.md) | Security/isolation execution contexts |
| **API** | |
| [api-sync.md](references/api-sync.md) | GM_* synchronous function usage |
| [api-async.md](references/api-async.md) | GM.* promise-based API usage |
| [api-storage.md](references/api-storage.md) | GM_setValue, GM_getValue, listeners |
| [http-requests.md](references/http-requests.md) | GM_xmlhttpRequest cross-origin |
| [web-requests.md](references/web-requests.md) | GM_webRequest interception (Firefox) |
| [api-cookies.md](references/api-cookies.md) | GM_cookie manipulation |
| [api-dom-ui.md](references/api-dom-ui.md) | addElement, addStyle, unsafeWindow |
| [api-tabs.md](references/api-tabs.md) | getTab, saveTab, openInTab |
| [api-audio.md](references/api-audio.md) | Mute/unmute tabs |
| **Quality** | |
| [common-pitfalls.md](references/common-pitfalls.md) | What breaks scripts and workarounds |
| [debugging.md](references/debugging.md) | How to debug userscripts |
| [browser-compatibility.md](references/browser-compatibility.md) | Chrome vs Firefox differences |
| [security-checklist.md](references/security-checklist.md) | Pre-delivery security validation |
| [version-numbering.md](references/version-numbering.md) | Version string comparison rules |

Overview

This skill teaches how to write Tampermonkey userscripts for browser automation, page modification, and persistent web enhancement. It provides practical patterns, header guidance (@match, @grant, @require), and cross-browser compatibility tips for Chrome, Firefox and Edge. The focus is on safe, maintainable scripts that automate interactions, inject CSS/JS, and store user preferences.

How this skill works

It inspects and explains essential userscript headers, GM_* API usage (both synchronous and promise-based), and common implementation patterns like waiting for elements, observing DOM mutations, and detecting SPA URL changes. It details permissions needed for cross-origin requests, injecting resources, and accessing page context, plus limitations and recommended workarounds. Examples include full userscript templates and a checklist to ensure secure, portable scripts.

When to use it

  • Automate repetitive browser tasks (form fills, clicks, navigation).
  • Modify page appearance or hide unwanted UI via injected CSS/HTML.
  • Scrape or extract structured data from pages you control or are permitted to scrape.
  • Detect URL changes in single-page apps and react to navigation.
  • Add persistent toggles or user preferences stored with GM_setValue/GM_getValue.

Best practices

  • Use specific @match patterns instead of *://*/* to reduce scope and risk.
  • Grant only the GM_* permissions you need; prefer @grant none when possible.
  • Wrap code in an IIFE with 'use strict' and include error handling for async operations.
  • Wait for elements with a MutationObserver or a promise-based wait utility before interacting.
  • Sanitize any user or remote input before inserting into the DOM and avoid hardcoded secrets.

Example use cases

  • Hide distracting banners and restyle a news site with GM_addStyle and a user toggle.
  • Auto-fill login fields and submit for a workflow you repeatedly perform.
  • Monitor dynamically loaded lists in an SPA and highlight items matching rules.
  • Fetch JSON from an external API using GM_xmlhttpRequest with @connect whitelisted.
  • Provide a context-menu command (GM_registerMenuCommand) to toggle features and persist choice with GM_setValue.

FAQ

Will a userscript work in both Chrome and Firefox?

Most scripts work cross-browser but check GM API differences (callbacks vs promises), require correct @grant usage, and test in each target browser.

How do I detect navigation in a single-page app?

Use window.onurlchange where supported or intercept History API methods and listen for popstate + MutationObserver as a fallback.