Chrome 扩展 Manifest V3 门槛不低。有了 Claude Code,3 小时完成传统 2-4 天的工作。
项目目标
一个网页阅读 AI 助手 Chrome 扩展:
- 点击扩展图标显示当前页面 AI 摘要
- 选中文字右键菜单 AI 解释
- 快捷键 Ctrl+Shift+S 触发摘要
技术栈:Manifest V3 + TypeScript + Claude API
Step 1:规划项目结构
bash
mkdir chrome-reader && cd chrome-reader
claude输入任务(用英文避免特殊字符问题):
I want to build a Chrome Extension with MV3. Features:
1. Popup shows AI summary of current page
2. Right-click context menu AI Explain on selected text
3. Keyboard shortcut Ctrl+Shift+S triggers summary
Plan the project structure and explain MV3 constraints.
Step 2:初始化项目
Create project structure:
chrome-reader/
manifest.json
src/
background.ts (Service Worker)
content.ts (Content Script)
popup/popup.html + popup.ts
icons/icon128.png
tsconfig.json
Install: typescript, @types/chrome
Configure tsconfig.json output to dist/
Step 3:实现 manifest.json
Generate manifest.json:
- Name: AI Reader Assistant, Version 1.0.0, MV3
- Permissions: activeTab, contextMenus, storage, scripting
- host_permissions: api.anthropic.com
- Background Service Worker: dist/background.js
- Content Script injected to all pages
- Command Ctrl+Shift+S triggers summarize
Step 4:实现 background.ts
Implement background.ts:
1. Register context menu AI Explain on install
2. On context menu click: call Claude API (claude-haiku-3-5), show result via Content Script
3. On shortcut: get page body, call API for summary, show via Content Script
4. Read API Key from chrome.storage.sync
Use fetch() not SDK. API calls in Service Worker only.
Step 5:实现 Popup 和 Content Script
Popup:
- API Key input (save to chrome.storage.sync)
- Summarize button
- Result area with loading state
Content Script:
- Listen for show_result message from background
- Show floating card at bottom-right
- Use Shadow DOM to isolate styles
Step 6:构建和测试
bash
npm run build # tsc + copy assets to dist/加载测试:chrome://extensions/ -> 开发者模式 -> 加载已解压的扩展,选 dist/
Step 7:排查 MV3 常见坑
Check for MV3 issues:
1. Service Worker cannot use XMLHttpRequest (use fetch)
2. Service Worker cannot access DOM
3. CSP allows external API calls
4. host_permissions correctly declared for api.anthropic.com
5. Cross-origin requests in Service Worker not Content Script
时效对比
| 步骤 | 传统方式 | Claude Code |
|---|---|---|
| 规划和结构 | 2-3 小时 | 15 分钟 |
| manifest.json | 1-2 小时(踩坑) | 5 分钟 |
| 核心功能实现 | 1-2 天 | 1-2 小时 |
| 调试和修复 | 半天 | 30 分钟 |
| 总计 | 2-4 天 | ~3 小时 |
三个关键经验
1. 提前声明 MV3 限制:告诉 Claude use Manifest V3 be careful of all limitations,帮你避开 Service Worker 坑。
2. 贴完整错误信息:Service Worker 错误在 chrome://extensions/ 查,Content Script 错误在页面 DevTools 里看。
3. 权限最小化:Chrome Web Store 审核检查权限最小化,让 Claude 帮你删除不必要的权限。
来源:Anthropic 官方文档 + Chrome Extensions Developer Guide