什么是Chrome插件
Chrome插件,官方名稱extensions(擴(kuò)展程序),一般都稱為Chrome插件,
擴(kuò)展程序是自定義瀏覽體驗(yàn)的小型軟件程序。它們讓用戶可以通過多種方式定制Chrome的功能和行為。
chrome用戶可以在chrome://extensions/中管理自己的插件。開發(fā)者編寫的插件,必須發(fā)布到Chrome網(wǎng)上應(yīng)用商店,別的用戶才能安裝使用。
一個(gè)簡(jiǎn)單的Chrome插件
首先插件項(xiàng)目必須有一個(gè)manifest.json文件,這是插件的配置文件,可以理解為插件的入口。
我們?cè)陧?xiàng)目中創(chuàng)建一個(gè)最簡(jiǎn)單的manifest.json配置文件:
{
"name": "Hello world!",
"description": "First Chrome Extension",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "hello.html",
"default_icon": "hi.png"
}
}
在配置文件中action字段配置popup彈框,點(diǎn)擊插件圖片是彈出小窗口頁面,顯示的就是default_popup的內(nèi)容。
hello.html的內(nèi)容如下:
<html>
<body>
<h1>Hello world</h1>
</body>
</html>
整個(gè)目錄結(jié)構(gòu)如下
? ~ tree hi
hi
├── hello.html
├── hi.png
└── manifest.json
0 directories, 3 files
現(xiàn)在安裝測(cè)試一下效果。打開chrome://extensions/,確保開發(fā)者模式已開

點(diǎn)擊按鈕「加載已解壓的擴(kuò)展程序」,選中開發(fā)目錄hi加載,效果如下圖

點(diǎn)擊地址欄右側(cè)的拼圖圖標(biāo),選中剛剛加載的擴(kuò)展程序,點(diǎn)擊,效果如下圖

現(xiàn)在您的第一個(gè)chrome插件就完成了。
新建一個(gè)React項(xiàng)目
? ~ npm create vite@latest my-react-hw
│
◇ Select a framework:
│ React
│
◇ Select a variant:
│ JavaScript
│
◇ Scaffolding project in /Users/fromdtor/my-react-hw...
│
└ Done. Now run:
cd my-react-hw
npm install
npm run dev
? my-react-hw npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'vite@6.3.5',
npm WARN EBADENGINE required: { node: '^18.0.0 || ^20.0.0 || >=22.0.0' },
npm WARN EBADENGINE current: { node: 'v21.6.2', npm: '10.2.4' }
npm WARN EBADENGINE }
added 154 packages in 5s
33 packages are looking for funding
run `npm fund` for details
? my-react-hw npm run dev
> my-react-hw@0.0.0 dev
> vite
VITE v6.3.5 ready in 1630 ms
? Local: http://localhost:5173/
? Network: use --host to expose
? press h + enter to show help
效果如圖

React項(xiàng)目集成到chrome插件
將第一項(xiàng)目的manifest.json和hi.png復(fù)制到react項(xiàng)目的public子目錄里,目錄結(jié)構(gòu)如下
? ~ tree my-react-hw
my-react-hw
├── README.md
├── eslint.config.js
├── index.html
├── package-lock.json
├── package.json
├── public
│ ├── hi.png
│ ├── manifest.json
│ └── vite.svg
├── src
│ ├── App.css
│ ├── App.jsx
│ ├── assets
│ │ └── react.svg
│ ├── index.css
│ └── main.jsx
└── vite.config.js
3 directories, 14 files
manifest.json的內(nèi)容修改一下:
{
"name": "Hello react!",
"description": "React Chrome Extension",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "index.html",
"default_icon": "hi.png"
}
}
運(yùn)行命令生成文件,可以看到hi.png和manifest.json這些在public目錄下的文件都被復(fù)制過來了
? my-react-hw npm install
? my-react-hw cd dist
? dist ls
assets hi.png index.html manifest.json vite.svg
在chrome://extensions/中加載生成的dist目錄,然后運(yùn)行,效果如下圖

接下來
接下來,就需要學(xué)習(xí)chrome插件可以讀寫chrome宿主的哪寫數(shù)據(jù),擁有chrome的哪些功能了。