browser-extension-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Browser Extension Development

浏览器扩展开发

Manifest V3, minimal permissions, cross-browser first.
Manifest V3、最小权限优先、跨浏览器兼容优先。

Manifest V3

Manifest V3

Required for new extensions:
json
{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "permissions": ["storage"],
  "host_permissions": ["https://api.example.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["https://*.example.com/*"],
    "js": ["content.js"]
  }],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none'"
  }
}
新扩展必填:
json
{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "permissions": ["storage"],
  "host_permissions": ["https://api.example.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["https://*.example.com/*"],
    "js": ["content.js"]
  }],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none'"
  }
}

Minimal Permissions

最小权限

Request only what you need. Justify each permission:
PermissionUse Case
storage
Save user preferences
activeTab
Access current tab on user action
scripting
Inject scripts programmatically
https://specific.com/*
Access specific API
Never:
<all_urls>
without documented justification.
Use optional permissions for non-core features:
javascript
chrome.permissions.request({
  origins: ['https://optional.com/*']
}, (granted) => {
  if (granted) enableFeature();
});
仅申请所需权限,为每个权限提供合理说明:
权限使用场景
storage
保存用户偏好设置
activeTab
在用户操作时访问当前标签页
scripting
以编程方式注入脚本
https://specific.com/*
访问特定API
切勿: 无文档说明理由的情况下使用
<all_urls>
为非核心功能使用可选权限:
javascript
chrome.permissions.request({
  origins: ['https://optional.com/*']
}, (granted) => {
  if (granted) enableFeature();
});

Message Passing

消息传递

Always validate messages at boundaries:
javascript
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Validate sender
  if (!sender.tab) return;

  // Validate message structure
  if (message.type !== 'FETCH_DATA') return;
  if (typeof message.url !== 'string') return;

  // Process safely
  fetchData(message.url).then(sendResponse);
  return true; // async response
});
Never trust data from content scripts without validation.
务必在边界处验证消息:
javascript
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 验证发送者
  if (!sender.tab) return;

  // 验证消息结构
  if (message.type !== 'FETCH_DATA') return;
  if (typeof message.url !== 'string') return;

  // 安全处理
  fetchData(message.url).then(sendResponse);
  return true; // 异步响应
});
切勿未经验证就信任来自内容脚本的数据。

Cross-Browser Support

跨浏览器支持

javascript
// Use webextension-polyfill for API normalization
import browser from 'webextension-polyfill';

// Feature detection
if (browser.storage?.sync) {
  await browser.storage.sync.set({ key: value });
} else {
  await browser.storage.local.set({ key: value });
}
Test on Chrome, Firefox, Safari, Edge.
javascript
// 使用webextension-polyfill实现API标准化
import browser from 'webextension-polyfill';

// 特性检测
if (browser.storage?.sync) {
  await browser.storage.sync.set({ key: value });
} else {
  await browser.storage.local.set({ key: value });
}
在Chrome、Firefox、Safari、Edge上进行测试。

Updates

扩展更新

  • Semantic versioning (MAJOR.MINOR.PATCH)
  • Changelog accessible in-extension
  • Gradual rollout for major changes
  • Highlight permission changes to users
  • Maintain backward compatibility
  • Preserve user data across versions
  • 语义化版本控制(MAJOR.MINOR.PATCH)
  • 在扩展内可访问更新日志
  • 重大变更采用逐步推送策略
  • 向用户高亮显示权限变更
  • 保持向后兼容性
  • 跨版本保留用户数据

Anti-Patterns

反模式

  • <all_urls>
    permission hoarding
  • eval()
    or remote code execution
  • Trusting content script data without validation
  • Manifest V2 for new development
  • Chrome-only without cross-browser testing
  • Silent permission scope creep
  • 滥用
    <all_urls>
    权限
  • 使用
    eval()
    或远程代码执行
  • 未经验证就信任内容脚本数据
  • 为新开发使用Manifest V2
  • 仅支持Chrome而未进行跨浏览器测试
  • 悄悄扩大权限范围