Skip to content

🚀 初探Chrome Extension开发 ​

📝 基础介绍 ​

Chrome扩展是一种可以定制化Chrome浏览器功能的小型软件程序。通过开发Chrome扩展,我们可以为浏览器添加各种实用功能,提升用户体验。

开发环境搭建 ​

  1. 在Chrome地址栏输入 chrome://extensions
  2. 开启右上角的"开发者模式"
  3. 现在你可以通过"加载已解压的扩展程序"来加载本地开发中的扩展

🔧 核心组件 ​

1. manifest.json 配置文件 📄 ​

这是每个Chrome扩展必须包含的核心配置文件,定义了扩展的各种属性和权限。

json
{
  "name": "My Extension",
  "version": "1.0",
  "manifest_version": 3,
  "description": "一个示例Chrome扩展",
  
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon.png",
    "default_title": "点击打开扩展"
  },
  
  "permissions": [
    "storage",
    "tabs",
    "notifications"
  ],
  
  "background": {
    "service_worker": "background.js"
  },
  
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ]
}

2. Background Service Worker 🔄 ​

作为扩展的大脑,负责处理后台任务和全局状态管理。

javascript
// background.js
chrome.runtime.onInstalled.addListener(() => {
  console.log('扩展已安装');
});

// 监听来自其他组件的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'getData') {
    sendResponse({ data: '这是来自后台的数据' });
  }
});

3. Popup 页面 💡 ​

点击扩展图标时弹出的交互界面。

html
<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { width: 300px; padding: 10px; }
  </style>
</head>
<body>
  <h2>我的扩展</h2>
  <button id="actionBtn">执行操作</button>
  <script src="popup.js"></script>
</body>
</html>

4. Content Scripts 📜 ​

注入到网页中运行的脚本,可以直接操作页面DOM。

javascript
// content.js
// 向页面注入自定义样式
const style = document.createElement('style');
style.textContent = `
  .my-extension-highlight {
    background-color: yellow;
  }
`;
document.head.appendChild(style);

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'highlight') {
    const elements = document.querySelectorAll(message.selector);
    elements.forEach(el => el.classList.add('my-extension-highlight'));
    sendResponse({ success: true });
  }
});

🔌 实用功能示例 ​

1. 徽章(Badge)显示 🏷️ ​

javascript
// 设置徽章文本和颜色
chrome.action.setBadgeText({ text: '新' });
chrome.action.setBadgeBackgroundColor({ color: '#FF0000' });

2. 右键菜单 📋 ​

javascript
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'searchSelection',
    title: '搜索:%s',
    contexts: ['selection']
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'searchSelection') {
    const url = `https://www.google.com/search?q=${encodeURIComponent(info.selectionText)}`;
    chrome.tabs.create({ url });
  }
});

3. 消息通信 📡 ​

javascript
// popup到content script的通信
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
  chrome.tabs.sendMessage(tabs[0].id, {
    action: 'highlight',
    selector: '.important'
  }, response => {
    console.log('操作结果:', response.success);
  });
});

💡 开发技巧 ​

  1. 调试技巧

    • background: 在扩展管理页面点击"service worker"
    • popup: 右键点击扩展图标,选择"检查"
    • content script: 在页面中使用DevTools调试
  2. 最佳实践

    • 使用manifest v3进行开发
    • 遵循最小权限原则
    • 注意性能优化,避免过度操作DOM
    • 做好错误处理和用户提示
  3. 安全注意事项

    • 避免使用eval()和innerHTML
    • 注意跨域安全
    • 谨慎处理用户数据

🎯 结语 ​

Chrome扩展开发是一个强大的工具,可以极大地增强浏览器的功能。通过合理使用各个组件和API,我们可以创建出实用且高效的扩展程序。

💡 提示:本文基于Manifest V3编写,如果你看到使用V2的教程,建议优先使用V3的新特性进行开发。

参考资料: