通过插件 · 网络脚本
插件通过 capture.intercept 注册 JS 回调,在 wx.request / uploadFile / downloadFile 执行前后改写请求或响应。
- 请求回调:请求真正发出前
- 响应回调:响应交给业务前
- 与免插件的 Network 脚本共用同一套
req/resp契约
注册
js
// 逻辑层
wadLogicLayer.capture.intercept.request(function (req) {
if (req.url.indexOf('/api/order') < 0) return;
req.header = Object.assign({}, req.header, { 'x-debug': '1' });
return req;
});
wadLogicLayer.capture.intercept.response(function (resp) {
if (!resp.req || resp.req.url.indexOf('/api/vip/check') < 0) return;
if (typeof resp.data === 'string') {
resp.data = resp.data.replace('"vip":false', '"vip":true');
}
return resp;
});返回值:
| 返回 | 行为 |
|---|---|
undefined / null / '' | 不修改,继续下一个 hook |
| 对象 | 采纳可写字段 |
| 其他类型 | 记日志,忽略 |
| 抛异常 | 请求不发出 / 响应替换为错误 JSON |
req 对象
| 字段 | 可写 | 说明 |
|---|---|---|
id / appid / kind | ❌ | 请求标识 |
url | ✅ | 请求 URL |
method | ✅ | 方法 |
header | ✅ | 请求头对象 |
data | ✅ | 请求体;JSON 时可能是对象 |
dataType | ✅ | 默认 json |
responseType | ✅ | text / arraybuffer |
timeout | ✅ | 毫秒 |
filePath / name / formData | ✅ | upload/download |
resp 对象
| 字段 | 可写 | 说明 |
|---|---|---|
id / appid / kind | ❌ | 对应请求 |
req | ❌ | 最终请求对象 |
statusCode | ✅ | HTTP 状态码 |
header | ✅ | 响应头 |
data | ✅ | 响应体(JSON 解析后 / 文本 / ArrayBuffer) |
errMsg | ✅ | 写回 wx 回调 |
tempFilePath | ✅ | download 临时文件 |
只读观察
用 capture.watch(fn) 订阅网络摘要,不阻断/改写:
js
const off = wadLogicLayer.capture.watch(function (d) {
wadLogicLayer.log('[net]', d.method, d.url, d.status);
});
// off();与重写规则的分工
- 简单替换/改状态码/改 URL:用 通过插件 · 网络重写
- 需要计算、解析 JSON、按条件分支:用本页的 JS 脚本
- 两者可同时存在,规则先执行,脚本后执行