Chrome插件开发入门教程

Chrome 扩展本质是一个带 manifest.json 的网页项目,用普通 HTML/CSS/JS 就能写。

2015 年写这篇时,标准还是 Manifest V2,background 是一个常驻的页面。2024 年 Chrome 全面停用 V2,现在必须用 V3——background 变成了会被随时休眠的 service worker,这是最大的迁移难点。

一、2015 年的写法(Manifest V2)

manifest.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.0.0",
"permissions": ["storage", "tabs", "http://*/*", "https://*/*"],
"browser_action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}

V2 的 background 是一个隐藏的后台页面,可以常驻内存、用全局变量存状态、直接操作 DOM。写起来很顺手。

权限声明

V2 时代 permissions 里混着 API 权限和域名权限,http://*/* 这种全站权限很常见——这也是后来被诟病的主要原因。

二、2024 年之后的写法(Manifest V3)

manifest.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0.0",
"permissions": ["storage", "activeTab"],
"host_permissions": ["https://example.com/*"],
"action": {
"default_popup": "popup.html",
"default_icon": "icons/48.png"
},
"content_scripts": [
{
"matches": ["https://example.com/*"],
"js": ["content.js"]
}
],
"background": {
"service_worker": "background.js"
},
"icons": { "16": "icons/16.png", "48": "icons/48.png", "128": "icons/128.png" }
}

主要变化:

项 V2 V3
版本号 "manifest_version": 2 3
后台 background.scripts + persistent background.service_worker
图标入口 browser_action / page_action action
域名权限 混在 permissions 里 单独的 host_permissions
远程代码 允许 eval、远程 JS 禁止,所有代码必须打包
网络请求拦截 webRequest 阻塞式 declarativeNetRequest 声明式

时间线

1
2
3
4
2020-11  Manifest V3 正式发布
2022-09 Google 宣布 V2 弃用计划
2023-01 企业版延期,个人版开始灰度
2024-06 Chrome 127 起全面停用 V2 扩展

现在新建扩展必须用 V3,商店已不接受 V2 提交。

三、三个运行环境

环境 能做什么 不能做什么
popup 访问扩展自己的 DOM,调用 chrome.* API 不能直接操作页面 DOM
content script 读写页面 DOM,和页面共用 DOM 树 不能直接调用大部分 chrome.* API
background(service worker) 调用所有 chrome.* API,处理事件 没有 DOM,随时可能被休眠

消息通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// content.js -> background
chrome.runtime.sendMessage({ type: 'GET_DATA', url: location.href }, (res) => {
console.log(res);
});

// background.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'GET_DATA') {
fetch(msg.url)
.then(r => r.text())
.then(t => sendResponse({ html: t }));
return true; // 异步响应必须返回 true,否则通道立即关闭
}
});

四、V3 最大的坑:service worker 会休眠

V2 的 background 页面可以这样写:

1
2
3
4
5
6
// V2:全局变量常驻
let counter = 0;
chrome.runtime.onMessage.addListener((msg) => {
counter++;
return { counter };
});

V3 里 service worker 大约 30 秒无事件就被终止,counter 会重置。正确做法是用 chrome.storage:

1
2
3
4
5
6
7
// V3:持久化到 storage
chrome.runtime.onMessage.addListener(async (msg) => {
const { counter = 0 } = await chrome.storage.local.get('counter');
const next = counter + 1;
await chrome.storage.local.set({ counter: next });
return { counter: next };
});

其他限制:

  • 不能用 XMLHttpRequest(用 fetch)
  • 不能用 localStorage(用 chrome.storage)
  • 不能用 DOM 相关 API
  • setTimeout 超过 30 秒不可靠(用 chrome.alarms)

五、最小示例:抓取页面标题

content.js:

1
chrome.runtime.sendMessage({ title: document.title });

popup.js:

1
2
3
chrome.runtime.onMessage.addListener((msg) => {
document.getElementById('out').textContent = msg.title;
});

注意:popup 只有在打开时才存在,content script 发消息时 popup 可能没开,消息会丢失。更可靠的方式是 content script 写入 chrome.storage,popup 打开时读取。

六、调试

环境 入口
popup 右键扩展图标 → 审查弹出内容
content script 页面 F12 → Console(日志会显示,但变量在隔离环境)
background chrome://extensions → 点击「Service Worker」链接
热更新 改代码后到扩展页点刷新,content script 需要重新加载页面

七、发布

  1. 注册 Chrome Web Store 开发者账号(一次性 5 美元)
  2. 打包:zip -r extension.zip . -x "*.git*"
  3. 上传、填写说明、截图、隐私政策
  4. 审核通常 1–3 个工作日,涉及敏感权限(<all_urls>、tabs)会审得更久

八、常见坑

  • host_permissions 和 permissions 分开:V3 把域名权限单独拆出来了,写错位置会导致 API 不可用
  • content script 拿不到页面 JS 的变量:它运行在隔离环境(isolated world),只能通过 DOM 交互。需要访问页面变量时用 chrome.scripting.executeScript({ world: 'MAIN' })
  • CSP 限制:不能内联 <script>,不能 eval,不能用远程 JS
  • service worker 不能 import 外部 CDN:所有依赖必须打包进扩展
  • **declarativeNetRequest 替代 webRequest**:拦截规则要写成 JSON,动态规则有数量上限(默认 5000 条)
  • 权限最小化:<all_urls> 这类全站权限会让审核变慢,也影响用户安装意愿

九、V2 → V3 迁移清单

  • manifest_version 改成 3
  • browser_action → action
  • background.scripts → background.service_worker
  • 全局变量改成 chrome.storage
  • webRequest → declarativeNetRequest
  • 移除所有 eval、内联脚本、远程 JS
  • 域名权限移到 host_permissions
  • chrome.extension.getBackgroundPage() 在 MV3 已彻底移除,改用消息通信或 chrome.runtime.getContexts()

参考


Chrome插件开发入门教程
https://iyuluo.com/2015/12/30/Chrome插件开发入门教程/
作者
yuluo
发布于
2015年12月30日
许可协议