Post

chome扩展开发快速入门

本文简单介绍chrome扩展开发流程

首先贴上官网链接

1. chrome扩展是什么

chrome扩展就是chrome内核的浏览器插件开发,可以增强浏览器或者网页功能

2. 简单介绍一下

chrome扩展使用js进行开发, 开发流程和传统js一致。 主要是manifest.json文件,这个文件是开发入口。

扩展主要需要两部分代码:

一部分为注入代码,就是讲业务js注入到目标网站中。

第二部分为后台运行代码,此部分代码一般为后台业务处理代码,比如浏览器网络拦截修改,下载请求拦截修改等等

3. 一个简单的项目展示

这里有一个简单的项目,整个项目只有4个文件,项目结构如下图

image

上图的manifest.json文件中,有以下定义:

  • 定义了后台处理业务为downloadworker.js. 这个js将会有一个线程异步执行。
  • 定义了权限申明 ,需要downloades权限
  • 定义了后台线程将会适用于所有域名

接下来是downloadworker.js代码:

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
import './biz.js';

var dinfo = {
    id:0,
    url:'',
    filename:'',
    data:undefined
    
};

chrome.downloads.onChanged.addListener(async (downloadItem) => {
    if(downloadItem.filename && downloadItem.filename.current.indexOf(".xlsx") > 0) {
        // dinfo.id = downloadItem.id
        dinfo.filename = downloadItem.filename.current

         // Fetch the file content to process it before re-downloading
      if(dinfo.filename && dinfo.filename.indexOf(".xlsx") > 0) {
        fetch(dinfo.url)
        .then(response => response.blob())
        .then(blob => {
            blob.arrayBuffer().then(buffer => {
                let uint = [...new Uint8Array(buffer)];
                console.log(blob,uint,JSON.stringify(uint))

                let url = 'http://127.0.0.1:17535/proxy/fileproxy';
                dinfo.data = uint
                let options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(dinfo),
                }
                fetch(url, options)
                .then((response) => response.json())
                .then((data) => console.log(data))
                .catch((e) => console.log('error', e));

            });
 
    });
}
    }
});

// A download is detected when a download event is created
chrome.downloads.onCreated.addListener(async (downloadItem) => {
    console.log("Download started:", downloadItem);
    dinfo.id = downloadItem.id;
     dinfo.url = downloadItem.url;
      
  });

这里的代码定义了浏览器下载事件,在浏览器下载excel文件时, 使用js代码再下载一份并上传到服务器。

里面的biz.js没有任何代码。

接下来讲解如何调试:

image

首先在chrome扩展管理中打开右上角开发者模式,然后再点击左上角加载未打包的扩展程序(直接选择项目目录)。

然后确定,就可以看到下图:

image

在这里可以看到插件被正常加载了, 点击检查视图 将会弹出debug窗口,在这里可以debug项目代码以及看到项目日志输出。

接着就可以去点击任意一个网站的下载按钮,并同步调试。

这样一个简单的chrome扩展就开发完成了。

This post is licensed under CC BY 4.0 by the author.