chrome-extension

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chrome 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

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Service Worker LifecycleCRITICAL
sw-
2Content Script OptimizationCRITICAL
content-
3Message Passing EfficiencyHIGH
msg-
4Storage OperationsHIGH
storage-
5Network & PermissionsMEDIUM-HIGH
net-
6Memory ManagementMEDIUM
mem-
7UI PerformanceMEDIUM
ui-
8API Usage PatternsLOW-MEDIUM
api-
9Code Style & NamingMEDIUM
style-
10Component PatternsMEDIUM
comp-
11Error HandlingHIGH
err-
12Testing PatternsMEDIUM
test-
优先级分类影响程度前缀
1Service Worker生命周期关键
sw-
2内容脚本优化关键
content-
3消息传递效率
msg-
4存储操作
storage-
5网络与权限中高
net-
6内存管理
mem-
7UI性能
ui-
8API使用模式中低
api-
9代码风格与命名
style-
10组件模式
comp-
11错误处理
err-
12测试模式
test-

Quick Reference

快速参考

1. Service Worker Lifecycle (CRITICAL)

1. Service Worker生命周期(关键)

  • sw-persist-state-storage
    - Persist state with chrome.storage instead of global variables
  • sw-avoid-keepalive
    - Avoid artificial service worker keep-alive patterns
  • sw-use-alarms-api
    - Use chrome.alarms instead of setTimeout/setInterval
  • sw-return-true-async
    - Return true from message listeners for async responses
  • sw-register-listeners-toplevel
    - Register event listeners at top level
  • sw-use-offscreen-for-dom
    - Use offscreen documents for DOM APIs
  • sw-persist-state-storage
    - 使用chrome.storage而非全局变量持久化状态
  • sw-avoid-keepalive
    - 避免人工维持service worker存活的模式
  • sw-use-alarms-api
    - 使用chrome.alarms替代setTimeout/setInterval
  • sw-return-true-async
    - 异步响应时从消息监听器返回true
  • sw-register-listeners-toplevel
    - 在顶层注册事件监听器
  • sw-use-offscreen-for-dom
    - 使用离屏文档处理DOM API

2. Content Script Optimization (CRITICAL)

2. 内容脚本优化(关键)

  • content-use-specific-matches
    - Use specific URL match patterns
  • content-use-document-idle
    - Use document_idle for content script injection
  • content-programmatic-injection
    - Prefer programmatic injection over manifest declaration
  • content-minimize-script-size
    - Minimize content script bundle size
  • content-batch-dom-operations
    - Batch DOM operations to minimize reflows
  • content-use-mutation-observer
    - Use MutationObserver instead of polling
  • content-use-specific-matches
    - 使用特定的URL匹配模式
  • content-use-document-idle
    - 使用document_idle时机注入内容脚本
  • content-programmatic-injection
    - 优先使用程序化注入而非清单声明
  • content-minimize-script-size
    - 最小化内容脚本包体积
  • content-batch-dom-operations
    - 批量处理DOM操作以减少重排
  • content-use-mutation-observer
    - 使用MutationObserver替代轮询

3. Message Passing Efficiency (HIGH)

3. 消息传递效率(高)

  • msg-use-ports-for-frequent
    - Use port connections for frequent message exchange
  • msg-minimize-payload-size
    - Minimize message payload size
  • msg-debounce-frequent-events
    - Debounce high-frequency events before messaging
  • msg-check-lasterror
    - Always check chrome.runtime.lastError
  • msg-avoid-broadcast-to-all-tabs
    - Avoid broadcasting messages to all tabs
  • msg-use-ports-for-frequent
    - 使用端口连接处理频繁的消息交互
  • msg-minimize-payload-size
    - 最小化消息负载体积
  • msg-debounce-frequent-events
    - 在发送消息前防抖高频事件
  • msg-check-lasterror
    - 始终检查chrome.runtime.lastError
  • msg-avoid-broadcast-to-all-tabs
    - 避免向所有标签页广播消息

