my-extension/
├─ manifest.json # 声明一切(入口)
├─ popup.html # 工具栏弹窗页
├─ popup.css # 弹窗样式
├─ popup.js # 弹窗逻辑
├─ background.js # 后台服务(service worker)
├─ content.js # 注入网页的脚本
└─ icons/
├─ icon16.png
├─ icon48.png
└─ icon128.png
// manifest.json
{
"manifest_version": 3,
"name": "extension",
"version": "1.0.0",
"description": "description",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"action": {
"default_title": "打开插件设置",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"js": ["content.js"]
}
],
"permissions": ["storage", "activeTab", "scripting"],
"host_permissions": ["https://*/*", "http://*/*"]
}
字段 作用
manifest_version 版本,必须是 3
name / version / description 名称、版本号、描述
icons 图标(16/48/128 三个尺寸)
action 工具栏按钮配置:default_popup 指定弹窗页
background 后台:service_worker 指定后台脚本
content_scripts 注入网页的脚本(我补充的,核心)
permissions API 权限(storage、scripting 等)
host_permissions 站点权限(能访问哪些网站)
// popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="popup.css">
</head>
<body>
<h3>我的插件</h3>
<button id="btn">切换背景色</button>
<script src="popup.js"></script>
</body>
</html>
// popup.js
document.getElementById('btn').addEventListener('click', async () => {
// 向 background 发消息
const res = await chrome.runtime.sendMessage({ type: 'toggle-bg' })
console.log('background 返回:', res)
})
// background.js
// 插件安装/更新时触发
chrome.runtime.onInstalled.addListener(() => {
console.log('插件安装成功')
chrome.storage.local.set({ enabled: true })
})
// 读取存储
async function getKey() {
const res = await chrome.storage.local.get('enabled')
return res.enabled
}
// 监听来自 popup / content script 的消息
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'toggle-bg') {
// 转发给当前标签页的 content script
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { type: 'toggle-bg' })
})
sendResponse('ok')
}
return true // ★ 异步 sendResponse 必须 return true
})
// content.js (注入到网页运行)
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'toggle-bg') {
document.body.style.background = 'pink' // 改网页背景色
sendResponse('已修改背景')
}
})
popup ←→ background ←→ content script
chrome.runtime chrome.tabs
.sendMessage .sendMessage
通信方向 API 说明
popup → background chrome.runtime.sendMessage() 都走 runtime
content → background chrome.runtime.sendMessage() 都走 runtime
background → popup 通过sendResponse返回 popup发的消息能拿到返回
background → content chrome.tabs.sendMessage(tabId, msg) 需要指定 tabId
① popup.js:点击按钮 → chrome.runtime.sendMessage({ type: 'toggle-bg' })
② background.js:onMessage 收到 → 查当前标签页 → chrome.tabs.sendMessage(tabId, {type:'toggle-bg'})
③ content.js:onMessage 收到 → 改 document.body 背景色
④ content.js:sendResponse('已修改') → 返回给 background
⑤ background.js:sendResponse('ok') → 返回给 popup
runtime 管「自己人」(popup/background)
tabs 管「网页」(content script)
background 是中转站,两头都能连
// storage
// 存(异步)
await chrome.storage.local.set({ key: 'value' })
// 取(异步,返回对象)
const res = await chrome.storage.local.get('key')
console.log(res.key) // 'value'
// 删
await chrome.storage.local.remove('key')
本地加载(开发调试)
打开 chrome://extensions(Edge 是 edge://extensions)
右上角打开「开发者模式」
点「加载已解压的扩展程序」
选择你的插件文件夹
改代码后,点插件卡片上的刷新按钮重新加载即可
// 休眠问题
// ❌ 错误:依赖全局变量,休眠后丢失
let count = 0
// ✅ 正确:存 storage,休眠也不丢
await chrome.storage.local.set({ count: 0 })
// return true
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// 同步处理,可以不用 return true
// 但如果是异步(比如 await 了),必须 return true 才能 sendResponse
setTimeout(() => sendResponse('异步返回'), 100)
return true // ★ 不写这行,sendResponse 会失效
})