tampermonkey-dev

Guides development of Tampermonkey user scripts using Vite + Vue 3 + vite-plugin-monkey. Applicable when injecting features into existing pages (floating panels, buttons, data extraction, cross-origin page requests), or when building browser-side helpers, page-enhancement plugins, or embedded page-scraping UIs. Triggered when users mention Tampermonkey, user scripts, GreasyFork, “monkey” scripts, or express intents like “add a button on site X” or “read data from page Y” to evaluate and guide a user-script approach.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "tampermonkey-dev" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-42450b1d82af7becce002803a0717a7b5743b440fa10e21e40a40872325e728c. Verify the upstream source and version against https://skillhub.cn/skills/user_d83dc1a5/kkluvvs-002 before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Guides development of Tampermonkey user scripts using Vite + Vue 3 + vite-plugin-monkey. Applicable when injecting features into existing pages (floating panels, buttons, data extraction, cross-origin page requests), or when building browser-side helpers, page-enhancement plugins, or embedded page-scraping UIs. Triggered when users mention Tampermonkey, user scripts, GreasyFork, “monkey” scripts, or express intents like “add a button on site X” or “read data from page Y” to evaluate and guide a user-script approach.

0 Downloads

Introduction source: third_party · user_d83dc1a5 · 1.0.0 Reference

SkillPi interpretation

Tasks
Before scaffolding, ask the user these questions. If any answer points to Chrome Extension, pivot immediately.
Audience
Not specified in the source documentation.
Inputs and outputs
Example 1: Basic Scaffold** **User Input**: "I want to add a floating button to GitHub that shows the current repo's star count when clicked." **Skill Output**: - `vite.config.ts` with `include: ['https://github.com/*']` and `connect: ['api.github.com']`. - `src/main.ts` creating `#tm-app` and mounting Vue. - `src/App.vue` with a draggable button and a panel showing star count fetched via `standard` GET to `https://api.github.com/repos/{owner}/{repo}`. - `src/utils/client.ts` providing `get(url)` for the GitHub API call. Example 2: Impersonating the Host Page** **User Input**: "I need a tool injected into a customer service backend that lets me copy the current conversation's buyer ID with o
Software, accounts and paid services
Not specified in the source documentation.
Limits and differences
Not specified in the source documentation.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: tampermonkey-dev
description: >
  Guide the user through developing a Tampermonkey userscript using Vite + Vue 3 + vite-plugin-monkey.
  Trigger this skill when the user mentions Tampermonkey, userscripts, GreasyFork, monkey scripts,
  or wants to inject functionality into an existing webpage (floating panels, buttons, data extraction,
  cross-domain requests from a page). Also trigger when the user wants to build a browser-side
  assistant tool, a page augmentation plugin, or a web scraping UI that lives inside the target page.
  Even if the user only says "I want to add a button to website X" or "read data from page Y",
  use this skill to determine if a userscript is the right approach.

Decision Gate: Is Tampermonkey the Right Tool?

Before scaffolding, ask the user these questions. If any answer points to Chrome Extension, pivot immediately.

  1. Scope: Does the feature need to run inside a specific website (or set of websites)?
    • Yes -> Userscript is suitable.
    • No (e.g., browser toolbar, new tab page, context menu) -> Chrome Extension required.
  2. Network Interception: Does the feature need to intercept, block, or redirect the page's own network requests?
    • Yes -> Chrome Extension (webRequest API). Userscripts can only send requests, not intercept the page's traffic.
  3. Browser UI Access: Does the feature need to modify the browser's native UI (address bar, bookmarks, right-click menu, download manager)?
    • Yes -> Chrome Extension.
  4. Pure CSS changes only?
    • Yes -> Recommend Stylus or a simple userstyle. A full userscript is overkill.

Execution Workflow

When the user confirms a userscript is appropriate, follow these steps in order. Do not skip steps.

Step 1: Identify Target Pages

  • Ask the user for the exact URL(s) or URL patterns where the script should run.
  • Determine include (loose match, supports wildcards/regex) and match (strict match) in vite.config.ts.
  • Determine connect array: all domains/IPs the script needs to call via GM_xmlhttpRequest.

Step 2: Scaffold the Project

Generate the following minimal structure:

my-userscript/
├── src/
│   ├── main.ts              # Entry point: create container div, mount Vue app
│   ├── App.vue              # Floating button + drag logic + menu container
│   ├── utils/
│   │   ├── client.ts        # API abstraction: tp_*, cr_*, standard
│   │   └── pageContext.ts   # (Optional) Extract data from host page's Vue/React/store
│   └── views/
│       └── Feature.vue      # The actual feature UI
├── vite.config.ts
├── package.json
└── .env.development

Use this package.json baseline:

{
  "name": "my-userscript",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.4.0",
    "axios": "^1.6.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.0.0",
    "vite": "^5.0.0",
    "vite-plugin-monkey": "^4.0.0",
    "vue-tsc": "^2.0.0"
  }
}