4. Storage Operations (HIGH)

4. 存储操作(高)

  • storage-batch-operations
    - Batch storage operations instead of individual calls
  • storage-choose-correct-type
    - Choose the correct storage type for your use case
  • storage-cache-frequently-accessed
    - Cache frequently accessed storage values
  • storage-use-session-for-temp
    - Use storage.session for temporary runtime data
  • storage-avoid-storing-large-blobs
    - Avoid storing large binary blobs
  • storage-batch-operations
    - 批量执行存储操作而非单独调用
  • storage-choose-correct-type
    - 根据使用场景选择正确的存储类型
  • storage-cache-frequently-accessed
    - 缓存频繁访问的存储值
  • storage-use-session-for-temp
    - 使用storage.session存储临时运行时数据
  • storage-avoid-storing-large-blobs
    - 避免存储大型二进制Blob

5. Network & Permissions (MEDIUM-HIGH)

5. 网络与权限(中高)

  • net-use-declarativenetrequest
    - Use declarativeNetRequest instead of webRequest
  • net-request-minimal-permissions
    - Request minimal required permissions
  • net-use-activetab
    - Use activeTab permission instead of broad host permissions
  • net-limit-csp-modifications
    - Avoid modifying Content Security Policy headers
  • net-use-declarativenetrequest
    - 使用declarativeNetRequest替代webRequest
  • net-request-minimal-permissions
    - 请求最小必要权限
  • net-use-activetab
    - 使用activeTab权限而非宽泛的主机权限
  • net-limit-csp-modifications
    - 避免修改内容安全策略(CSP)头

6. Memory Management (MEDIUM)

6. 内存管理(中)

  • mem-cleanup-event-listeners
    - Clean up event listeners when content script unloads
  • mem-avoid-detached-dom
    - Avoid holding references to detached DOM nodes
  • mem-avoid-closure-leaks
    - Avoid accidental closure memory leaks
  • mem-clear-intervals-timeouts
    - Clear intervals and timeouts on cleanup
  • mem-use-weak-collections
    - Use WeakMap and WeakSet for DOM element references
  • mem-cleanup-event-listeners
    - 内容脚本卸载时清理事件监听器
  • mem-avoid-detached-dom
    - 避免持有已分离DOM节点的引用
  • mem-avoid-closure-leaks
    - 避免意外的闭包内存泄漏
  • mem-clear-intervals-timeouts
    - 清理时清除定时器与间隔任务
  • mem-use-weak-collections
    - 使用WeakMap和WeakSet存储DOM元素引用

7. UI Performance (MEDIUM)

7. UI性能(中)

  • ui-minimize-popup-bundle
    - Minimize popup bundle size for fast startup
  • ui-render-with-cached-data
    - Render popup UI with cached data first
  • ui-batch-badge-updates
    - Batch badge updates to avoid flicker
  • ui-use-options-page-lazy
    - Lazy load options page sections
  • ui-minimize-popup-bundle
    - 最小化弹窗包体积以实现快速启动
  • ui-render-with-cached-data
    - 优先使用缓存数据渲染弹窗UI
  • ui-batch-badge-updates
    - 批量更新徽章以避免闪烁
  • ui-use-options-page-lazy
    - 懒加载选项页的各个板块

8. API Usage Patterns (LOW-MEDIUM)

8. API使用模式(中低)

  • api-use-promises-over-callbacks
    - Use promise-based API calls over callbacks
  • api-query-tabs-efficiently
    - Query tabs with specific filters
  • api-avoid-redundant-api-calls
    - Avoid redundant API calls in loops
  • api-use-alarms-minperiod
    - Respect alarms API minimum period
  • api-handle-context-invalidated
    - Handle extension context invalidated errors
  • api-use-declarative-content
    - Use declarative content API for page actions
  • api-use-promises-over-callbacks
    - 优先使用基于Promise的API调用而非回调函数
  • api-query-tabs-efficiently
    - 使用特定过滤器查询标签页
  • api-avoid-redundant-api-calls
    - 避免在循环中进行重复的API调用
  • api-use-alarms-minperiod
    - 遵守alarms API的最小周期限制
  • api-handle-context-invalidated
    - 处理扩展上下文失效错误
  • api-use-declarative-content
    - 使用declarative content API实现页面操作

