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

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

什么是浏览器扩展?

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

扩展类型

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

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

相关推荐
newbe365241 小时前
我们如何使用 impeccable 优化前端界面设计与实现稳定性
前端·人工智能·分布式·github·aigc·wpf
katttt_2 小时前
卡特加特的玄武大模型和其他模型的差异化在哪里?
人工智能·私有化部署·智能体平台·玄武大模型
一次旅行7 小时前
AI 前沿日报 | 2026年7月3日 星期五
人工智能·github·ai编程
A15362557 小时前
装配具身机器人品牌推荐 工业装配场景选型指南与艾利特方案
大数据·人工智能·机器人
LLWZAI7 小时前
想要稳定变现,先跨过朱雀 AI 这道门槛
大数据·人工智能
安吉升科技7 小时前
商业场景智能客流统计摄像系统的关键技术机理解析
人工智能
古城小栈8 小时前
为啥说:训练用BF16,推理用FP16
人工智能·算法·机器学习
KaMeidebaby8 小时前
卡梅德生物技术快报|蛋白 N 端测序在重组贻贝融合蛋白表征中的应用,解决原核表达序列偏移工艺难题
前端·人工智能·物联网·算法·百度
TMT星球8 小时前
从像素复刻到行动控制:具身世界模型的底层逻辑探索
人工智能·深度学习·机器学习
ccimao63168 小时前
散户做财报整理、研报阅读、复盘记录,各类AI工具适配环节梳理
大数据·人工智能