chrome-extension
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChrome Extension Best Practices
Chrome扩展程序最佳实践
Comprehensive performance and code quality guide for Chrome Extensions (Manifest V3). Contains 67 rules across 12 categories, prioritized by impact to guide automated refactoring and code generation.
针对Chrome扩展程序(Manifest V3)的全面性能与代码质量指南。包含12个分类下的67条规则,按影响优先级排序,可指导自动化重构与代码生成。
When to Apply
适用场景
Reference these guidelines when:
- Writing new Chrome extension code
- Migrating from Manifest V2 to Manifest V3
- Optimizing service worker lifecycle and state management
- Implementing content scripts for page interaction
- Debugging performance issues in extensions
在以下场景中参考本指南:
- 编写新的Chrome扩展代码
- 从Manifest V2迁移至Manifest V3
- 优化service worker生命周期与状态管理
- 实现用于页面交互的内容脚本
- 调试扩展程序中的性能问题
Rule Categories by Priority
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Service Worker Lifecycle | CRITICAL | |
| 2 | Content Script Optimization | CRITICAL | |
| 3 | Message Passing Efficiency | HIGH | |
| 4 | Storage Operations | HIGH | |
| 5 | Network & Permissions | MEDIUM-HIGH | |
| 6 | Memory Management | MEDIUM | |
| 7 | UI Performance | MEDIUM | |
| 8 | API Usage Patterns | LOW-MEDIUM | |
| 9 | Code Style & Naming | MEDIUM | |
| 10 | Component Patterns | MEDIUM | |
| 11 | Error Handling | HIGH | |
| 12 | Testing Patterns | MEDIUM | |
| 优先级 | 分类 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | Service Worker生命周期 | 关键 | |
| 2 | 内容脚本优化 | 关键 | |
| 3 | 消息传递效率 | 高 | |
| 4 | 存储操作 | 高 | |
| 5 | 网络与权限 | 中高 | |
| 6 | 内存管理 | 中 | |
| 7 | UI性能 | 中 | |
| 8 | API使用模式 | 中低 | |
| 9 | 代码风格与命名 | 中 | |
| 10 | 组件模式 | 中 | |
| 11 | 错误处理 | 高 | |
| 12 | 测试模式 | 中 | |
Quick Reference
快速参考
1. Service Worker Lifecycle (CRITICAL)
1. Service Worker生命周期(关键)
- - Persist state with chrome.storage instead of global variables
sw-persist-state-storage - - Avoid artificial service worker keep-alive patterns
sw-avoid-keepalive - - Use chrome.alarms instead of setTimeout/setInterval
sw-use-alarms-api - - Return true from message listeners for async responses
sw-return-true-async - - Register event listeners at top level
sw-register-listeners-toplevel - - Use offscreen documents for DOM APIs
sw-use-offscreen-for-dom
- - 使用chrome.storage而非全局变量持久化状态
sw-persist-state-storage - - 避免人工维持service worker存活的模式
sw-avoid-keepalive - - 使用chrome.alarms替代setTimeout/setInterval
sw-use-alarms-api - - 异步响应时从消息监听器返回true
sw-return-true-async - - 在顶层注册事件监听器
sw-register-listeners-toplevel - - 使用离屏文档处理DOM API
sw-use-offscreen-for-dom
2. Content Script Optimization (CRITICAL)
2. 内容脚本优化(关键)
- - Use specific URL match patterns
content-use-specific-matches - - Use document_idle for content script injection
content-use-document-idle - - Prefer programmatic injection over manifest declaration
content-programmatic-injection - - Minimize content script bundle size
content-minimize-script-size - - Batch DOM operations to minimize reflows
content-batch-dom-operations - - Use MutationObserver instead of polling
content-use-mutation-observer
- - 使用特定的URL匹配模式
content-use-specific-matches - - 使用document_idle时机注入内容脚本
content-use-document-idle - - 优先使用程序化注入而非清单声明
content-programmatic-injection - - 最小化内容脚本包体积
content-minimize-script-size - - 批量处理DOM操作以减少重排
content-batch-dom-operations - - 使用MutationObserver替代轮询
content-use-mutation-observer
3. Message Passing Efficiency (HIGH)
3. 消息传递效率(高)
- - Use port connections for frequent message exchange
msg-use-ports-for-frequent - - Minimize message payload size
msg-minimize-payload-size - - Debounce high-frequency events before messaging
msg-debounce-frequent-events - - Always check chrome.runtime.lastError
msg-check-lasterror - - Avoid broadcasting messages to all tabs
msg-avoid-broadcast-to-all-tabs
- - 使用端口连接处理频繁的消息交互
msg-use-ports-for-frequent - - 最小化消息负载体积
msg-minimize-payload-size - - 在发送消息前防抖高频事件
msg-debounce-frequent-events - - 始终检查chrome.runtime.lastError
msg-check-lasterror - - 避免向所有标签页广播消息
msg-avoid-broadcast-to-all-tabs
4. Storage Operations (HIGH)
4. 存储操作(高)
- - Batch storage operations instead of individual calls
storage-batch-operations - - Choose the correct storage type for your use case
storage-choose-correct-type - - Cache frequently accessed storage values
storage-cache-frequently-accessed - - Use storage.session for temporary runtime data
storage-use-session-for-temp - - Avoid storing large binary blobs
storage-avoid-storing-large-blobs
- - 批量执行存储操作而非单独调用
storage-batch-operations - - 根据使用场景选择正确的存储类型
storage-choose-correct-type - - 缓存频繁访问的存储值
storage-cache-frequently-accessed - - 使用storage.session存储临时运行时数据
storage-use-session-for-temp - - 避免存储大型二进制Blob
storage-avoid-storing-large-blobs
5. Network & Permissions (MEDIUM-HIGH)
5. 网络与权限(中高)
- - Use declarativeNetRequest instead of webRequest
net-use-declarativenetrequest - - Request minimal required permissions
net-request-minimal-permissions - - Use activeTab permission instead of broad host permissions
net-use-activetab - - Avoid modifying Content Security Policy headers
net-limit-csp-modifications
- - 使用declarativeNetRequest替代webRequest
net-use-declarativenetrequest - - 请求最小必要权限
net-request-minimal-permissions - - 使用activeTab权限而非宽泛的主机权限
net-use-activetab - - 避免修改内容安全策略(CSP)头
net-limit-csp-modifications
6. Memory Management (MEDIUM)
6. 内存管理(中)
- - Clean up event listeners when content script unloads
mem-cleanup-event-listeners - - Avoid holding references to detached DOM nodes
mem-avoid-detached-dom - - Avoid accidental closure memory leaks
mem-avoid-closure-leaks - - Clear intervals and timeouts on cleanup
mem-clear-intervals-timeouts - - Use WeakMap and WeakSet for DOM element references
mem-use-weak-collections
- - 内容脚本卸载时清理事件监听器
mem-cleanup-event-listeners - - 避免持有已分离DOM节点的引用
mem-avoid-detached-dom - - 避免意外的闭包内存泄漏
mem-avoid-closure-leaks - - 清理时清除定时器与间隔任务
mem-clear-intervals-timeouts - - 使用WeakMap和WeakSet存储DOM元素引用
mem-use-weak-collections
7. UI Performance (MEDIUM)
7. UI性能(中)
- - Minimize popup bundle size for fast startup
ui-minimize-popup-bundle - - Render popup UI with cached data first
ui-render-with-cached-data - - Batch badge updates to avoid flicker
ui-batch-badge-updates - - Lazy load options page sections
ui-use-options-page-lazy
- - 最小化弹窗包体积以实现快速启动
ui-minimize-popup-bundle - - 优先使用缓存数据渲染弹窗UI
ui-render-with-cached-data - - 批量更新徽章以避免闪烁
ui-batch-badge-updates - - 懒加载选项页的各个板块
ui-use-options-page-lazy
8. API Usage Patterns (LOW-MEDIUM)
8. API使用模式(中低)
- - Use promise-based API calls over callbacks
api-use-promises-over-callbacks - - Query tabs with specific filters
api-query-tabs-efficiently - - Avoid redundant API calls in loops
api-avoid-redundant-api-calls - - Respect alarms API minimum period
api-use-alarms-minperiod - - Handle extension context invalidated errors
api-handle-context-invalidated - - Use declarative content API for page actions
api-use-declarative-content
- - 优先使用基于Promise的API调用而非回调函数
api-use-promises-over-callbacks - - 使用特定过滤器查询标签页
api-query-tabs-efficiently - - 避免在循环中进行重复的API调用
api-avoid-redundant-api-calls - - 遵守alarms API的最小周期限制
api-use-alarms-minperiod - - 处理扩展上下文失效错误
api-handle-context-invalidated - - 使用declarative content API实现页面操作
api-use-declarative-content
9. Code Style & Naming (MEDIUM)
9. 代码风格与命名(中)
- - Use is/has/should prefixes for boolean variables
style-boolean-naming - - Use consistent cache variable naming
style-cache-naming - - Define constants for magic values
style-constants - - Organize code by feature/layer
style-directory-structure - - Use consistent file naming conventions
style-file-naming - - Use descriptive function names
style-function-naming - - Use type-only imports for types
style-import-type - - Use index files for module entry points
style-index-entry-points - - Use enums for message types
style-message-enums - - Use PascalCase for types and interfaces
style-type-naming
- - 布尔变量使用is/has/should前缀
style-boolean-naming - - 使用统一的缓存变量命名规则
style-cache-naming - - 为魔法值定义常量
style-constants - - 按功能/层级组织代码
style-directory-structure - - 使用统一的文件命名规范
style-file-naming - - 使用描述性的函数名称
style-function-naming - - 类型导入使用仅类型导入语法
style-import-type - - 使用index文件作为模块入口
style-index-entry-points - - 使用枚举定义消息类型
style-message-enums - - 类型与接口使用PascalCase命名
style-type-naming
10. Component Patterns (MEDIUM)
10. 组件模式(中)
- - Use adapter pattern for browser APIs
comp-adapter-interface - - Structure content scripts consistently
comp-content-script-structure - - Use BEM or prefixed CSS classes
comp-css-class-patterns - - Use manager classes for complex state
comp-manager-class - - Use type guards for runtime validation
comp-type-guards - - Create reusable UI components
comp-ui-components
- - 为浏览器API使用适配器模式
comp-adapter-interface - - 统一内容脚本的结构
comp-content-script-structure - - 使用BEM或带前缀的CSS类名
comp-css-class-patterns - - 使用管理器类处理复杂状态
comp-manager-class - - 使用类型守卫进行运行时验证
comp-type-guards - - 创建可复用的UI组件
comp-ui-components
11. Error Handling (HIGH)
11. 错误处理(高)
- - Handle extension context invalidation
err-context-invalidation - - Use early returns for error handling
err-early-return - - Use nullish coalescing for defaults
err-null-coalescing - - Use promise barriers for coordination
err-promise-barrier - - Handle storage operation failures
err-storage-operations - - Safely parse URLs with try/catch
err-url-parsing - - Validate inputs at boundaries
err-validation-pattern
- - 处理扩展上下文失效问题
err-context-invalidation - - 使用提前返回进行错误处理
err-early-return - - 使用空值合并运算符设置默认值
err-null-coalescing - - 使用Promise屏障进行协调
err-promise-barrier - - 处理存储操作失败的情况
err-storage-operations - - 使用try/catch安全解析URL
err-url-parsing - - 在边界处验证输入
err-validation-pattern
12. Testing Patterns (MEDIUM)
12. 测试模式(中)
- - Mock chrome APIs in tests
test-browser-api-mocking - - Organize tests by feature
test-organization - - Test validation functions thoroughly
test-validation-functions
- - 在测试中模拟Chrome API
test-browser-api-mocking - - 按功能组织测试用例
test-organization - - 全面测试验证函数
test-validation-functions
How to Use
使用方法
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
阅读单个参考文件获取详细说明与代码示例:
- 分类定义 - 分类结构与影响级别说明
- 规则模板 - 添加新规则的模板
Full Compiled Document
完整编译文档
For a complete guide with all rules in a single document, see AGENTS.md.
如需查看包含所有规则的完整指南,请参阅AGENTS.md。
Reference Files
参考文件
| File | Description |
|---|---|
| AGENTS.md | Complete compiled guide with all rules |
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| AGENTS.md | 包含所有规则的完整编译指南 |
| references/_sections.md | 分类定义与排序说明 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |