浏览器扩展开发:打造个性化浏览体验
什么是浏览器扩展?
浏览器扩展是一种可以增强浏览器功能的小型软件程序。
扩展类型
| 类型 | 说明 |
|---|---|
| 扩展程序 | 完整功能的扩展 |
| 主题 | 自定义浏览器外观 |
| 插件 | 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"]
}
]
}
Popup 页面
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();
}
});
总结
浏览器扩展开发是前端开发的一个有趣方向:
- 快速上手:HTML/CSS/JavaScript 即可开发
- 丰富 API:访问浏览器核心功能
- 个性化:打造独特的浏览体验
- 分发渠道:Chrome Web Store、Firefox Add-ons
开始你的第一个扩展开发之旅吧!