利用react开发chrome插件

什么是Chrome插件

Chrome插件,官方名称extensions(扩展程序),一般都称为Chrome插件,
扩展程序是自定义浏览体验的小型软件程序。它们让用户可以通过多种方式定制Chrome的功能和行为。

chrome用户可以在chrome://extensions/中管理自己的插件。开发者编写的插件,必须发布到Chrome网上应用商店,别的用户才能安装使用。

一个简单的Chrome插件

首先插件项目必须有一个manifest.json文件,这是插件的配置文件,可以理解为插件的入口。
我们在项目中创建一个最简单的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弹框,点击插件图片是弹出小窗口页面,显示的就是default_popup的内容。
hello.html的内容如下:

<html>

<body>
    <h1>Hello world</h1>
</body>

</html>

整个目录结构如下

➜  ~ tree hi
hi
├── hello.html
├── hi.png
└── manifest.json

0 directories, 3 files

现在安装测试一下效果。打开chrome://extensions/,确保开发者模式已开

1

点击按钮「加载已解压的扩展程序」,选中开发目录hi加载,效果如下图

2

点击地址栏右侧的拼图图标,选中刚刚加载的扩展程序,点击,效果如下图

3

现在您的第一个chrome插件就完成了。

新建一个React项目

➜  ~ 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

效果如图

4

React项目集成到chrome插件

将第一项目的manifest.json和hi.png复制到react项目的public子目录里,目录结构如下

➜  ~ 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的内容修改一下:

{
    "name": "Hello react!",
    "description": "React Chrome Extension",
    "version": "1.0",
    "manifest_version": 3,
    "action": {
        "default_popup": "index.html",
        "default_icon": "hi.png"
    }
}

运行命令生成文件,可以看到hi.png和manifest.json这些在public目录下的文件都被复制过来了

➜  my-react-hw npm install
➜  my-react-hw cd dist
➜  dist ls
assets        hi.png        index.html    manifest.json vite.svg

chrome://extensions/中加载生成的dist目录,然后运行,效果如下图

5

接下来

接下来,就需要学习chrome插件可以读写chrome宿主的哪写数据,拥有chrome的哪些功能了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容