Chrome 插件框架 Plasmo 基本使用示例

📦 1. 安装 Plasmo

在项目目录下运行:

bash 复制代码
npm create plasmo@latest

按照提示选择:

  • Name: your-extension
  • Extension Type: Chrome (or multiple browsers)
  • TypeScript: 推荐 Yes
  • Manifest Version: MV3
  • Use React: Yes(Plasmo 推荐)

完成后会生成一个 Plasmo 扩展工程。


popup.tsx 编辑:

tsx 复制代码
function Popup() {
  return (
    <div style={{ padding: 16 }}>
      <h1>Hello Plasmo!</h1>
      <p>这是你的第一个 Plasmo 扩展。</p>
    </div>
  )
}

export default Popup

运行:

bash 复制代码
npm run dev

Plasmo 会自动生成浏览器扩展,并让你在开发者模式下安装。


🧲 3. 创建一个 Content Script(注入到网页的脚本)

新建文件:content.ts

ts 复制代码
console.log("Plasmo content script running!")

window.addEventListener("click", () => {
  console.log("你点击了页面!")
})

Plasmo 会自动把它加入 manifest,无需你配置 manifest.json。


🔥 4. 与页面进行 DOM 操作

ts 复制代码
// content.ts
const banner = document.createElement("div")
banner.innerText = "Hello from Plasmo!"
banner.style.cssText = `
  position: fixed;
  top: 20px;
  left: 20px;
  padding: 10px 20px;
  background: black;
  color: white;
  border-radius: 8px;
  z-index: 999999;
`
document.body.appendChild(banner)

🔄 5. Background Service Worker(后台脚本)

创建 background.ts

ts 复制代码
chrome.runtime.onInstalled.addListener(() => {
  console.log("扩展已安装!")
})

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === "PING") {
    sendResponse({ text: "PONG" })
  }
})

🔗 6. Content Script 与 Background 交互

content.ts:

ts 复制代码
chrome.runtime.sendMessage({ type: "PING" }, (response) => {
  console.log("后台回复:", response.text)
})

🎉 7. 打包扩展

bash 复制代码
npm run build

打包后输出在 build/ 目录。


📚 完整最小示例结构

复制代码
my-plasmo-extension/
├─ popup.tsx
├─ background.ts
├─ content.ts
├─ package.json
└─ plasmo.config.mjs

这就是一个可运行的 Plasmo 扩展最小示例。

相关推荐
资讯第一线2 小时前
《Chrome》 [142.0.7444.60][绿色便携版] 下载
前端·chrome
会篮球的程序猿2 小时前
原生表格文本过长展示问题,参考layui长文本,点击出现文本域
前端·javascript·layui
top_designer2 小时前
Firefly 样式参考:AI 驱动的 UI 资产“无限”生成
前端·人工智能·ui·aigc·ux·设计师
蜗牛前端2 小时前
使用 Trae AI 开发完整的开源 npm 包:snail-git-add
前端
Dontla3 小时前
React useMemo(当依赖项未变化,重复渲染时直接返回上一次缓存计算结果,而非重新执行计算)
前端·react.js·缓存
花生Peadar3 小时前
AI编程从入门到精通
前端·后端·代码规范
bug爱好者3 小时前
vue3.x 使用vue3-tree-org实现组织架构图 + 自定义模版内容 - 附完整示例
前端·javascript·vue.js
达达尼昂3 小时前
🎯 Flutter 拖拽选择组件:flutter_drag_selector —— 像选文件一样选择列表项
前端·flutter
Keely402853 小时前
Claude 配置使用墨刀MCP(modao-proto-mcp)
前端·aigc·claude