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

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

什么是浏览器扩展?

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

扩展类型

类型 说明
扩展程序 完整功能的扩展
主题 自定义浏览器外观
插件 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

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

相关推荐
只是甲5 小时前
Text2SQL 系列博客 02:技术原理深度剖析 - 从自然语言到 SQL 的完整链路
人工智能·text2sql·nl2sql·ai agent·自助数据分析·data agent·agentic 数据洞察
懷淰メ5 小时前
【AI赋能】基于PyQt+YOLO+DeepSeek水上漂浮物检测系统(详细介绍)
人工智能·yolo·目标检测·计算机视觉·pyqt·漂浮物·水上漂浮物
EQUINOX15 小时前
【论文精读】| CLIP精读
大数据·人工智能
PC2005-cloud5 小时前
博文已索引但不展示:一次 Bing SEO 问题排查记录
服务器·人工智能
weixin_408099675 小时前
2026 图片去文字 API 实战:AI一键去除图片文字(附 Python / Java / PHP / JS 完整代码)
人工智能·api接口·图片去水印·石榴智能·ai图像修复·图片去文字
greenbbLV6 小时前
2026节日慰问品政策解读:合规标准升级与福利行业新趋势
人工智能·节日
奈斯先生Vector6 小时前
告别工具碎片化:基于 Nano Banana 全模态 AI 聚合架构搭建“文本-图像-视频”自动化协同生产线
运维·数据库·人工智能·架构·自动化·aigc·音视频
领麦微红外6 小时前
国产MEMS红外测温传感器:传感器+算法+产品级出厂标定一站式交付模式深度解读
人工智能·硬件工程·产品经理
mingo_敏6 小时前
DeepAgents : 检索(Retrieval)
人工智能·深度学习·langchain
微三云 - 廖会灵 (私域系统开发)6 小时前
消费即资产:积分增值异业联盟商业模式完整拆解(附落地逻辑、合规方案与盈利模型)
大数据·人工智能