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

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

什么是浏览器扩展?

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

扩展类型

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

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

相关推荐
Sam09277 分钟前
AI Agent 沙箱怎么做:从文件、网络、工具到权限边界的工程实践
人工智能·ai
大嘴皮猴儿11 分钟前
跨境电商运营笔记:我是如何用工具解决多语言素材问题的
大数据·人工智能·新媒体运营·自动翻译·教育电商
JS菌13 分钟前
Skills 动态加载系统:让 AI Agent 按需获取领域知识
前端·人工智能·后端
赤龙ERP13 分钟前
赤龙一周观察 · 6月第2周
大数据·人工智能·ai·erp
qq_2915792518 分钟前
霍客引擎与电商图片AI:智能视觉营销的新范式
人工智能
JGDT_19 分钟前
ERP重塑与未来趋势:SAP的实践及大一统格局(上)
大数据·人工智能·安全·架构·开源
洛星核21 分钟前
CrewAI 安装、使用方法详细全解
人工智能·github·人机交互·ai编程·agi·智能体
chen_zn9523 分钟前
RLinf复现RECAP(一):从轨迹回报到优势标签
人工智能·强化学习·具身智能·vla