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仅用于开发环境,不会打包到生产环境
- 在浏览器中打开应用,悬停在任意元素上,按下 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. 在浏览器中悬停在一个按钮上
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: "在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
安装完成后,在开发过程中悬停在浏览器中的任意元素上,按下:
- **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
通过技能脚本安装
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>在开发模式下:
- 在浏览器中悬停在任意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. 你在浏览器中悬停在元素上→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// 来自react-grab";
},
// 自定义文件打开行为
onOpenFile: (filePath, lineNumber) => {
// 若已处理返回true;返回false则使用默认行为
return false;
},
},
actions: [
{
id: "jira-action",
label: "创建Jira工单",
shortcut: "J",
onAction: async (context) => {
await createJiraTicket({
filePath: context.filePath,
componentName: context.componentName,
html: context.element.outerHTML,
});
context.hideContextMenu();
},
},
{
id: "toolbar-inspect",
label: "检查",
target: "toolbar", // 放置在工具栏而非右键菜单
onAction: () => {
console.log("触发检查操作");
},
},
],
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]
命令:
init 自动检测项目并安装react-grab
add 将react-grab连接到AI编码Agent(别名:install)
remove 断开与AI编码Agent的连接
configure 配置选项(激活键、上下文行数等)
选项:
-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命令:会自动检测框架——除非必要,不要手动添加脚本标签。
npx -y grab@latest init - Agent使用MCP:对于AI驱动的工作流,使用添加MCP服务器,让Agent无需依赖剪贴板即可获取上下文。
grab add mcp - 团队共享插件:创建共享插件,标准化团队内的元素上下文格式(例如,始终包含JIRA项目前缀)。
- 冻结状态用于检查:当需要检查悬停时会消失的动态元素时,使用原语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源映射(仅开发模式;非压缩构建) |
| 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 — 源代码和问题反馈
- react-grab.com — 官方文档
- 完整API参考 — 完整TypeScript API文档
- 安装脚本 — (项目设置)·
install.sh(Agent集成)add-agent.sh