抓包与改包 API(wad.net.*)
读取宿主的 Network 捕获记录、按 id 取响应体、增删改包规则。面板与逻辑层的调用形式不同:
| 面板 | 逻辑层 | |
|---|---|---|
records | Promise | 同步返回数组 |
body | Promise | 不支持(用 records 里的摘要) |
addRule / removeRule | Promise,返回结果 | 投递,立即返回 true |
rules | Promise | 不支持 |
渲染层没有 wad.net。
API
| 方法 | 签名 | 说明 |
|---|---|---|
wad.net.records | records(n?) → Promise<Record[]> | 最近 n 条(默认 50)请求摘要 |
wad.net.body | body(id) → Promise<string> | 按请求 id 取响应体 |
wad.net.rules | rules() → Promise<Rule[]> | 本插件 owner 的规则 |
wad.net.addRule | addRule(rule) → Promise<Rule> | 新增改包规则 |
wad.net.removeRule | removeRule(id) → Promise | 删除规则 |
Record 结构
js
{
id: 'r_169...', // 请求 id(net.body 用)
url: 'https://...',
method: 'GET',
status: 200, // WS 没有
kind: 'http' | 'ws',
ws: false,
dir: 'req' | 'resp', // WS 方向
len: 1234, // 响应字节数
at: 1699999999999
}最近失败的请求
js
const records = await wad.net.records(100);
const failed = records.filter(function (r) {
return r.kind === 'http' && r.status >= 400;
});
failed.forEach(function (r) {
console.log(r.status, r.method, r.url);
});取某个请求的响应体
js
const records = await wad.net.records(200);
const hit = records.find(function (r) {
return r.url.indexOf('/api/user/profile') >= 0 && r.status === 200;
});
if (hit) {
const body = await wad.net.body(hit.id);
render(JSON.parse(body));
}先开捕获
net.body 只能取到已经捕获的请求。没有记录会 reject NotFound。
改包规则
js
// ① 命中条件
rule.match = {
url: 'contains:/api/pay', // contains: / prefix: / regex: / 精确串
method: 'POST', // 可选
status: 200 // 可选(响应侧)
};
// ② 响应动作
rule.response = {
setBody: '{"code":0}',
setStatus: 200,
setHeader: { 'x-wad': '1' }
};
// ③ 请求动作
rule.request = {
setUrl: 'https://other.host/api/pay',
setHeader: { 'x-debug': '1' }
};一键 mock
js
const rule = await wad.net.addRule({
match: { url: 'contains:/api/vip/check' },
response: { setBody: JSON.stringify({ code: 0, vip: true }), setStatus: 200 }
});
wad.log('规则已生效', rule.id);
// 恢复
await wad.net.removeRule(rule.id);注意
rules()只返回本插件创建的规则,看不到别的插件;- 改包在宿主网络栈生效,重开小程序后仍生效,直到
removeRule或卸载插件; - 卸载插件时宿主会清掉该插件名下的全部规则;
- 想实时观察新请求,用事件
wad.on('network', ...),不要轮询; - 不写插件也能改包:Network 页的脚本 / 重写是独立工具,见 Network 脚本与重写。
完整示例:接口失败告警
html
<script type="text/wad-logic">
wad.on('network', function (e) {
if (e.kind === 'http' && e.status >= 500) {
wad.emit('alert', { url: e.url, status: e.status });
}
});
</script>
<script>
wad.ready.then(function () {
wad.on('alert', function (a) {
wad.ui.toast('服务异常 ' + a.status);
});
});
</script>