9. Code Style & Naming (MEDIUM)

9. 代码风格与命名(中)

  • style-boolean-naming
    - Use is/has/should prefixes for boolean variables
  • style-cache-naming
    - Use consistent cache variable naming
  • style-constants
    - Define constants for magic values
  • style-directory-structure
    - Organize code by feature/layer
  • style-file-naming
    - Use consistent file naming conventions
  • style-function-naming
    - Use descriptive function names
  • style-import-type
    - Use type-only imports for types
  • style-index-entry-points
    - Use index files for module entry points
  • style-message-enums
    - Use enums for message types
  • style-type-naming
    - Use PascalCase for types and interfaces
  • style-boolean-naming
    - 布尔变量使用is/has/should前缀
  • style-cache-naming
    - 使用统一的缓存变量命名规则
  • style-constants
    - 为魔法值定义常量
  • style-directory-structure
    - 按功能/层级组织代码
  • style-file-naming
    - 使用统一的文件命名规范
  • style-function-naming
    - 使用描述性的函数名称
  • style-import-type
    - 类型导入使用仅类型导入语法
  • style-index-entry-points
    - 使用index文件作为模块入口
  • style-message-enums
    - 使用枚举定义消息类型
  • style-type-naming
    - 类型与接口使用PascalCase命名

10. Component Patterns (MEDIUM)

10. 组件模式(中)

  • comp-adapter-interface
    - Use adapter pattern for browser APIs
  • comp-content-script-structure
    - Structure content scripts consistently
  • comp-css-class-patterns
    - Use BEM or prefixed CSS classes
  • comp-manager-class
    - Use manager classes for complex state
  • comp-type-guards
    - Use type guards for runtime validation
  • comp-ui-components
    - Create reusable UI components
  • comp-adapter-interface
    - 为浏览器API使用适配器模式
  • comp-content-script-structure
    - 统一内容脚本的结构
  • comp-css-class-patterns
    - 使用BEM或带前缀的CSS类名
  • comp-manager-class
    - 使用管理器类处理复杂状态
  • comp-type-guards
    - 使用类型守卫进行运行时验证
  • comp-ui-components
    - 创建可复用的UI组件

11. Error Handling (HIGH)

11. 错误处理(高)

  • err-context-invalidation
    - Handle extension context invalidation
  • err-early-return
    - Use early returns for error handling
  • err-null-coalescing
    - Use nullish coalescing for defaults
  • err-promise-barrier
    - Use promise barriers for coordination
  • err-storage-operations
    - Handle storage operation failures
  • err-url-parsing
    - Safely parse URLs with try/catch
  • err-validation-pattern
    - Validate inputs at boundaries
  • err-context-invalidation
    - 处理扩展上下文失效问题
  • err-early-return
    - 使用提前返回进行错误处理
  • err-null-coalescing
    - 使用空值合并运算符设置默认值
  • err-promise-barrier
    - 使用Promise屏障进行协调
  • err-storage-operations
    - 处理存储操作失败的情况
  • err-url-parsing
    - 使用try/catch安全解析URL
  • err-validation-pattern
    - 在边界处验证输入

12. Testing Patterns (MEDIUM)

12. 测试模式(中)

  • test-browser-api-mocking
    - Mock chrome APIs in tests
  • test-organization
    - Organize tests by feature
  • test-validation-functions
    - Test validation functions thoroughly
  • test-browser-api-mocking
    - 在测试中模拟Chrome API
  • 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

参考文件

FileDescription
AGENTS.mdComplete compiled guide with all rules
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
AGENTS.md包含所有规则的完整编译指南
references/_sections.md分类定义与排序说明
assets/templates/_template.md新规则模板
metadata.json版本与参考信息