Step 3: Configure vite-plugin-monkey

Generate vite.config.ts:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import monkey, { util } from 'vite-plugin-monkey';
import { resolve } from 'path';

export default defineConfig({
  plugins: [
    vue(),
    monkey({
      entry: 'src/main.ts',
      userscript: {
        name: 'my_userscript',
        version: '1.0.0',
        description: 'A userscript for ...',
        include: ['https://target-site.com/*'],
        match: ['https://target-site.com/specific-page'],
        connect: ['api.backend.com', '127.0.0.1'],
        license: 'MIT',
      },
    }),
    // Optional: auto-import Vue APIs
    // AutoImport({ imports: [util.unimportPreset] }),
  ],
  resolve: {
    alias: { '@': resolve(__dirname, './src') },
  },
});

Critical: Every domain the script calls via GM_xmlhttpRequest must be listed in connect. Otherwise Tampermonkey blocks the request.

Step 4: Write the Entry Point (src/main.ts)

The entry must create a new DOM container and mount an isolated Vue app. Do not mount onto the host page's existing root element.

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia'; // optional

const div = document.createElement('div');
div.id = 'tm-app'; // use a unique id to avoid collisions
const app = createApp(App);
app.use(createPinia()); // optional
app.mount(div);
document.body.append(div);

Why isolation matters: The host page may use Vue 2, React, or jQuery. Mounting onto their root can cause conflicts. A standalone <div> guarantees your Vue 3 app runs in its own shadow-free but DOM-isolated tree.

Step 5: Write App.vue (Floating Trigger + Menu)

App.vue serves as the anchor. It provides a draggable floating button. Clicking opens a menu/panel containing the actual features.

Required elements:

  1. Floating button: position: fixed, z-index: 9999 or higher. Use an isolated stacking context (isolation: isolate) to prevent z-index bleeding.
  2. Drag logic:
    • mousedown: record start position, attach global mousemove/mouseup listeners.
    • mousemove: calculate delta. If total distance > threshold (e.g., 5px), flag as "dragging" and update left/top.
    • mouseup: if not dragging, toggle menu. If dragging, persist position (e.g., GM_setValue).
  3. Boundary check: Keep button inside viewport (Math.max(0, Math.min(x, innerWidth - btnWidth))).
  4. Menu panel positioning: Calculate available space. If button is in bottom-right, panel should open top-left to avoid clipping.
  5. Menu z-index: Must be higher than the button. If button is 9999, menu should be 10000+. Any modals inside the menu should be 10001+.
  6. Layering rule for selects/messages inside modals: If using Ant Design Vue, either use :getPopupContainer="trigger => trigger.parentNode" on <a-select> so dropdowns render inside the modal tree, or set global CSS .ant-select-dropdown { z-index: 10004 !important; } and .ant-message { z-index: 10003 !important; }.

Step 6: Design the API Layer (src/utils/client.ts)

Userscripts face a unique problem: they live in the page's origin but often need to talk to other origins. Provide three request modes:

Mode A: tp_* (Tampermonkey Plugin Backend)

  • Use case: Calling a dedicated backend API built for the userscript (e.g., mock data service, tracking API).
  • Base URL: Loaded from import.meta.env.VITE_BASE_API.
  • Engine: GM_xmlhttpRequest.
  • Cookie behavior: Does NOT automatically carry the page's cookies. If auth is needed, pass tokens explicitly.
  • Typical implementation:
    tp_request(method, url, options) {
      url = url.startsWith('http') ? url : import.meta.env.VITE_BASE_API + url;
      return request(method, url, options);
    }

Mode B: cr_* (Current Origin / Impersonate Page)

  • Use case: Calling the host page's own backend API (e.g., login, user info, page-specific endpoints).
  • Base URL: window.location.origin.
  • Engine: Native XMLHttpRequest (_mode = 'xhr').
  • Cookie behavior: Automatically carries the page's session cookies because it's a same-origin XHR.
  • Why this matters: The host backend cannot distinguish a cr_post request from a legitimate page request. This is essential for actions that require the user's active session.
  • Typical implementation:
    cr_request(method, url, options) {
      url = url.startsWith('http') ? url : window.location.origin + url;
      options._mode = 'xhr';
      return request(method, url, options);
    }

Mode C: standard (Direct External Request)

  • Use case: Calling arbitrary external services (Jenkins, Nacos, third-party APIs).
  • Base URL: None -- caller provides full URL.
  • Engine: GM_xmlhttpRequest.
  • Typical implementation:
    request(method, url, options) {
      options.method = method;
      return ajax(url, options);
    }

Engine Switching (ajax.js)

The underlying ajax.js decides which engine to use based on _mode:

  • If _mode === 'xhr': use native XMLHttpRequest.
  • Otherwise: use GM_xmlhttpRequest (if available).
  • This abstraction lets the rest of the codebase remain engine-agnostic.

