tampermonkey-dev
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.
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
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.
- 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.
- Network Interception: Does the feature need to intercept, block, or redirect the page's own network requests?
- Yes -> Chrome Extension (
webRequestAPI). Userscripts can only send requests, not intercept the page's traffic.
- Yes -> Chrome Extension (
- 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.
- 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) andmatch(strict match) invite.config.ts. - Determine
connectarray: all domains/IPs the script needs to call viaGM_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:
- Floating button:
position: fixed,z-index: 9999or higher. Use an isolated stacking context (isolation: isolate) to prevent z-index bleeding. - Drag logic:
mousedown: record start position, attach globalmousemove/mouseuplisteners.mousemove: calculate delta. If total distance > threshold (e.g., 5px), flag as "dragging" and updateleft/top.mouseup: if not dragging, toggle menu. If dragging, persist position (e.g.,GM_setValue).
- Boundary check: Keep button inside viewport (
Math.max(0, Math.min(x, innerWidth - btnWidth))). - Menu panel positioning: Calculate available space. If button is in bottom-right, panel should open top-left to avoid clipping.
- 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+.
- 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_postrequest 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 nativeXMLHttpRequest. - 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:
- Collect DOM nodes that carry Vue markers:
__vue__,__vue_app__,__vueParentComponent. - From
__vue_app__, access_context.config.globalProperties.$storeor_context.provides.pinia. - For Pinia, the internal store map is
_s(aMap). Iterate it to find candidate stores. - Recursively scan candidate objects. Score them based on expected field names (e.g.,
conversationId,messages,userId). - Unwrap Vue 3 reactivity: check for
__v_isRef,.value,._valueand drill down (limit depth to ~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:
- Manual: Copy the file content into Tampermonkey's "New Script" editor.
- GreasyFork: Upload the file to greasyfork.org for public distribution.
- Internal: Host the
.user.json 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.tswithinclude: ['https://github.com/*']andconnect: ['api.github.com'].src/main.tscreating#tm-appand mounting Vue.src/App.vuewith a draggable button and a panel showing star count fetched viastandardGET tohttps://api.github.com/repos/{owner}/{repo}.src/utils/client.tsprovidingget(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.tswithinclude: ['https://cs-backend.company.com/*'].src/utils/pageContext.tsprobing the page's Vue/Pinia store forconversation/buyerId.src/App.vuewith a copy button that readsbuyerIdfrom page context and copies to clipboard.- No
client.tsneeded 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.tswithinclude: ['*'](all pages) andconnect: ['my-translate-api.com'].src/utils/client.tswithtp_postpointing toVITE_BASE_API.src/App.vuecapturingwindow.getSelection()?.toString()and sending it viatp_post('/api/translate', { text }).- CORS is handled by
GM_xmlhttpRequestbecausemy-translate-api.comis inconnect.
Anti-patterns (Explicitly Avoid)
- Never mount onto the host page's root element (e.g.,
#app). Always create your own<div>. - Never assume the host page uses Vue 3.
pageContext.tsmust support Vue 2 (__vue__.$store) and Vue 3 / Pinia fallback. - Never use
fetchfor cross-domain requests. Always route throughGM_xmlhttpRequestvia therequestabstraction, and ensure domains are inconnect. - Never hardcode URLs without
BASE_URLabstraction. If multiple API calls hit the same host, extract a constant. - Do not recommend Tampermonkey for: browser-wide features, network interception, native UI modification, or pure CSS changes.
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 解决现代用户脚本开发的核心痛点:跨域请求、页面上下文提取、UI隔离
- 提供完整工具链指导(Vite + Vue 3 + vite-plugin-monkey)
- 覆盖多种实际场景:GitHub增强、客服后台工具、通用文本处理
Areas to improve
-
触发词覆盖范围 Reported severity: Minor
描述中重复了frontmatter的description内容
Recommendation: 移除skill_body中重复的description段落以避免冗余
Highlights
- 触发词全面覆盖用户脚本相关术语(Tampermonkey, userscripts, GreasyFork等)
- 明确识别用户意图:页面注入、浮动面板、数据提取、跨域请求
Highlights
- 结构清晰:决策门控→执行流程→示例→反模式
- 步骤划分明确,每步有具体产出物和代码模板
- 包含端到端示例和常见陷阱规避指南
Highlights
- 工具版本明确指定,避免兼容性问题
- 关键配置项(如connect数组)有强调说明
- API抽象层设计合理,支持多种请求模式
- UI层z-index和拖拽逻辑有详细实现指导
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
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.
User discussion
No verified reviews yet.