5.1 Chrome 浏览器插件实战案例
Content Script:修改网页内容
什么是 Content Script?
Content Script 可以:
- 读取网页的DOM结构
- 修改网页内容
- 监听网页事件
- 与 background script 通信
使用场景:
- 屏蔽广告
- 自动填表
- 网页翻译
- 数据抓取
- 样式美化
【案例2】网页划词搜索
功能:选中文字后,自动弹出搜索按钮
第 1 步:更新 manifest.json
{
"manifest_version": 3,
"name": "划词搜索",
"version": "1.0.0",
"description": "选中文字后快速搜索",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["content.css"]
}
],
"permissions": ["activeTab"]
}新字段说明:
content_scripts: 要注入的脚本配置matches: 哪些网页需要注入(<all_urls>= 所有网页)js: 要注入的JavaScript文件css: 要注入的CSS文件
第 2 步:创建 content.js
// 创建搜索按钮
function createSearchButton() {
const button = document.createElement('div');
button.id = 'quick-search-btn';
button.textContent = '搜索';
button.style.cssText = `
position: fixed;
background: #4285f4;
color: white;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
z-index: 10000;
font-size: 14px;
display: none;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
`;
document.body.appendChild(button);
return button;
}
// 初始化
const searchButton = createSearchButton();
// 监听文字选中
document.addEventListener('mouseup', function(e) {
const selectedText = window.getSelection().toString().trim();
if (selectedText.length > 0) {
// 显示按钮,定位到鼠标位置
searchButton.style.display = 'block';
searchButton.style.left = e.pageX + 'px';
searchButton.style.top = (e.pageY + 20) + 'px';
} else {
searchButton.style.display = 'none';
}
});
// 点击按钮搜索
searchButton.addEventListener('click', function() {
const selectedText = window.getSelection().toString().trim();
const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(selectedText)}`;
window.open(searchUrl, '_blank');
searchButton.style.display = 'none';
});
// 点击其他地方隐藏按钮
document.addEventListener('mousedown', function(e) {
if (e.target !== searchButton) {
searchButton.style.display = 'none';
}
});代码解析:
createSearchButton(): 创建一个固定定位的按钮mouseup事件:检测文字选中window.getSelection(): 获取选中的文字- 动态定位按钮到鼠标位置
- 点击按钮在新标签页打开搜索
测试:
- 重新加载插件
- 打开任意网页
- 选中一段文字
- 应该会出现「搜索」按钮
- 点击按钮跳转到 Google 搜索
遇到按钮不出现时,先在页面里按 Command+Option+I 打开 DevTools,切到 Console 看看是否有权限或脚本注入报错,再把错误贴给 AI。
Background Script:后台任务
Manifest V3 的变化
重要:Chrome Extension Manifest V3 使用 Service Worker 代替了旧版的 Background Page。
区别:
- ❌ 旧版:
background.js一直运行(占内存) - ✅ 新版:Service Worker 按需激活(省资源)
【案例3】监听标签页创建
功能:新标签页创建时,自动在控制台输出日志
manifest.json 配置:
{
"manifest_version": 3,
"name": "Tab Monitor",
"version": "1.0.0",
"background": {
"service_worker": "background.js"
},
"permissions": ["tabs"]
}background.js:
// 监听标签页创建
chrome.tabs.onCreated.addListener((tab) => {
console.log('新标签页创建:', tab.url || '空白页');
// 可以在这里做更多操作
// 比如:自动打开特定网址、记录浏览历史等
});
// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
console.log('标签页加载完成:', tab.url);
}
});
// 监听标签页关闭
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
console.log('标签页关闭,ID:', tabId);
});查看日志:
- 访问
chrome://extensions/ - 找到你的插件
- 点击「service worker」链接
- 打开 DevTools 查看控制台
通信机制
Content Script ↔️ Background 通信
场景:Content Script 在网页中抓取数据,发送给 Background 处理
Content Script 发送消息:
// content.js
// 向 background 发送消息
chrome.runtime.sendMessage(
{
action: 'getData',
data: {
title: document.title,
url: window.location.href
}
},
function(response) {
console.log('收到回复:', response);
}
);Background Script 接收消息:
// background.js
// 监听消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('收到消息:', request);
if (request.action === 'getData') {
// 处理数据
const processedData = {
...request.data,
timestamp: Date.now()
};
// 回复消息
sendResponse({
success: true,
data: processedData
});
}
return true; // 异步响应必须返回 true
});使用 AI 开发 Chrome 插件
Cursor 提示词模板
我想开发一个 Chrome 插件,需求如下:
【基本信息】
- 插件名称:[名称]
- 功能描述:[详细描述功能]
- 使用场景:[什么时候用]
【技术要求】
- Manifest V3
- 需要的权限:[tabs/storage/activeTab等]
- 是否需要 content script:[是/否]
- 是否需要 background:[是/否]
【具体功能】
1. [功能1的详细说明]
2. [功能2的详细说明]
请帮我:
1. 生成完整的项目结构
2. 提供所有必要的代码文件
3. 添加详细的代码注释
4. 说明如何安装和测试示例:
我想开发一个 Chrome 插件,需求如下:
【基本信息】
- 插件名称:Quick Bookmark
- 功能描述:快速保存当前网页到书签,并自动分类
- 使用场景:浏览网页时,一键保存到预设的文件夹
【技术要求】
- Manifest V3
- 需要的权限:bookmarks, activeTab, storage
- 需要 popup 界面
- 需要 background 处理书签逻辑
【具体功能】
1. 点击插件图标弹出界面,显示:
- 当前网页标题和URL
- 预设的书签文件夹列表(工作、学习、娱乐等)
2. 选择文件夹后,一键保存
3. 保存成功后显示提示
4. 支持自定义文件夹列表
请帮我:
1. 生成完整的项目结构
2. 提供所有必要的代码文件
3. 添加详细的代码注释
4. 说明如何安装和测试Last updated on