浏览器扩展开发:打造个性化浏览体验

浏览器扩展开发:打造个性化浏览体验

什么是浏览器扩展?

浏览器扩展是一种可以增强浏览器功能的小型软件程序。

扩展类型

类型 说明
扩展程序 完整功能的扩展
主题 自定义浏览器外观
插件 NPAPI 插件(已废弃)

扩展结构

复制代码
my-extension/
├── manifest.json
├── background.js
├── popup.html
├── popup.js
├── content.js
└── icons/
    ├── icon16.png
    ├── icon48.png
    └── icon128.png

Manifest 文件

json 复制代码
{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "description": "A simple browser extension",
  "permissions": ["activeTab", "storage"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}
html 复制代码
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      width: 200px;
      padding: 10px;
    }
    button {
      width: 100%;
      padding: 8px;
      background: #42b983;
      color: white;
      border: none;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h3>My Extension</h3>
  <button id="btn">Click Me</button>
  <script src="popup.js"></script>
</body>
</html>
javascript 复制代码
// popup.js
document.getElementById('btn').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      function: () => {
        alert('Hello from extension!');
      }
    });
  });
});

Background Service Worker

javascript 复制代码
// background.js
chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed');
});

chrome.action.onClicked.addListener((tab) => {
  console.log('Extension clicked');
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    console.log('Tab loaded:', tab.url);
  }
});

Content Script

javascript 复制代码
// content.js
console.log('Running on:', window.location.href);

// 修改页面内容
const style = document.createElement('style');
style.textContent = `
  body {
    background-color: #f0f0f0 !important;
  }
`;
document.head.appendChild(style);

存储 API

javascript 复制代码
// 保存数据
chrome.storage.local.set({ 
  username: 'John',
  preferences: { darkMode: true }
}, () => {
  console.log('Data saved');
});

// 读取数据
chrome.storage.local.get(['username', 'preferences'], (result) => {
  console.log(result.username);
  console.log(result.preferences);
});

消息传递

javascript 复制代码
// popup.js -> background.js
chrome.runtime.sendMessage({ type: 'GET_DATA' }, (response) => {
  console.log(response);
});

// background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'GET_DATA') {
    sendResponse({ data: 'Hello from background' });
  }
});

权限说明

json 复制代码
{
  "permissions": [
    "activeTab",
    "storage",
    "tabs",
    "scripting",
    "<all_urls>"
  ]
}

打包与发布

bash 复制代码
# 开发模式加载
# 浏览器 -> 扩展程序 -> 加载已解压的扩展程序

# 打包
# 浏览器 -> 扩展程序 -> 打包扩展程序

实战案例

案例:页面翻译工具

javascript 复制代码
// content.js
function translateText() {
  const paragraphs = document.querySelectorAll('p');
  paragraphs.forEach(p => {
    const text = p.textContent;
    // 调用翻译 API
    translate(text).then(result => {
      p.textContent = result;
    });
  });
}

chrome.runtime.onMessage.addListener((request) => {
  if (request.action === 'translate') {
    translateText();
  }
});

总结

浏览器扩展开发是前端开发的一个有趣方向:

  1. 快速上手:HTML/CSS/JavaScript 即可开发
  2. 丰富 API:访问浏览器核心功能
  3. 个性化:打造独特的浏览体验
  4. 分发渠道:Chrome Web Store、Firefox Add-ons

开始你的第一个扩展开发之旅吧!

相关推荐
ZYJCSZKJ6 小时前
AI数字人实时交互系统的工程架构与多方言适配实践
人工智能·架构·交互·ai数字人直播系统
2601_965958467 小时前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
智购科技智能售货柜7 小时前
2026自动售货机整机可靠性测试:从高低温交变到EMC电磁兼容的认证工程实践~YH
运维·服务器·数据库·人工智能·物联网
“初生”7 小时前
用 Codex 做一致性 AI 动画:5 步工作流,角色不再漂移
人工智能·ai·chatgpt
AI_小站7 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
随风而飘1867 小时前
KEITHLEY吉时利 2400 数字源表
人工智能·功能测试·科技·测试工具
HyperAI超神经7 小时前
【Triton 教程】triton_language.fdiv
人工智能·深度学习·triton
心无旁骛~7 小时前
anywhere-labs/deepseek-harness-desktop 如何围绕上游演进:Submodule、版本溯源与非 Fork 架构
人工智能·架构
xiaohaiAIgeo7 小时前
【2026年】医药研发实验室GLP的通风设计要求:稳定性可验证性与合规性
网络·人工智能·科普知识
ZGIAI7 小时前
ZGI Runner 与 Sandbox:两层运行边界
人工智能·架构