目录
前言
一、浏览器插件的主要功能
二、插件的工作原理
插件结构
manifest.json
icons
background.js
content-scripts
三、插件例子
popup
popup.html
popup.js
styles.css
background.js
content-script.js
manifest.json
四、其它
前言
本文不做特殊说明,均在Manifest V3版本下说明
一、浏览器插件的主要功能
- 修改网页内容
- 增强浏览器功能
- 与外部服务交互
- 开发者工具
二、插件的工作原理
插件结构
- manifest.json:插件配置文件
- background.js:后台脚本
- content-script.js:注入页面的脚本
- popup:弹窗UI
- options:插件设置页面(可选)
- icons:插件图标(必须)
- _locales:多语言支持(可选)
manifest.json
这是Chrome插件最重要也是必不可少的文件,用来配置所有和插件相关的配置,必须放在根目录中。
下面是一个示例manifest.json,我们将以这个示例切入,逐步说明配置项:
{"manifest_version": 3,"name": "Run script automatically","description": "Runs a script on www.example.com automatically when user installs the extension","version": "1.0","icons": {"16": "images/icon-16.png","32": "images/icon-32.png","48": "images/icon-48.png","128": "images/icon-128.png"},"background": {"service_worker": "service-worker.js"},"content_scripts": [{"js": ["content-script.js"],"matches": ["http://*.example.com//"]}],"permissions": ["scripting", "activeTab"] }
- manifest_version:指定扩展程序使用的清单文件格式的版本,唯一支持的值是3
- name:插件名字
- version:插件版本号
- description:插件描述
- icons:插件图标
- background:插件的“后台脚本”
- content_scripts:用户打开网页时,使用的插入脚本
- permissions:启用特定扩展API
icons
icons不同的键值,图标会在不同的地方使用:
- 16:扩展程序页面和上下文菜单中的图标
- 32:Windows计算机需要此大小
- 48:显示在"扩展程序"页面上
- 128:会在安装过程中和Chrome应用商店中显示
background.js
在V3版本中
background.js其实就是“Service Worker”,Service Worker是插件的“核心处理脚本”(大脑)
Service Worker的三个特点:
- 无持久化运行:仅在需要时激活(如响应事件、处理消息),闲置时会被浏览器终止,节省资源
- 无DOM访问能力:不能直接操作DOM(document、window等对象不可用),也不发使用alert、confirm等弹窗API
- 生命周期由浏览器管理:无需手动控制启动 / 关闭,浏览器会根据事件自动调度
Service Worker的五个核心功能:
- 监听浏览器级事件(chrome.runtime.onInstalled、chrome.tabs.onUpdated等)
- 作为插件各组件的通信中枢
- 处理跨域请求
- 管理插件状态
- 调度定时任务
content-scripts
用于操作网页,它一般具有下面五个能力:
- 修改网页DOM:可以直接读取、修改当前网页的HTML结构、CSS样式或文本内容。
- 获取网页信息:能够提取网页中的数据(文本、图片链接等等),并通过插件的其他部分进行处理或上传
- 注入交互逻辑:可以为网页添加自定义的交互功能,比如添加新按钮、绑定事件监听,实现网页原本没有的功能
- 隔离性运行:虽然能访问网页DOM,但内容脚本运行在独立的沙盒环境中,不能直接访问网页自身的JavaScript变量/函数,也不能直接访问插件的后台脚本变量,安全性高
- 跨域请求能力:相比普通网页脚本,内容脚本可以通过插件的后台页面间接发起跨域请求
三、插件例子
整个插件结构如下:
-extension-icons-logo.png-popup-popup.html-popup.js-styles.css-backrgound.js-content-script.js-manifest.json
popup
popup.html
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Page Info</title><link rel="stylesheet" href="styles.css">
</head>
<body><div class="container"><h1>当前页面信息</h1><p id="title">标题:加载中...</p><p id="url">URL:加载中...</p><button id="changeBg">随机背景色</button></div><script src="popup.js"></script>
</body>
</html>
popup.js
// 获取当前标签页信息
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {const tab = tabs[0];document.getElementById('title').textContent = `标题:${tab.title}`;document.getElementById('url').textContent = `URL:${tab.url}`;
});// 点击按钮修改页面背景色
document.getElementById('changeBg').addEventListener('click', () => {const colors = ['#ffcccc', '#ccffcc', '#ccccff', '#ffffcc'];const randomColor = colors[Math.floor(Math.random() * colors.length)];// 向内容脚本发送消息chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {chrome.tabs.sendMessage(tabs[0].id, { action: "changeBg", color: randomColor });});
});
styles.css
body {width: 300px;padding: 10px;font-family: Arial, sans-serif;
}
button {padding: 8px;background: #4CAF50;color: white;border: none;cursor: pointer;
}
background.js
// Manifest V3使用Service Worker,无需常驻后台
console.log("Service Worker已加载");
content-script.js
// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {if (request.action === "changeBg") {document.body.style.backgroundColor = request.color;}
});
manifest.json
{"name": "Page Info Viewer","version": "1.0","manifest_version": 3,"description": "显示当前页面的标题和URL,并修改背景色","permissions": ["activeTab", "scripting"],"icons": {"16": "icons/logo.png", "48": "icons/logo.png", "128": "icons/logo.png" },"action": {"default_popup": "popup/popup.html"},"background": {"service_worker": "background.js"},"content_scripts": [{"matches": ["<all_urls>"],"js": ["content-script.js"]}]
}
效果:
四、其它
如果您对该文感兴趣,可以参考我的专栏:
https://blog.csdn.net/zheshiyangyang/category_13023388.html