Step 7: Extract Data from the Host Page (Optional)

If the feature needs to read the host page's internal state (e.g., current conversation, current product, user info), do not ask the user to manually input it. Instead, probe the page's JS runtime.

Strategy:

  1. Collect DOM nodes that carry Vue markers: __vue__, __vue_app__, __vueParentComponent.
  2. From __vue_app__, access _context.config.globalProperties.$store or _context.provides.pinia.
  3. For Pinia, the internal store map is _s (a Map). Iterate it to find candidate stores.
  4. Recursively scan candidate objects. Score them based on expected field names (e.g., conversationId, messages, userId).
  5. Unwrap Vue 3 reactivity: check for __v_isRef, .value, ._value and drill down (limit depth to ~6).
  6. Support both Vue 2 (window.app.__vue__.$store.state.xxx) and Vue 3 / Pinia.

Important: This is heuristic. If the host page changes its internal structure, extraction may break. Advise the user to treat this as best-effort and provide manual fallback inputs.

Step 8: Build and Distribute

npm run build

This produces dist/<name>.user.js. Distribution methods:

  1. Manual: Copy the file content into Tampermonkey's "New Script" editor.
  2. GreasyFork: Upload the file to greasyfork.org for public distribution.
  3. Internal: Host the .user.js on an internal server and share the raw URL. Users can install it directly via Tampermonkey's "Install from URL".

Input / Output Examples

Example 1: Basic Scaffold

  • User Input: "I want to add a floating button to GitHub that shows the current repo's star count when clicked."
  • Skill Output:
    • vite.config.ts with include: ['https://github.com/*'] and connect: ['api.github.com'].
    • src/main.ts creating #tm-app and mounting Vue.
    • src/App.vue with a draggable button and a panel showing star count fetched via standard GET to https://api.github.com/repos/{owner}/{repo}.
    • src/utils/client.ts providing get(url) for the GitHub API call.

Example 2: Impersonating the Host Page

  • User Input: "I need a tool injected into a customer service backend that lets me copy the current conversation's buyer ID with one click."
  • Skill Output:
    • vite.config.ts with include: ['https://cs-backend.company.com/*'].
    • src/utils/pageContext.ts probing the page's Vue/Pinia store for conversation / buyerId.
    • src/App.vue with a copy button that reads buyerId from page context and copies to clipboard.
    • No client.ts needed because no external API is called.

Example 3: Dedicated Backend + Cross-domain

  • User Input: "I want a script that works on any page: select some text, click a floating button, and send it to my backend for translation."
  • Skill Output:
    • vite.config.ts with include: ['*'] (all pages) and connect: ['my-translate-api.com'].
    • src/utils/client.ts with tp_post pointing to VITE_BASE_API.
    • src/App.vue capturing window.getSelection()?.toString() and sending it via tp_post('/api/translate', { text }).
    • CORS is handled by GM_xmlhttpRequest because my-translate-api.com is in connect.

Anti-patterns (Explicitly Avoid)

  1. Never mount onto the host page's root element (e.g., #app). Always create your own <div>.
  2. Never assume the host page uses Vue 3. pageContext.ts must support Vue 2 (__vue__.$store) and Vue 3 / Pinia fallback.
  3. Never use fetch for cross-domain requests. Always route through GM_xmlhttpRequest via the request abstraction, and ensure domains are in connect.
  4. Never hardcode URLs without BASE_URL abstraction. If multiple API calls hit the same host, extract a constant.
  5. Do not recommend Tampermonkey for: browser-wide features, network interception, native UI modification, or pure CSS changes.

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 解决现代用户脚本开发的核心痛点:跨域请求、页面上下文提取、UI隔离
  • 提供完整工具链指导(Vite + Vue 3 + vite-plugin-monkey)
  • 覆盖多种实际场景:GitHub增强、客服后台工具、通用文本处理
Trigger Precision88/100

Areas to improve

  • 触发词覆盖范围 Reported severity: Minor

    描述中重复了frontmatter的description内容

    Recommendation: 移除skill_body中重复的description段落以避免冗余

Highlights

  • 触发词全面覆盖用户脚本相关术语(Tampermonkey, userscripts, GreasyFork等)
  • 明确识别用户意图:页面注入、浮动面板、数据提取、跨域请求
Structure and Standards95/100

Highlights

  • 结构清晰:决策门控→执行流程→示例→反模式
  • 步骤划分明确,每步有具体产出物和代码模板
  • 包含端到端示例和常见陷阱规避指南
Execution Reliability90/100

Highlights

  • 工具版本明确指定,避免兼容性问题
  • 关键配置项(如connect数组)有强调说明
  • API抽象层设计合理,支持多种请求模式
  • UI层z-index和拖拽逻辑有详细实现指导
Evidence Verifiability (mean of the first four)91/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • api.github.com
  • cs-backend.company.com
  • github.com
  • greasyfork.org
  • target-site.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Not specified in the source documentation.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.