本文参考文档: 浏览器插件开发教程文档 (yuque.com)
目录结构
- manifest.json
- service worker
- content scripts
- 插件页面
manifest.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| { "manifest_version": 3, "name": "插件名称", "version": "版本",
"description": "插件描述", "author": "作者名", "background": { "service_worker": "background.js" }, "options_ui": { "page": "options.html", "open_in_tab": true }, "content_scripts": [ { "matches": [ "*://www.baidu.com/*" ], "js": [ "test.js" ], "all_frames": true, "css": [] } ], "web_accessible_resources": [ { "matches": [ "*://www.baidu.com/*" ], "resources": [ "test.css" ] } ], "host_permissions": [ "https://*/*" ], "permissions": [ "storage", "contextMenus", "cookies" ], "action": { "default_icon": { "16": "icon16.png", "32": "icon32.png", "48": "icon48.png", "64": "icon64.png", "128": "icon128.png" }, "default_popup": "popup.html", "icons": { "16": "icon16.png", "32": "icon32.png", "48": "icon48.png", "64": "icon64.png", "128": "icon128.png" } } }
|
content scripts
文档如下: https://developer.chrome.com/docs/extensions/mv3/content_scripts/
content scripts只能使用部分的浏览器api,最常用的api为storage与runtime两个api。
| 配置项 |
详情 |
|
| matches |
指定此内容脚本将被注入到哪些页面,详见match_patterns |
|
| js |
要注入匹配页面的 JavaScript 文件列表。它们按照它们在此数组中出现的顺序注入。 |
|
| css |
要注入匹配页面的 CSS 文件列表。在为页面构造或显示任何 DOM 之前,它们按照它们在此数组中出现的顺序注入。 |
|
| all_frames |
默认为false,表示仅匹配顶部框架。 如果指定true,它将注入所有框架,即使该框架不是选项卡中最顶层的框架。每个框架都独立检查 URL 要求,如果不满足 URL 要求,它不会注入子框架。 |
|
| run_at |
document_idle |
参考:运行 |
| document_start |
|
|
| document_end |
|
|
service worker
一个插件只能有一个service worker,可以在manifest配置type来使service worker声明为ES Module
1 2 3 4
| "background": { "service_worker": "background.js", "type": "module" }
|
在background.js 中 设置如下
1 2 3 4 5 6 7 8 9 10 11 12 13
| chrome.action.onClicked.addListener(async (tab) => { console.log(tab); if (tab.url.includes("www.baidu.com")) { console.log("this is baidu page"); chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['exec.js'], world:"MAIN" }); }else{ console.log("this is not baidu page"); } })
|
上文意思是。点击这个图标 代表着 执行下面这个js 并且主环境
Ul elements
界面组件 | Chrome Extensions | Chrome for Developers
样式很多 自己看
通信
界面组件 | Chrome Extensions | Chrome for Developers
由于content_scripts运行在网页中,而不是浏览器插件的环境,所以它需要一些特殊的方式来和浏览器插件的内容进行通信。
通信的方式包括用于一次性请求的简单通信和用于长期连接的长连接通信。
挨个传递通信