tampermonkey-dev

指导使用 Vite + Vue 3 + vite-plugin-monkey 开发 Tampermonkey 用户脚本。用于在现有网页注入功能(如浮动面板、按钮、数据提取、页面跨域请求),或构建浏览器端辅助工具、页面增强插件与嵌入目标页面的抓取 UI。当用户提及 Tampermonkey、用户脚本、GreasyFork、猴子脚本,或表示“在网站 X 添加按钮”“从页面 Y 读取数据”时触发此技能以判断并指导采用用户脚本方案。

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "tampermonkey-dev":https://skillpi.com/zh/skills/deepskill-42450b1d82af7becce002803a0717a7b5743b440fa10e21e40a40872325e728c。安装前核对上游来源和版本:https://skillhub.cn/skills/user_d83dc1a5/kkluvvs-002。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

skillhub.cn

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

指导使用 Vite + Vue 3 + vite-plugin-monkey 开发 Tampermonkey 用户脚本。用于在现有网页注入功能(如浮动面板、按钮、数据提取、页面跨域请求),或构建浏览器端辅助工具、页面增强插件与嵌入目标页面的抓取 UI。当用户提及 Tampermonkey、用户脚本、GreasyFork、猴子脚本,或表示“在网站 X 添加按钮”“从页面 Y 读取数据”时触发此技能以判断并指导采用用户脚本方案。

0 下载

介绍来源: third_party · user_d83dc1a5 · 1.0.0 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
适合谁
来源文档未说明。
输入和输出
翻译待完成,请参阅来源文档。
软件、账号及付费要求
来源文档未说明。
限制与区别
来源文档未说明。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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.

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

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

待提升项

  • 触发词覆盖范围 原报告严重程度:轻微

    描述中重复了frontmatter的description内容

    改进建议:移除skill_body中重复的description段落以避免冗余

亮点

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

亮点

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

亮点

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

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

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

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

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

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

来源文档未说明。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。