浏览器扩展开发:打造个性化浏览体验
浏览器扩展开发打造个性化浏览体验什么是浏览器扩展浏览器扩展是一种可以增强浏览器功能的小型软件程序。扩展类型类型说明扩展程序完整功能的扩展主题自定义浏览器外观插件NPAPI 插件已废弃扩展结构my-extension/ ├── manifest.json ├── background.js ├── popup.html ├── popup.js ├── content.js └── icons/ ├── icon16.png ├── icon48.png └── icon128.pngManifest 文件{ 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 页面!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 h3My Extension/h3 button idbtnClick Me/button script srcpopup.js/script /body /html// 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// 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// 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// 保存数据 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); });消息传递// 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 }); } });权限说明{ permissions: [ activeTab, storage, tabs, scripting, all_urls ] }打包与发布# 开发模式加载 # 浏览器 - 扩展程序 - 加载已解压的扩展程序 # 打包 # 浏览器 - 扩展程序 - 打包扩展程序实战案例案例页面翻译工具// 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开始你的第一个扩展开发之旅吧