本文最后更新于 2025-08-14T01:08:34+08:00
介绍
plasmo 是一个用于构建浏览器扩展的框架,它基于 React 和 TypeScript,提供了一套简单易用的 API,可以帮助开发者快速构建功能丰富的浏览器扩展。
plasmo 的主要特点包括:跨平台支持、模块化开发、丰富的插件系统等。通过使用 plasmo,开发者可以轻松地创建出具有强大功能的浏览器扩展,例如:广告拦截器、密码管理器、翻译工具等。
安装器安装
这里使用 pnpm 安装
pnpm安装
在powershell中执行以下命令:
1
| Invoke-WebRequest https://get.pnpm.io/install.ps1 -UseBasicParsing | Invoke-Expression
|
直接拉github 可能比较慢
也可以在npm中安装
1 2 3
| npm install -g pnpm
npm install -g @pnpm/exe
|
兼容性
以下是各版本 pnpm 与各版本 Node.js 之间的兼容性表格。
Node.js |
pnpm 7 |
pnpm 8 |
pnpm 9 |
Node.js 12 |
❌ |
❌ |
❌ |
Node.js 14 |
✔️ |
❌ |
❌ |
Node.js 16 |
✔️ |
✔️ |
❌ |
Node.js 18 |
✔️ |
✔️ |
✔️ |
Node.js 20 |
✔️ |
✔️ |
✔️ |
项目安装
1 2 3 4 5
| pnpm create plasmo
yarn create plasmo
npm create plasmo
|
创建项目
1
| plasmo create plasmo_study
|
这里创建项目 输入自己的项目名 |描述|作者名

运行项目
项目结构

manifest.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| { "manifest_version": 3, "name": "My Extension", "version": "1.0", "description": "A simple extension", "action": { "default_popup": "popup/index.html" }, "permissions": ["storage", "activeTab"], "background": { "service_worker": "background/index.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content/index.js"] } ] }
|
background
background 脚本用于处理扩展的后台逻辑,例如:监听浏览器事件、与浏览器通信等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { Plasmo } from "@plasmo/core";
export default Plasmo.registerBackground({ async onInstall() { console.log("Extension installed"); }, async onUpdated() { console.log("Extension updated"); }, async onMessage(message: any, sender: any) { console.log("Message received:", message); return "Message received"; }, });
|
content
content 脚本用于在网页中注入代码,例如:修改网页内容、添加事件监听等。
1 2 3 4 5 6 7 8 9 10 11
| import { Plasmo } from "@plasmo/core";
export default Plasmo.registerContent({ async onDOMReady() { console.log("DOM ready"); }, async onMessage(message: any, sender: any) { console.log("Message received:", message); return "Message received"; }, });
|
popup 脚本用于创建扩展的弹出窗口,例如:显示扩展的界面、与用户交互等。
1 2 3 4 5 6 7 8 9 10 11 12
| import { Plasmo } from "@plasmo/core";
export default Plasmo.registerPopup({ render() { return ( <div> <h1>Hello, Plasmo!</h1> <button onClick={() => alert("Hello, Plasmo!")}>Click me</button> </div> ); }, });
|
配置文件
plasmo.config.ts
1 2 3 4 5
| import { PlasmoConfig } from "@plasmo/core";
export default PlasmoConfig({ });
|
总结
plasmo 是一个功能强大的浏览器扩展开发框架,它提供了丰富的 API 和插件系统,可以帮助开发者快速构建出具有强大功能的浏览器扩展。通过使用 plasmo,开发者可以轻松地实现广告拦截、密码管理、翻译工具等功能,为用户提供更加便捷、安全的浏览体验。