vlambda博客
学习文章列表

开源一款好用的AJAX和FETCH拦截器

因为手里的一个项目需要获取一个第三方软件的数据,但是他们不提供数据库的直接访问,且其提供的api接口能力有限,于是只好另辟蹊径,通过浏览器扩展插件进行web请求和响应的拦截。

大致思路如下:

通过浏览器扩展插件技术将做了monkey patch的ajax和fetch脚本注入到需要拦截web请求和响应的页面,那么这个页面上的window下原有的XMLHttpRequest和fetch便会被我们修改过的ajax和fetch替代。结果页面上的每个ajax和fetch请求和响应都会先通过我们挂载的拦截器函数的处理,然后在发送出去或者接收回页面。

这个思路是通用的,适用于一切的可以加载chrome扩展的web应用。当然,我想如果App在打包时可以注入用于拦截的javascript到webkit浏览器,也是可以进行web请求拦截的。

开源的代码在我的gitee仓库下。(点这里访问)本项目以MIT许可开放。

这只是解决了ajax,还有fetch的需要处理。这部分只好自己手搓一个了。

核心代码在src\fetch.js中。

使用方式如下:

1. 安装
- 下载这个git仓库。
- 运行 `npm run build`
- 拦截ajax, 需要使用`dist`目录下的`ajaxhook.ming.js`.
```html <script src="dist/ajaxhook.min.js"></script> ```
- 拦截fetch需要使用`dist`下的`fetchhook.ming.js`.
```html <script src="dist/ajaxhook.min.js"></script> ```
2. 使用
- 用`proxy`拦截ajax:
```javascript
ah.proxy({ //请求发起前进入 onRequest: (config, handler) => { console.log(config.url) handler.next(config); }, //请求成功后进入 onResponse: (response, handler) => { console.log(response.response) handler.next(response) }, //请求发生错误时进入,比如超时;注意,不包括http状态码错误,如404仍然会认为请求成功 onError: (err, handler) => { console.log(err.type) handler.next(err) } }) ```
- 用`hookFetch`拦截fetch:
```javascript
fh.hookFetch({ requestInterceptors: { // input is usually url, init is of Request entity. itc1: function (input, init){ .... do something return init }, itc2: function (input, init){ .... do something return init }, }, responseInterceptors: { // input is usually url, interceptorRes is of Response body. itc3: function (input, interceptorRes){ .... do something return interceptorRes }, itc4: function (input, interceptorRes){ .... do something return interceptorRes }, }    })

    欢迎下载ajax-fetch-interceptor使用,也欢迎提交Pull Request。