react-grab
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesereact-grab — Browser Element Context for AI Agents
react-grab — 面向AI Agent的浏览器元素上下文获取工具
Keyword:·react-grab·grab·element contextcopy component to aiPoint at any UI element in your browser, press Cmd/Ctrl+C, and instantly copy its React component name, source file path, and HTML markup to clipboard — ready for your AI coding agent.
关键词:·react-grab·grab·element contextcopy component to ai指向浏览器中的任意UI元素,按下Cmd/Ctrl+C,即可立即将其React组件名称、源文件路径和HTML标记复制到剪贴板——随时可以提供给你的AI编码Agent使用。
When to use this skill
适用场景
- Set up react-grab in a React project (Next.js, Vite, Webpack) for AI-assisted development
- Point at UI elements and copy precise component context to Claude Code / Cursor / Copilot / Gemini
- Add react-grab MCP server so your AI agent can receive element context programmatically
- Configure react-grab with a custom plugin for project-specific workflows (Jira, Figma, etc.)
- Use the programmatic API (,
getElementContext) for automation or test toolingfreeze - Remove react-grab from a project or a specific agent integration
- 在React项目(Next.js、Vite、Webpack)中配置react-grab,用于AI辅助开发
- 指向UI元素,复制精准的组件上下文到Claude Code / Cursor / Copilot / Gemini
- 配置react-grab MCP服务端,让你的AI Agent可以程序化获取元素上下文
- 通过自定义插件配置react-grab,适配项目专属工作流(Jira、Figma等)
- 使用程序化API(、
getElementContext)实现自动化或测试工具能力freeze - 从项目或特定Agent集成中移除react-grab
Instructions
使用说明
- Run (or
bash scripts/install.sh) to install react-grab in your projectnpx -y grab@latest init - Start your dev server — react-grab is dev-only and never ships to production
- Open your app in a browser, hover over any element, and press Cmd+C (Mac) / Ctrl+C (Win)
- Paste the clipboard content into your AI coding agent (Claude Code / Cursor / Copilot / Gemini)
- Optionally run to enable MCP tool access for programmatic use
bash scripts/add-agent.sh mcp
For detailed API and framework-specific setup, see references/api.md.
- 执行 (或
bash scripts/install.sh)在你的项目中安装react-grabnpx -y grab@latest init - 启动开发服务端——react-grab仅用于开发环境,永远不会被打包到生产版本
- 在浏览器中打开你的应用, hover 任意元素,按下 Cmd+C(Mac)/ Ctrl+C(Windows)
- 将剪贴板内容粘贴到你的AI编码Agent(Claude Code / Cursor / Copilot / Gemini)中即可
- 可选执行 开启MCP工具访问权限,用于程序化调用
bash scripts/add-agent.sh mcp
如需查看完整API和框架专属配置指南,请参考 references/api.md。
Examples
示例
Copy element context to Claude Code
复制元素上下文到Claude Code
undefinedundefined1. Start your app
1. 启动你的应用
npm run dev
npm run dev
2. Hover over a button in the browser
2. 在浏览器中 hover 某个按钮
3. Press Cmd+C (Mac) or Ctrl+C (Win/Linux)
3. 按下 Cmd+C(Mac)或 Ctrl+C(Win/Linux)
Clipboard now contains:
剪贴板现在包含以下内容:
in LoginForm at components/login-form.tsx:46:19
in LoginForm at components/login-form.tsx:46:19
<button class="btn-primary" type="submit">
<button class="btn-primary" type="submit">
Log in
Log in
</button>
</button>
4. Paste into Claude Code — it knows exactly where the component lives
4. 粘贴到Claude Code中——它会精准识别组件的位置
undefinedundefinedSet up MCP integration
配置MCP集成
bash
undefinedbash
undefinedInstall react-grab MCP server
安装react-grab MCP服务端
npx -y grab@latest add mcp
npx -y grab@latest add mcp
Your AI agent can now call the get_element_context MCP tool
你在浏览器中选中元素后,AI Agent就可以调用get_element_context MCP工具
to receive element context after you select it in the browser
获取对应的元素上下文
undefinedundefinedAdd custom plugin action
添加自定义插件动作
ts
import { registerPlugin } from "react-grab";
registerPlugin({
name: "open-in-figma",
actions: [{
id: "figma",
label: "Find in Figma",
shortcut: "F",
onAction: (ctx) => {
window.open(`figma://search?q=${ctx.componentName}`);
},
}],
});ts
import { registerPlugin } from "react-grab";
registerPlugin({
name: "open-in-figma",
actions: [{
id: "figma",
label: "Find in Figma",
shortcut: "F",
onAction: (ctx) => {
window.open(`figma://search?q=${ctx.componentName}`);
},
}],
});Quick Start
快速开始
bash
undefinedbash
undefinedOne command — auto-detects your framework and installs everything
一键命令——自动识别你的框架并安装所有依赖
npx -y grab@latest init
npx -y grab@latest init
Add MCP server for programmatic AI agent access
添加MCP服务端,支持AI Agent程序化访问
npx -y grab@latest add mcp
npx -y grab@latest add mcp
Add to a specific AI agent
添加到特定AI Agent
npx -y grab@latest add claude-code
After installation, hover over any element in your browser during development and press:
- **Mac**: `Cmd+C`
- **Windows/Linux**: `Ctrl+C`
Output copied to clipboard:in LoginForm at components/login-form.tsx:46:19
<a class="ml-auto text-sm underline-offset-4 hover:underline">
Forgot your password?
</a>
```
Paste directly into your AI coding agent prompt — no file searching needed.
npx -y grab@latest add claude-code
安装完成后,开发过程中在浏览器里hover任意元素,按下对应快捷键即可:
- **Mac**: `Cmd+C`
- **Windows/Linux**: `Ctrl+C`
复制到剪贴板的输出格式:in LoginForm at components/login-form.tsx:46:19
<a class="ml-auto text-sm underline-offset-4 hover:underline">
Forgot your password?
</a>
```
直接粘贴到你的AI编码Agent提示词中即可——无需手动查找文件。
Installation
安装指南
Auto-detect (Recommended)
自动识别安装(推荐)
bash
npx -y grab@latest initDetects your framework (Next.js App Router / Pages Router / Vite / TanStack Start / Webpack)
and package manager (npm / yarn / pnpm / bun) automatically.
bash
npx -y grab@latest init自动识别你的框架(Next.js App Router / Pages Router / Vite / TanStack Start / Webpack)和包管理器(npm / yarn / pnpm / bun)。
Manual installation by framework
按框架手动安装
Next.js App Router ():
app/layout.tsxtsx
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
{process.env.NODE_ENV === "development" && (
<Script
src="//unpkg.com/react-grab/dist/index.global.js"
crossOrigin="anonymous"
strategy="beforeInteractive"
/>
)}
</body>
</html>
)
}Next.js Pages Router ():
pages/_document.tsxtsx
import Script from 'next/script'
// Inside _document component:
{process.env.NODE_ENV === "development" && (
<Script
src="//unpkg.com/react-grab/dist/index.global.js"
crossOrigin="anonymous"
strategy="beforeInteractive"
/>
)}Vite ():
index.htmlhtml
<script type="module">
if (import.meta.env.DEV) {
await import('//unpkg.com/react-grab/dist/index.global.js');
}
</script>Webpack (entry file):
js
if (process.env.NODE_ENV === 'development') {
import('react-grab');
}Package install (for programmatic use):
bash
npm install react-grabNext.js App Router ():
app/layout.tsxtsx
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
{process.env.NODE_ENV === "development" && (
<Script
src="//unpkg.com/react-grab/dist/index.global.js"
crossOrigin="anonymous"
strategy="beforeInteractive"
/>
)}
</body>
</html>
)
}Next.js Pages Router ():
pages/_document.tsxtsx
import Script from 'next/script'
// 在_document组件内部:
{process.env.NODE_ENV === "development" && (
<Script
src="//unpkg.com/react-grab/dist/index.global.js"
crossOrigin="anonymous"
strategy="beforeInteractive"
/>
)}Vite ():
index.htmlhtml
<script type="module">
if (import.meta.env.DEV) {
await import('//unpkg.com/react-grab/dist/index.global.js');
}
</script>Webpack (入口文件):
js
if (process.env.NODE_ENV === 'development') {
import('react-grab');
}包安装(用于程序化调用):
bash
npm install react-grabor: pnpm add react-grab | yarn add react-grab | bun add react-grab
或: pnpm add react-grab | yarn add react-grab | bun add react-grab
undefinedundefinedInstall react-grab via skill scripts
通过技能脚本安装react-grab
bash
undefinedbash
undefinedAuto-detect framework and install
自动识别框架并安装
bash scripts/install.sh
bash scripts/install.sh
Install for a specific framework
针对指定框架安装
bash scripts/install.sh --framework next-app
bash scripts/install.sh --framework next-app
Add to a specific AI agent
添加到指定AI Agent
bash scripts/add-agent.sh claude-code
bash scripts/add-agent.sh cursor
bash scripts/add-agent.sh mcp
---bash scripts/add-agent.sh claude-code
bash scripts/add-agent.sh cursor
bash scripts/add-agent.sh mcp
---Core Usage
核心用法
Keyboard shortcut
快捷键使用
In development mode:
- Hover over any React element in the browser
- Press Cmd+C (Mac) or Ctrl+C (Windows/Linux)
- The context is copied to clipboard
Output format:
in <ComponentName> at <file-path>:<line>:<col>
<element-html>在开发模式下:
- 在浏览器中hover任意React元素
- 按下 Cmd+C(Mac)或 Ctrl+C(Windows/Linux)
- 上下文会被复制到剪贴板
输出格式:
in <ComponentName> at <file-path>:<line>:<col>
<element-html>Floating toolbar
浮动工具栏
A draggable toolbar appears in the corner of your browser when react-grab is active:
- Click to toggle activation on/off
- Drag to any screen edge
- Collapse when not needed
react-grab激活时,浏览器角落会出现可拖拽的工具栏:
- 点击可切换激活/关闭状态
- 可拖拽到任意屏幕边缘
- 不需要时可收起
Multi-element selection (drag)
多元素选择(拖拽)
Click and drag across multiple elements to capture all their contexts at once. Each element's
component stack and HTML is included in the clipboard output.
点击并拖拽选中多个元素,即可一次性捕获所有元素的上下文。剪贴板输出会包含每个元素的组件栈和HTML。
Programmatic API
程序化API
ts
import { getGlobalApi } from "react-grab";
const api = getGlobalApi();
// Activate the overlay
api.activate(); // show overlay
api.deactivate(); // hide overlay
api.toggle(); // toggle
// Copy an element's context to clipboard
await api.copyElement(document.querySelector('.my-button'));
// Get source info without copying
const source = await api.getSource(element);
console.log(source.filePath); // "src/components/Button.tsx"
console.log(source.lineNumber); // 42
console.log(source.componentName); // "Button"
// Get the full stack context string
const stack = await api.getStackContext(element);
// "in Button (at Button.tsx:42:5)\n in Card (at Card.tsx:10:3)"
// Check current state
const state = api.getState();
// { isActive, isDragging, isCopying, targetElement, ... }ts
import { getGlobalApi } from "react-grab";
const api = getGlobalApi();
// 激活浮层
api.activate(); // 显示浮层
api.deactivate(); // 隐藏浮层
api.toggle(); // 切换状态
// 复制元素上下文到剪贴板
await api.copyElement(document.querySelector('.my-button'));
// 仅获取源文件信息,不复制
const source = await api.getSource(element);
console.log(source.filePath); // "src/components/Button.tsx"
console.log(source.lineNumber); // 42
console.log(source.componentName); // "Button"
// 获取完整栈上下文字符串
const stack = await api.getStackContext(element);
// "in Button (at Button.tsx:42:5)\n in Card (at Card.tsx:10:3)"
// 查看当前状态
const state = api.getState();
// { isActive, isDragging, isCopying, targetElement, ... }Primitives API (standalone usage)
基础API(独立使用)
Use without the default overlay UI — for automation, test tooling, or custom integrations:
ts
import { getElementContext, freeze, unfreeze, openFile } from "react-grab/primitives";
// or: import { getElementContext } from "react-grab/core";
const button = document.querySelector('.submit-btn');
// Freeze page state (pause React updates, CSS animations, preserve :hover/:focus)
freeze();
// Get all context for an element
const context = await getElementContext(button);
console.log(context.componentName); // "SubmitButton"
console.log(context.selector); // "button.submit-btn"
console.log(context.stackString); // "in SubmitButton (at Button.tsx:12:5)"
console.log(context.htmlPreview); // "<button class=\"submit-btn\">Submit</button>"
console.log(context.styles); // Relevant computed CSS
unfreeze(); // Restore normal page behavior
// Open the source file in editor
await openFile("/src/components/Button.tsx", 12);无需使用默认浮层UI即可调用,可用于自动化、测试工具或自定义集成:
ts
import { getElementContext, freeze, unfreeze, openFile } from "react-grab/primitives";
// 或: import { getElementContext } from "react-grab/core";
const button = document.querySelector('.submit-btn');
// 冻结页面状态(暂停React更新、CSS动画,保留:hover/:focus状态)
freeze();
// 获取元素的所有上下文
const context = await getElementContext(button);
console.log(context.componentName); // "SubmitButton"
console.log(context.selector); // "button.submit-btn"
console.log(context.stackString); // "in SubmitButton (at Button.tsx:12:5)"
console.log(context.htmlPreview); // "<button class=\"submit-btn\">Submit</button>"
console.log(context.styles); // 相关的计算后CSS属性
unfreeze(); // 恢复页面正常行为
// 在编辑器中打开源文件
await openFile("/src/components/Button.tsx", 12);MCP Integration
MCP集成
react-grab ships an MCP server () for programmatic AI agent access:
@react-grab/mcpbash
undefinedreact-grab内置MCP服务端(),支持AI Agent程序化访问:
@react-grab/mcpbash
undefinedAdd MCP server
添加MCP服务端
npx -y grab@latest add mcp
The MCP server exposes a `get_element_context` tool that returns the most recent element
selection from the browser overlay. Your AI agent calls this tool to receive the context
that you selected in the browser.
**Flow:**
1. You hover over element in browser → react-grab captures context
2. AI agent calls `get_element_context` MCP tool
3. Agent receives: component name, file path, line number, HTML markup
4. Agent makes precise code changes without file searching
---npx -y grab@latest add mcp
MCP服务端暴露了`get_element_context`工具,会返回最近一次在浏览器浮层中选中的元素信息。你的AI Agent可以调用该工具获取你在浏览器中选中的上下文。
**流程:**
1. 你在浏览器中hover元素 → react-grab捕获上下文
2. AI Agent调用`get_element_context` MCP工具
3. Agent收到:组件名称、文件路径、行号、HTML标记
4. Agent无需查找文件即可做出精准的代码修改
---AI Agent Integration
AI Agent集成
Add react-grab to your specific AI coding agent:
bash
npx -y grab@latest add claude-code # Claude Code
npx -y grab@latest add cursor # Cursor
npx -y grab@latest add copilot # GitHub Copilot
npx -y grab@latest add codex # OpenAI Codex
npx -y grab@latest add gemini # Google Gemini CLI
npx -y grab@latest add opencode # OpenCode
npx -y grab@latest add amp # Amp
npx -y grab@latest add droid # DroidRemove an integration:
bash
npx -y grab@latest remove cursor将react-grab添加到你使用的特定AI编码Agent:
bash
npx -y grab@latest add claude-code # Claude Code
npx -y grab@latest add cursor # Cursor
npx -y grab@latest add copilot # GitHub Copilot
npx -y grab@latest add codex # OpenAI Codex
npx -y grab@latest add gemini # Google Gemini CLI
npx -y grab@latest add opencode # OpenCode
npx -y grab@latest add amp # Amp
npx -y grab@latest add droid # Droid移除集成:
bash
npx -y grab@latest remove cursorPlugin System
插件系统
Extend react-grab with custom context menu actions, toolbar buttons, and lifecycle hooks:
ts
import { registerPlugin } from "react-grab";
registerPlugin({
name: "send-to-jira",
hooks: {
// Add annotation to clipboard content
transformCopyContent: async (content, elements) => {
return content + "\n// Sent from react-grab";
},
// Custom file-open behavior
onOpenFile: (filePath, lineNumber) => {
// Return true if handled; false to use default behavior
return false;
},
},
actions: [
{
id: "jira-action",
label: "Create Jira Ticket",
shortcut: "J",
onAction: async (context) => {
await createJiraTicket({
filePath: context.filePath,
componentName: context.componentName,
html: context.element.outerHTML,
});
context.hideContextMenu();
},
},
{
id: "toolbar-inspect",
label: "Inspect",
target: "toolbar", // Places in toolbar instead of context menu
onAction: () => {
console.log("Inspect triggered");
},
},
],
theme: {
hue: 200, // Change overlay color (0-360 HSL)
crosshair: { enabled: false }, // Disable crosshair overlay
},
});通过自定义上下文菜单动作、工具栏按钮和生命周期钩子扩展react-grab能力:
ts
import { registerPlugin } from "react-grab";
registerPlugin({
name: "send-to-jira",
hooks: {
// 为剪贴板内容添加注释
transformCopyContent: async (content, elements) => {
return content + "\n// Sent from react-grab";
},
// 自定义文件打开行为
onOpenFile: (filePath, lineNumber) => {
// 如果已处理返回true;返回false则使用默认行为
return false;
},
},
actions: [
{
id: "jira-action",
label: "Create Jira Ticket",
shortcut: "J",
onAction: async (context) => {
await createJiraTicket({
filePath: context.filePath,
componentName: context.componentName,
html: context.element.outerHTML,
});
context.hideContextMenu();
},
},
{
id: "toolbar-inspect",
label: "Inspect",
target: "toolbar", // 放置在工具栏而非上下文菜单
onAction: () => {
console.log("Inspect triggered");
},
},
],
theme: {
hue: 200, // 修改浮层颜色(0-360 HSL)
crosshair: { enabled: false }, // 关闭十字准星浮层
},
});Available plugin hooks
可用插件钩子
ts
hooks: {
onActivate?: () => void
onDeactivate?: () => void
onElementHover?: (element: Element) => void
onElementSelect?: (element: Element) => boolean | void // return true to cancel default
onBeforeCopy?: (elements: Element[]) => void
transformCopyContent?: (content: string, elements: Element[]) => string | Promise<string>
onAfterCopy?: (elements: Element[], success: boolean) => void
onOpenFile?: (filePath: string, lineNumber?: number) => boolean | void
transformHtmlContent?: (html: string, elements: Element[]) => string | Promise<string>
transformAgentContext?: (ctx: AgentContext, elements: Element[]) => AgentContext
transformSnippet?: (snippet: string, element: Element) => string | Promise<string>
}ts
hooks: {
onActivate?: () => void
onDeactivate?: () => void
onElementHover?: (element: Element) => void
onElementSelect?: (element: Element) => boolean | void // 返回true可取消默认行为
onBeforeCopy?: (elements: Element[]) => void
transformCopyContent?: (content: string, elements: Element[]) => string | Promise<string>
onAfterCopy?: (elements: Element[], success: boolean) => void
onOpenFile?: (filePath: string, lineNumber?: number) => boolean | void
transformHtmlContent?: (html: string, elements: Element[]) => string | Promise<string>
transformAgentContext?: (ctx: AgentContext, elements: Element[]) => AgentContext
transformSnippet?: (snippet: string, element: Element) => string | Promise<string>
}CLI Reference
CLI参考
bash
grab [command] [options]
Commands:
init Auto-detect project and install react-grab
add Connect react-grab to an AI coding agent (alias: install)
remove Disconnect from an AI coding agent
configure Configure options (activation key, context lines, etc.)
Options:
-y, --yes Skip confirmation prompts
-c, --cwd Working directory (default: process.cwd())
-v, --version Display version
-h, --help Display helpbash
grab [command] [options]
Commands:
init 自动识别项目并安装react-grab
add 将react-grab连接到AI编码Agent(别名:install)
remove 断开与AI编码Agent的连接
configure 配置选项(激活按键、上下文行数等)
Options:
-y, --yes 跳过确认提示
-c, --cwd 工作目录(默认:process.cwd())
-v, --version 显示版本号
-h, --help 显示帮助信息Configuration
配置
Pass options to for programmatic control (when not using the CDN script):
init()ts
import { init } from "react-grab";
init({
enabled: true, // Enable/disable entirely
activationMode: "toggle", // "toggle" | "hold"
activationKey: "c", // Key to press (with Cmd/Ctrl)
maxContextLines: 10, // Limit React component stack depth
freezeReactUpdates: true, // Pause React state while active
getContent: async (elements) => { // Custom clipboard content formatter
const contexts = await generateSnippet(elements);
return contexts.join("\n---\n");
},
});Disable entirely (before script loads):
js
window.__REACT_GRAB_DISABLED__ = true;调用时传入参数实现程序化控制(不使用CDN脚本时适用):
init()ts
import { init } from "react-grab";
init({
enabled: true, // 全局开启/关闭
activationMode: "toggle", // "toggle" | "hold"
activationKey: "c", // 触发按键(需搭配Cmd/Ctrl)
maxContextLines: 10, // 限制React组件栈深度
freezeReactUpdates: true, // 激活时暂停React状态更新
getContent: async (elements) => { // 自定义剪贴板内容格式化器
const contexts = await generateSnippet(elements);
return contexts.join("\n---\n");
},
});全局关闭(脚本加载前设置):
js
window.__REACT_GRAB_DISABLED__ = true;Best practices
最佳实践
- Dev-only: react-grab is designed for development only. Always wrap in or
NODE_ENV === "development".import.meta.env.DEV - Use command:
inithandles framework detection — don't manually add script tags unless needed.npx -y grab@latest init - MCP for agents: For AI-driven workflows, add the MCP server with so agents can pull context without clipboard dependencies.
grab add mcp - Plugin for teams: Create a shared plugin to standardize element context format across your team (e.g., always include JIRA project prefix).
- Freeze for inspection: Use from the primitives API when you need to inspect dynamic elements that disappear on hover.
freeze()
- 仅用于开发环境: react-grab仅为开发场景设计,务必使用或
NODE_ENV === "development"包裹引入代码。import.meta.env.DEV - 优先使用命令:
init会自动处理框架识别,除非必要否则无需手动添加script标签。npx -y grab@latest init - Agent场景使用MCP: 对于AI驱动的工作流,通过添加MCP服务端,让Agent无需依赖剪贴板即可拉取上下文。
grab add mcp - 团队场景使用插件: 创建共享插件,统一团队内的元素上下文格式(例如始终包含JIRA项目前缀)。
- 检查动态元素使用冻结: 当你需要检查hover时会消失的动态元素时,可调用基础API中的方法。
freeze()
Troubleshooting
问题排查
| Issue | Solution |
|---|---|
| Overlay not appearing | Check |
Component name shows as | Ensure |
| File path missing | Requires React source maps enabled (dev mode only; not minified builds) |
| MCP tool returns empty | You need to select an element in the browser first before calling |
| Check Node.js >=18 and package manager (npm/pnpm/yarn/bun) is installed |
| 问题 | 解决方案 |
|---|---|
| 浮层不显示 | 检查是否用 |
组件名称显示为 | 确保 |
| 文件路径缺失 | 需要开启React source map(仅开发模式生效,压缩构建版本不支持) |
| MCP工具返回空内容 | 调用 |
| 检查Node.js版本>=18,且已安装包管理器(npm/pnpm/yarn/bun) |
References
参考资料
- react-grab GitHub — source code and issues
- react-grab.com — official documentation
- Full API Reference — complete TypeScript API docs
- Install Scripts — (project setup) ·
install.sh(agent integration)add-agent.sh
- react-grab GitHub — 源码和issue反馈
- react-grab.com — 官方文档
- 完整API参考 — 完整TypeScript API文档
- 安装脚本 — (项目配置)·
install.sh(Agent集成)add-agent.sh