@xbrowser/cli 1.28.0 → 1.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
- package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
- package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
- package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
- package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
- package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
- package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
- package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
- package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
- package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
- package/dist/cli.js +3447 -3377
- package/dist/daemon-main.js +1240 -786
- package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
- package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
- package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
- package/dist/index.d.ts +458 -476
- package/dist/index.js +3766 -3576
- package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
- package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
- package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
- package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
- package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
- package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
- package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
- package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
- package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
- package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
- package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
- package/package.json +9 -3
|
@@ -9,11 +9,11 @@ import {
|
|
|
9
9
|
landingOffset,
|
|
10
10
|
rand,
|
|
11
11
|
typingDelay
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-SMYSNO4M.js";
|
|
13
13
|
import {
|
|
14
14
|
connectToCDP,
|
|
15
15
|
launchChrome
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-2KPI5GKP.js";
|
|
17
17
|
import {
|
|
18
18
|
errMsg
|
|
19
19
|
} from "./chunk-GDKLH7ZY.js";
|
|
@@ -34,12 +34,16 @@ import { EventEmitter as EventEmitter2 } from "events";
|
|
|
34
34
|
import { EventEmitter } from "events";
|
|
35
35
|
|
|
36
36
|
// src/cdp-driver/mouse.ts
|
|
37
|
+
function buttonBit(button) {
|
|
38
|
+
return button === "left" ? 1 : button === "right" ? 2 : 4;
|
|
39
|
+
}
|
|
37
40
|
var XBMouseImpl = class {
|
|
38
41
|
conn;
|
|
39
42
|
sessionId;
|
|
40
43
|
_x = 0;
|
|
41
44
|
_y = 0;
|
|
42
45
|
_button = "none";
|
|
46
|
+
_buttons = 0;
|
|
43
47
|
constructor(conn, sessionId) {
|
|
44
48
|
this.conn = conn;
|
|
45
49
|
this.sessionId = sessionId;
|
|
@@ -70,7 +74,7 @@ var XBMouseImpl = class {
|
|
|
70
74
|
_truncated = true;
|
|
71
75
|
break;
|
|
72
76
|
}
|
|
73
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
|
|
77
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button, buttons: this._buttons });
|
|
74
78
|
this._x = p.x;
|
|
75
79
|
this._y = p.y;
|
|
76
80
|
await sleep(p.delay);
|
|
@@ -78,7 +82,7 @@ var XBMouseImpl = class {
|
|
|
78
82
|
this._x = tx;
|
|
79
83
|
this._y = ty;
|
|
80
84
|
if (_truncated) {
|
|
81
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
|
|
85
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button, buttons: this._buttons });
|
|
82
86
|
}
|
|
83
87
|
await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
|
|
84
88
|
} else {
|
|
@@ -90,7 +94,7 @@ var XBMouseImpl = class {
|
|
|
90
94
|
const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
|
|
91
95
|
this._x = rx;
|
|
92
96
|
this._y = ry;
|
|
93
|
-
await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
|
|
97
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, buttons: this._buttons, clickCount: opts.clickCount ?? 1 });
|
|
94
98
|
for (let i = 1; i < (opts.clickCount ?? 1); i++) {
|
|
95
99
|
if (opts.delay) await sleep(opts.delay);
|
|
96
100
|
await this.down({ button });
|
|
@@ -103,11 +107,13 @@ var XBMouseImpl = class {
|
|
|
103
107
|
async down(opts = {}) {
|
|
104
108
|
const button = opts.button ?? "left";
|
|
105
109
|
this._button = button;
|
|
110
|
+
this._buttons |= buttonBit(button);
|
|
106
111
|
await this.send("Input.dispatchMouseEvent", {
|
|
107
112
|
type: "mousePressed",
|
|
108
113
|
x: this._x,
|
|
109
114
|
y: this._y,
|
|
110
115
|
button,
|
|
116
|
+
buttons: this._buttons,
|
|
111
117
|
// r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
|
|
112
118
|
// 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
|
|
113
119
|
clickCount: opts.clickCount ?? 1
|
|
@@ -121,8 +127,11 @@ var XBMouseImpl = class {
|
|
|
121
127
|
x: this._x,
|
|
122
128
|
y: this._y,
|
|
123
129
|
button,
|
|
130
|
+
// release 先带位发送再清位(Puppeteer 同序——DOM mouseup 的 buttons 反映释放后状态)
|
|
131
|
+
buttons: this._buttons,
|
|
124
132
|
clickCount: opts.clickCount ?? 1
|
|
125
133
|
});
|
|
134
|
+
this._buttons &= ~buttonBit(button);
|
|
126
135
|
}
|
|
127
136
|
async move(x, y, opts = {}) {
|
|
128
137
|
const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
|
|
@@ -140,7 +149,8 @@ var XBMouseImpl = class {
|
|
|
140
149
|
type: "mouseMoved",
|
|
141
150
|
x: this._x,
|
|
142
151
|
y: this._y,
|
|
143
|
-
button: this._button
|
|
152
|
+
button: this._button,
|
|
153
|
+
buttons: this._buttons
|
|
144
154
|
});
|
|
145
155
|
}
|
|
146
156
|
this._x = x;
|
|
@@ -160,9 +170,11 @@ var XBMouseImpl = class {
|
|
|
160
170
|
x: this._x,
|
|
161
171
|
y: this._y,
|
|
162
172
|
button: "left",
|
|
173
|
+
buttons: 1,
|
|
163
174
|
clickCount: 1
|
|
164
175
|
});
|
|
165
176
|
this._button = "left";
|
|
177
|
+
this._buttons |= 1;
|
|
166
178
|
const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
|
|
167
179
|
const fx = this._x, fy = this._y;
|
|
168
180
|
for (let i = 1; i <= steps; i++) {
|
|
@@ -174,7 +186,8 @@ var XBMouseImpl = class {
|
|
|
174
186
|
type: "mouseMoved",
|
|
175
187
|
x: this._x,
|
|
176
188
|
y: this._y,
|
|
177
|
-
button: this._button
|
|
189
|
+
button: this._button,
|
|
190
|
+
buttons: this._buttons
|
|
178
191
|
});
|
|
179
192
|
}
|
|
180
193
|
this._x = x;
|
|
@@ -185,15 +198,22 @@ var XBMouseImpl = class {
|
|
|
185
198
|
x,
|
|
186
199
|
y,
|
|
187
200
|
button: "left",
|
|
201
|
+
buttons: this._buttons,
|
|
188
202
|
clickCount: 1
|
|
189
203
|
});
|
|
190
204
|
this._button = "none";
|
|
205
|
+
this._buttons &= ~1;
|
|
206
|
+
}
|
|
207
|
+
async wheelAt(x, y, deltaX, deltaY) {
|
|
208
|
+
await this.move(x, y);
|
|
209
|
+
await this.wheel(deltaX, deltaY);
|
|
191
210
|
}
|
|
192
211
|
async wheel(deltaX, deltaY) {
|
|
193
212
|
await this.send("Input.dispatchMouseEvent", {
|
|
194
213
|
type: "mouseWheel",
|
|
195
214
|
x: this._x,
|
|
196
215
|
y: this._y,
|
|
216
|
+
buttons: this._buttons,
|
|
197
217
|
deltaX,
|
|
198
218
|
deltaY
|
|
199
219
|
});
|
|
@@ -1331,6 +1351,216 @@ var XBElementHandleImpl = class {
|
|
|
1331
1351
|
}
|
|
1332
1352
|
};
|
|
1333
1353
|
|
|
1354
|
+
// src/cdp-driver/page-media.ts
|
|
1355
|
+
var MediaService = class {
|
|
1356
|
+
constructor(options) {
|
|
1357
|
+
this.options = options;
|
|
1358
|
+
}
|
|
1359
|
+
options;
|
|
1360
|
+
async screenshot(opts = {}) {
|
|
1361
|
+
const params = {
|
|
1362
|
+
format: opts.type ?? "png"
|
|
1363
|
+
};
|
|
1364
|
+
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
1365
|
+
params.quality = opts.quality;
|
|
1366
|
+
}
|
|
1367
|
+
if (opts.fullPage) {
|
|
1368
|
+
params.captureBeyondViewport = true;
|
|
1369
|
+
}
|
|
1370
|
+
if (opts.clip) {
|
|
1371
|
+
const clip = {
|
|
1372
|
+
x: Math.round(opts.clip.x),
|
|
1373
|
+
y: Math.round(opts.clip.y),
|
|
1374
|
+
width: Math.round(Math.max(1, opts.clip.width)),
|
|
1375
|
+
height: Math.round(Math.max(1, opts.clip.height)),
|
|
1376
|
+
scale: opts.clip.scale ?? 1
|
|
1377
|
+
};
|
|
1378
|
+
params.clip = clip;
|
|
1379
|
+
}
|
|
1380
|
+
if (opts.omitBackground) {
|
|
1381
|
+
params.omitBackground = true;
|
|
1382
|
+
}
|
|
1383
|
+
const result = await this.options.conn.send(
|
|
1384
|
+
"Page.captureScreenshot",
|
|
1385
|
+
params,
|
|
1386
|
+
this.options.sessionId
|
|
1387
|
+
);
|
|
1388
|
+
return Buffer.from(result.data, "base64");
|
|
1389
|
+
}
|
|
1390
|
+
async pdf(opts = {}) {
|
|
1391
|
+
const params = {};
|
|
1392
|
+
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
1393
|
+
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
1394
|
+
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
1395
|
+
if (opts.format) params.paperFormat = opts.format;
|
|
1396
|
+
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
1397
|
+
if (opts.margin) {
|
|
1398
|
+
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
1399
|
+
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
1400
|
+
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
1401
|
+
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
1402
|
+
}
|
|
1403
|
+
const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
|
|
1404
|
+
return Buffer.from(result.data, "base64");
|
|
1405
|
+
}
|
|
1406
|
+
viewportSize() {
|
|
1407
|
+
return this.options.viewportSize ?? null;
|
|
1408
|
+
}
|
|
1409
|
+
async setViewportSize(size) {
|
|
1410
|
+
await this.options.conn.send(
|
|
1411
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1412
|
+
{
|
|
1413
|
+
width: size.width,
|
|
1414
|
+
height: size.height,
|
|
1415
|
+
deviceScaleFactor: 1,
|
|
1416
|
+
mobile: false
|
|
1417
|
+
},
|
|
1418
|
+
this.options.sessionId
|
|
1419
|
+
);
|
|
1420
|
+
this.options.onViewportSize(size);
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
1424
|
+
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
1425
|
+
*/
|
|
1426
|
+
async setDeviceScaleFactor(dsf) {
|
|
1427
|
+
const size = this.options.viewportSize ?? await this.options.evaluate(
|
|
1428
|
+
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
1429
|
+
);
|
|
1430
|
+
await this.options.conn.send(
|
|
1431
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1432
|
+
{
|
|
1433
|
+
width: size.width,
|
|
1434
|
+
height: size.height,
|
|
1435
|
+
deviceScaleFactor: dsf,
|
|
1436
|
+
mobile: false
|
|
1437
|
+
},
|
|
1438
|
+
this.options.sessionId
|
|
1439
|
+
);
|
|
1440
|
+
this.options.onViewportSize(size);
|
|
1441
|
+
}
|
|
1442
|
+
// ── Scripts ─────────────────────────────────────────────────
|
|
1443
|
+
};
|
|
1444
|
+
|
|
1445
|
+
// src/cdp-driver/page-file-input.ts
|
|
1446
|
+
var FileInputService = class {
|
|
1447
|
+
constructor(options) {
|
|
1448
|
+
this.options = options;
|
|
1449
|
+
}
|
|
1450
|
+
options;
|
|
1451
|
+
async dropFiles(selector, payload) {
|
|
1452
|
+
await this.options.evaluate(`
|
|
1453
|
+
(function() {
|
|
1454
|
+
var el = ${queryJS(selector)};
|
|
1455
|
+
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
1456
|
+
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
1457
|
+
var bin = atob(b64);
|
|
1458
|
+
var buf = new Uint8Array(bin.length);
|
|
1459
|
+
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
1460
|
+
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
1461
|
+
var dt = new DataTransfer();
|
|
1462
|
+
dt.items.add(file);
|
|
1463
|
+
var rect = el.getBoundingClientRect();
|
|
1464
|
+
var opts = {
|
|
1465
|
+
bubbles: true, cancelable: true,
|
|
1466
|
+
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
1467
|
+
};
|
|
1468
|
+
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
1469
|
+
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
1470
|
+
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
1471
|
+
})()
|
|
1472
|
+
`);
|
|
1473
|
+
}
|
|
1474
|
+
async setInputFiles(selector, files) {
|
|
1475
|
+
const fileArr = Array.isArray(files) ? files : [files];
|
|
1476
|
+
const fileList = fileArr.map((f) => ({
|
|
1477
|
+
name: f.name,
|
|
1478
|
+
type: f.mimeType,
|
|
1479
|
+
dataBase64: f.buffer.toString("base64")
|
|
1480
|
+
}));
|
|
1481
|
+
await this.options.evaluate(`
|
|
1482
|
+
(function() {
|
|
1483
|
+
var selector = ${JSON.stringify(selector)};
|
|
1484
|
+
var input = ${queryJS(selector)};
|
|
1485
|
+
if (!input) throw new Error('Element not found: ' + selector);
|
|
1486
|
+
|
|
1487
|
+
var fileList = ${JSON.stringify(fileList)};
|
|
1488
|
+
var dt = new DataTransfer();
|
|
1489
|
+
|
|
1490
|
+
fileList.forEach(function(f) {
|
|
1491
|
+
var binary = atob(f.dataBase64);
|
|
1492
|
+
var bytes = new Uint8Array(binary.length);
|
|
1493
|
+
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1494
|
+
var blob = new Blob([bytes], { type: f.type });
|
|
1495
|
+
var file = new File([blob], f.name, { type: f.type });
|
|
1496
|
+
dt.items.add(file);
|
|
1497
|
+
});
|
|
1498
|
+
|
|
1499
|
+
input.files = dt.files;
|
|
1500
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1501
|
+
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1502
|
+
})()
|
|
1503
|
+
`);
|
|
1504
|
+
}
|
|
1505
|
+
// ── dragAndDrop ─────────────────────────────────────────────
|
|
1506
|
+
async dragAndDrop(source, target) {
|
|
1507
|
+
const sourceRect = await this.options.evaluate(`
|
|
1508
|
+
(function() {
|
|
1509
|
+
const el = ${queryJS(source)};
|
|
1510
|
+
if (!el) throw new Error('Source not found: ${source}');
|
|
1511
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1512
|
+
const r = el.getBoundingClientRect();
|
|
1513
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1514
|
+
})()
|
|
1515
|
+
`);
|
|
1516
|
+
const targetRect = await this.options.evaluate(`
|
|
1517
|
+
(function() {
|
|
1518
|
+
const el = ${queryJS(target)};
|
|
1519
|
+
if (!el) throw new Error('Target not found: ${target}');
|
|
1520
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1521
|
+
const r = el.getBoundingClientRect();
|
|
1522
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1523
|
+
})()
|
|
1524
|
+
`);
|
|
1525
|
+
const sx = sourceRect.x + sourceRect.width / 2;
|
|
1526
|
+
const sy = sourceRect.y + sourceRect.height / 2;
|
|
1527
|
+
const tx = targetRect.x + targetRect.width / 2;
|
|
1528
|
+
const ty = targetRect.y + targetRect.height / 2;
|
|
1529
|
+
try {
|
|
1530
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1531
|
+
type: "dragStart",
|
|
1532
|
+
x: sx,
|
|
1533
|
+
y: sy,
|
|
1534
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1535
|
+
}, this.options.sessionId);
|
|
1536
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1537
|
+
type: "dragOver",
|
|
1538
|
+
x: tx,
|
|
1539
|
+
y: ty,
|
|
1540
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1541
|
+
}, this.options.sessionId);
|
|
1542
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1543
|
+
type: "drop",
|
|
1544
|
+
x: tx,
|
|
1545
|
+
y: ty,
|
|
1546
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1547
|
+
}, this.options.sessionId);
|
|
1548
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1549
|
+
type: "dragCancel",
|
|
1550
|
+
x: sx,
|
|
1551
|
+
y: sy,
|
|
1552
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1553
|
+
}, this.options.sessionId);
|
|
1554
|
+
} catch {
|
|
1555
|
+
await this.options.mouse.move(sx, sy);
|
|
1556
|
+
await this.options.mouse.down();
|
|
1557
|
+
await this.options.mouse.move(tx, ty, { steps: 10 });
|
|
1558
|
+
await this.options.mouse.up();
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
// ── setOfflineMode ──────────────────────────────────────────
|
|
1562
|
+
};
|
|
1563
|
+
|
|
1334
1564
|
// src/cdp-driver/page-helpers.ts
|
|
1335
1565
|
function globToRegex(glob) {
|
|
1336
1566
|
let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
|
|
@@ -1482,65 +1712,1078 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
|
|
|
1482
1712
|
};
|
|
1483
1713
|
}
|
|
1484
1714
|
|
|
1485
|
-
// src/cdp-driver/page.ts
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
_viewportSize = null;
|
|
1498
|
-
_loadState = {
|
|
1499
|
-
loadFired: true,
|
|
1500
|
-
domContentFired: true,
|
|
1501
|
-
networkIdle: true
|
|
1502
|
-
};
|
|
1503
|
-
mouse;
|
|
1504
|
-
keyboard;
|
|
1505
|
-
// Network tracking for waitForLoadState('networkidle')
|
|
1506
|
-
inflightRequests = /* @__PURE__ */ new Set();
|
|
1507
|
-
networkIdleResolve = null;
|
|
1508
|
-
networkIdleTimer = null;
|
|
1509
|
-
static NETWORK_IDLE_MS = 500;
|
|
1510
|
-
constructor(conn, sessionId, targetId, context, browser) {
|
|
1511
|
-
this.conn = conn;
|
|
1512
|
-
this.sessionId = sessionId;
|
|
1513
|
-
this._targetId = targetId;
|
|
1514
|
-
this._contextImpl = context;
|
|
1515
|
-
this._browserImpl = browser;
|
|
1516
|
-
this.mouse = new XBMouseImpl(conn, sessionId);
|
|
1517
|
-
this.keyboard = new XBKeyboardImpl(conn, sessionId);
|
|
1518
|
-
}
|
|
1519
|
-
_emit(event, ...args) {
|
|
1520
|
-
this._emitter.emit(event, ...args);
|
|
1521
|
-
}
|
|
1522
|
-
/** Internal initialization — must be called after construction */
|
|
1523
|
-
async _init() {
|
|
1524
|
-
await this.conn.send("Page.enable", void 0, this.sessionId);
|
|
1525
|
-
await this.conn.send("Runtime.enable", void 0, this.sessionId);
|
|
1526
|
-
await this.conn.send("Network.enable", void 0, this.sessionId);
|
|
1527
|
-
await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
|
|
1528
|
-
});
|
|
1529
|
-
if (this._contextImpl.ignoreHTTPSErrors) {
|
|
1530
|
-
await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
|
|
1715
|
+
// src/cdp-driver/page-network-events.ts
|
|
1716
|
+
function setupNetworkEvents(options) {
|
|
1717
|
+
options.addSubscription(
|
|
1718
|
+
options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
|
|
1719
|
+
const p = params;
|
|
1720
|
+
options.state.inflightRequests.add(p.requestId);
|
|
1721
|
+
options.storeRequest(p.requestId, {
|
|
1722
|
+
url: p.request.url,
|
|
1723
|
+
method: p.request.method,
|
|
1724
|
+
headers: p.request.headers,
|
|
1725
|
+
postData: p.request.postData ?? null,
|
|
1726
|
+
resourceType: p.type
|
|
1531
1727
|
});
|
|
1532
|
-
|
|
1728
|
+
options.emit("request", createXBRequest(
|
|
1729
|
+
null,
|
|
1730
|
+
{
|
|
1731
|
+
requestId: p.requestId,
|
|
1732
|
+
url: p.request.url,
|
|
1733
|
+
method: p.request.method,
|
|
1734
|
+
headers: p.request.headers,
|
|
1735
|
+
postData: p.request.postData ?? null,
|
|
1736
|
+
resourceType: p.type
|
|
1737
|
+
}
|
|
1738
|
+
));
|
|
1739
|
+
options.checkNetworkIdle();
|
|
1740
|
+
})
|
|
1741
|
+
);
|
|
1742
|
+
options.addSubscription(
|
|
1743
|
+
options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
|
|
1744
|
+
const p = params;
|
|
1745
|
+
options.storeResponse(p.requestId, {
|
|
1746
|
+
status: p.response.status,
|
|
1747
|
+
url: p.response.url,
|
|
1748
|
+
headers: p.response.headers
|
|
1533
1749
|
});
|
|
1750
|
+
options.emit("response", createXBResponse(
|
|
1751
|
+
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
1752
|
+
options.conn,
|
|
1753
|
+
options.sessionId
|
|
1754
|
+
));
|
|
1755
|
+
})
|
|
1756
|
+
);
|
|
1757
|
+
options.addSubscription(
|
|
1758
|
+
options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
|
|
1759
|
+
const p = params;
|
|
1760
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1761
|
+
options.emit("requestfinished", p);
|
|
1762
|
+
options.checkNetworkIdle();
|
|
1763
|
+
})
|
|
1764
|
+
);
|
|
1765
|
+
options.addSubscription(
|
|
1766
|
+
options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
|
|
1767
|
+
const p = params;
|
|
1768
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1769
|
+
options.checkNetworkIdle();
|
|
1770
|
+
})
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
// src/cdp-driver/page-lifecycle-events.ts
|
|
1775
|
+
function setupPageEvents(options) {
|
|
1776
|
+
options.addSubscription(
|
|
1777
|
+
options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
|
|
1778
|
+
const p = params;
|
|
1779
|
+
if (p.frame) {
|
|
1780
|
+
options.setUrl(p.frame.url);
|
|
1781
|
+
}
|
|
1782
|
+
options.emit("framenavigated", options.mainFrame());
|
|
1783
|
+
})
|
|
1784
|
+
);
|
|
1785
|
+
options.addSubscription(
|
|
1786
|
+
options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
|
|
1787
|
+
options.markLoadFired();
|
|
1788
|
+
})
|
|
1789
|
+
);
|
|
1790
|
+
options.addSubscription(
|
|
1791
|
+
options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
|
|
1792
|
+
options.markDomContentFired();
|
|
1793
|
+
})
|
|
1794
|
+
);
|
|
1795
|
+
options.addSubscription(
|
|
1796
|
+
options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
|
|
1797
|
+
const p = params;
|
|
1798
|
+
const dialog = {
|
|
1799
|
+
type: p.type,
|
|
1800
|
+
message: () => p.message,
|
|
1801
|
+
defaultValue: () => p.defaultValue,
|
|
1802
|
+
accept: async (text) => {
|
|
1803
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1804
|
+
accept: true,
|
|
1805
|
+
promptText: text
|
|
1806
|
+
}, options.sessionId);
|
|
1807
|
+
},
|
|
1808
|
+
dismiss: async () => {
|
|
1809
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1810
|
+
accept: false
|
|
1811
|
+
}, options.sessionId);
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
options.emit("dialog", dialog);
|
|
1815
|
+
const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
|
|
1816
|
+
setTimeout(() => {
|
|
1817
|
+
options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
|
|
1818
|
+
});
|
|
1819
|
+
}, 0);
|
|
1820
|
+
})
|
|
1821
|
+
);
|
|
1822
|
+
options.addSubscription(
|
|
1823
|
+
options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
|
|
1824
|
+
const p = params;
|
|
1825
|
+
let selector = "";
|
|
1826
|
+
try {
|
|
1827
|
+
const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1828
|
+
const attrs = result.node?.attributes || [];
|
|
1829
|
+
const idIdx = attrs.indexOf("id");
|
|
1830
|
+
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
1831
|
+
} catch {
|
|
1832
|
+
}
|
|
1833
|
+
if (!selector) {
|
|
1834
|
+
try {
|
|
1835
|
+
const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1836
|
+
const evalResult = await options.conn.send("Runtime.callFunctionOn", {
|
|
1837
|
+
objectId: result.objectId,
|
|
1838
|
+
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
1839
|
+
returnByValue: true
|
|
1840
|
+
}, options.sessionId);
|
|
1841
|
+
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
1842
|
+
} catch {
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
const fileChooser = {
|
|
1846
|
+
selector,
|
|
1847
|
+
isMultiple: p.mode === "selectMultiple",
|
|
1848
|
+
setFiles: async (files) => {
|
|
1849
|
+
const fileArray = Array.isArray(files) ? files : [files];
|
|
1850
|
+
await options.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
1851
|
+
}
|
|
1852
|
+
};
|
|
1853
|
+
options.emit("filechooser", fileChooser);
|
|
1854
|
+
})
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
// src/cdp-driver/page-network-waits.ts
|
|
1859
|
+
var NetworkWaitService = class {
|
|
1860
|
+
constructor(options) {
|
|
1861
|
+
this.options = options;
|
|
1862
|
+
}
|
|
1863
|
+
options;
|
|
1864
|
+
// ── waitForResponse ─────────────────────────────────────────
|
|
1865
|
+
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
1866
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1867
|
+
const predicate = createResponsePredicate(urlOrPredicate);
|
|
1868
|
+
for (const [, data] of this.options.responses) {
|
|
1869
|
+
const response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1870
|
+
if (predicate(response)) return response;
|
|
1534
1871
|
}
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1872
|
+
return new Promise((resolve, reject) => {
|
|
1873
|
+
const timer = setTimeout(() => {
|
|
1874
|
+
this.options.off("response", handler);
|
|
1875
|
+
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
1876
|
+
}, timeout);
|
|
1877
|
+
const handler = (params) => {
|
|
1878
|
+
let response;
|
|
1879
|
+
const respObj = params;
|
|
1880
|
+
if (respObj.response) {
|
|
1881
|
+
const data = {
|
|
1882
|
+
requestId: respObj.requestId || "",
|
|
1883
|
+
status: respObj.response.status || 0,
|
|
1884
|
+
url: respObj.response.url || "",
|
|
1885
|
+
headers: respObj.response.headers || {}
|
|
1886
|
+
};
|
|
1887
|
+
response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1888
|
+
} else if (typeof params.status === "function") {
|
|
1889
|
+
response = params;
|
|
1890
|
+
} else {
|
|
1891
|
+
return;
|
|
1892
|
+
}
|
|
1893
|
+
if (predicate(response)) {
|
|
1894
|
+
clearTimeout(timer);
|
|
1895
|
+
this.options.off("response", handler);
|
|
1896
|
+
resolve(response);
|
|
1897
|
+
}
|
|
1898
|
+
};
|
|
1899
|
+
this.options.on("response", handler);
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
// ── waitForRequest ──────────────────────────────────────────
|
|
1903
|
+
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
1904
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1905
|
+
const predicate = createRequestPredicate(urlOrPredicate);
|
|
1906
|
+
for (const [, data] of this.options.requests) {
|
|
1907
|
+
const request = createXBRequest(this.pageLike(), data);
|
|
1908
|
+
if (predicate(request)) return request;
|
|
1909
|
+
}
|
|
1910
|
+
return new Promise((resolve, reject) => {
|
|
1911
|
+
const timer = setTimeout(() => {
|
|
1912
|
+
this.options.off("request", handler);
|
|
1913
|
+
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
1914
|
+
}, timeout);
|
|
1915
|
+
const handler = (params) => {
|
|
1916
|
+
let request;
|
|
1917
|
+
const reqObj = params;
|
|
1918
|
+
if (reqObj.request) {
|
|
1919
|
+
request = createXBRequest(this.pageLike(), {
|
|
1920
|
+
requestId: reqObj.requestId || "",
|
|
1921
|
+
url: reqObj.request.url || "",
|
|
1922
|
+
method: reqObj.request.method || "",
|
|
1923
|
+
headers: reqObj.request.headers || {},
|
|
1924
|
+
postData: reqObj.request.postData ?? null,
|
|
1925
|
+
resourceType: reqObj.type || ""
|
|
1926
|
+
});
|
|
1927
|
+
} else if (typeof params.url === "function") {
|
|
1928
|
+
request = params;
|
|
1929
|
+
} else {
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
if (predicate(request)) {
|
|
1933
|
+
clearTimeout(timer);
|
|
1934
|
+
this.options.off("request", handler);
|
|
1935
|
+
resolve(request);
|
|
1936
|
+
}
|
|
1937
|
+
};
|
|
1938
|
+
this.options.on("request", handler);
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
// ── waitForURL ──────────────────────────────────────────────
|
|
1942
|
+
async waitForURL(url, opts = {}) {
|
|
1943
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1944
|
+
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
1945
|
+
if (checkFn(this.options.currentUrl())) return;
|
|
1946
|
+
return new Promise((resolve, reject) => {
|
|
1947
|
+
const timer = setTimeout(() => {
|
|
1948
|
+
this.options.off("framenavigated", handler);
|
|
1949
|
+
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
1950
|
+
}, timeout);
|
|
1951
|
+
const handler = () => {
|
|
1952
|
+
if (checkFn(this.options.currentUrl())) {
|
|
1953
|
+
clearTimeout(timer);
|
|
1954
|
+
this.options.off("framenavigated", handler);
|
|
1955
|
+
resolve();
|
|
1956
|
+
}
|
|
1957
|
+
};
|
|
1958
|
+
this.options.on("framenavigated", handler);
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
pageLike() {
|
|
1962
|
+
return {
|
|
1963
|
+
_networkResponses: this.options.responses,
|
|
1964
|
+
_connection: this.options.conn,
|
|
1965
|
+
sessionId: this.options.sessionId
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
};
|
|
1969
|
+
|
|
1970
|
+
// src/cdp-driver/page-routes.ts
|
|
1971
|
+
var NetworkRouteService = class {
|
|
1972
|
+
constructor(options) {
|
|
1973
|
+
this.options = options;
|
|
1974
|
+
}
|
|
1975
|
+
options;
|
|
1976
|
+
routeHandlers = [];
|
|
1977
|
+
interceptionEnabled = false;
|
|
1978
|
+
get isInterceptionEnabled() {
|
|
1979
|
+
return this.interceptionEnabled;
|
|
1980
|
+
}
|
|
1981
|
+
subscriptions = [];
|
|
1982
|
+
async route(url, handler) {
|
|
1983
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
1984
|
+
this.routeHandlers.push({ pattern: String(url), regex, handler });
|
|
1985
|
+
if (!this.interceptionEnabled) {
|
|
1986
|
+
this.interceptionEnabled = true;
|
|
1987
|
+
await this.options.conn.send("Fetch.enable", {
|
|
1988
|
+
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
1989
|
+
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
1990
|
+
// 会顶掉 _init 的 auth 配置)
|
|
1991
|
+
handleAuthRequests: true
|
|
1992
|
+
}, this.options.sessionId);
|
|
1993
|
+
this.subscriptions.push(
|
|
1994
|
+
this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
|
|
1995
|
+
this._handleRequestPaused(params);
|
|
1996
|
+
})
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
async unroute(url, handler) {
|
|
2001
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2002
|
+
this.routeHandlers = this.routeHandlers.filter(
|
|
2003
|
+
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2004
|
+
);
|
|
2005
|
+
if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
|
|
2006
|
+
this.interceptionEnabled = false;
|
|
2007
|
+
await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
|
|
2008
|
+
});
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
async _handleRequestPaused(params) {
|
|
2012
|
+
const requestUrl = params.request.url;
|
|
2013
|
+
for (const { regex, handler } of this.routeHandlers) {
|
|
2014
|
+
if (regex.test(requestUrl)) {
|
|
2015
|
+
this.options.emit("request", createXBRequest(
|
|
2016
|
+
null,
|
|
2017
|
+
{
|
|
2018
|
+
requestId: params.requestId,
|
|
2019
|
+
url: params.request.url,
|
|
2020
|
+
method: params.request.method,
|
|
2021
|
+
headers: params.request.headers,
|
|
2022
|
+
postData: params.request.postData ?? null,
|
|
2023
|
+
resourceType: params.resourceType
|
|
2024
|
+
}
|
|
2025
|
+
));
|
|
2026
|
+
const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
|
|
2027
|
+
try {
|
|
2028
|
+
await handler(route);
|
|
2029
|
+
} catch {
|
|
2030
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2031
|
+
requestId: params.requestId
|
|
2032
|
+
}, this.options.sessionId).catch(() => {
|
|
2033
|
+
});
|
|
2034
|
+
}
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2039
|
+
requestId: params.requestId
|
|
2040
|
+
}, this.options.sessionId).catch(() => {
|
|
2041
|
+
});
|
|
2042
|
+
}
|
|
2043
|
+
};
|
|
2044
|
+
|
|
2045
|
+
// src/cdp-driver/page-navigation.ts
|
|
2046
|
+
var NavigationService = class {
|
|
2047
|
+
constructor(options) {
|
|
2048
|
+
this.options = options;
|
|
2049
|
+
}
|
|
2050
|
+
options;
|
|
2051
|
+
async goto(url, opts = {}) {
|
|
2052
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2053
|
+
const waitUntil = opts.waitUntil ?? "load";
|
|
2054
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2055
|
+
this.options.state.loadFired = false;
|
|
2056
|
+
this.options.state.domContentFired = false;
|
|
2057
|
+
this.options.state.networkIdle = false;
|
|
2058
|
+
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
2059
|
+
try {
|
|
2060
|
+
await this.options.conn.send(
|
|
2061
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2062
|
+
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
|
|
2063
|
+
this.options.sessionId
|
|
2064
|
+
);
|
|
2065
|
+
} catch {
|
|
2066
|
+
}
|
|
2067
|
+
try {
|
|
2068
|
+
const rawUa = await this.options.conn.send(
|
|
2069
|
+
"Runtime.evaluate",
|
|
2070
|
+
{ expression: "navigator.userAgent", returnByValue: true },
|
|
2071
|
+
this.options.sessionId
|
|
2072
|
+
);
|
|
2073
|
+
const ua = rawUa?.value || "";
|
|
2074
|
+
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
2075
|
+
if (cleaned !== ua) {
|
|
2076
|
+
await this.options.conn.send(
|
|
2077
|
+
"Network.setUserAgentOverride",
|
|
2078
|
+
{ userAgent: cleaned },
|
|
2079
|
+
this.options.sessionId
|
|
2080
|
+
);
|
|
2081
|
+
}
|
|
2082
|
+
} catch {
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
const result = await this.options.conn.send(
|
|
2086
|
+
"Page.navigate",
|
|
2087
|
+
{ url, referrer: opts.referer },
|
|
2088
|
+
this.options.sessionId
|
|
2089
|
+
);
|
|
2090
|
+
if (result.errorText) {
|
|
2091
|
+
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
2092
|
+
}
|
|
2093
|
+
if (waitUntil === "commit") {
|
|
2094
|
+
this.options.setUrl(url);
|
|
2095
|
+
return {
|
|
2096
|
+
status: () => 0,
|
|
2097
|
+
ok: () => false,
|
|
2098
|
+
url: () => url,
|
|
2099
|
+
headers: () => ({})
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
await this.options.waitForLoadState(waitUntil, timeout);
|
|
2103
|
+
this.options.setUrl(url);
|
|
2104
|
+
const statusCode = 200;
|
|
2105
|
+
const finalUrl = url;
|
|
2106
|
+
const headers = {};
|
|
2107
|
+
return {
|
|
2108
|
+
status: () => statusCode,
|
|
2109
|
+
ok: () => statusCode >= 200 && statusCode < 300,
|
|
2110
|
+
url: () => finalUrl,
|
|
2111
|
+
headers: () => headers
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
async goBack(opts = {}) {
|
|
2115
|
+
try {
|
|
2116
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2117
|
+
if (navHistory.currentIndex > 0) {
|
|
2118
|
+
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
2119
|
+
if (prevUrl && prevUrl !== "about:blank") {
|
|
2120
|
+
await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
|
|
2121
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2122
|
+
});
|
|
2123
|
+
this.options.setUrl(prevUrl);
|
|
2124
|
+
return;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
} catch {
|
|
2128
|
+
}
|
|
2129
|
+
await this.options.evaluate("() => history.back()");
|
|
2130
|
+
await this.options.waitForTimeout(3e3);
|
|
2131
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2132
|
+
}
|
|
2133
|
+
async goForward(opts = {}) {
|
|
2134
|
+
try {
|
|
2135
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2136
|
+
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
2137
|
+
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
2138
|
+
if (nextUrl && nextUrl !== "about:blank") {
|
|
2139
|
+
await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
|
|
2140
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2141
|
+
});
|
|
2142
|
+
this.options.setUrl(nextUrl);
|
|
2143
|
+
return;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
} catch {
|
|
2147
|
+
}
|
|
2148
|
+
await this.options.evaluate("() => history.forward()");
|
|
2149
|
+
await this.options.waitForTimeout(3e3);
|
|
2150
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2151
|
+
}
|
|
2152
|
+
async reload(opts = {}) {
|
|
2153
|
+
this.options.state.loadFired = false;
|
|
2154
|
+
this.options.state.domContentFired = false;
|
|
2155
|
+
this.options.state.networkIdle = false;
|
|
2156
|
+
await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
|
|
2157
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2158
|
+
}
|
|
2159
|
+
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
2160
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2161
|
+
const checkState = () => {
|
|
2162
|
+
switch (state) {
|
|
2163
|
+
case "domcontentloaded":
|
|
2164
|
+
return this.options.state.domContentFired;
|
|
2165
|
+
case "load":
|
|
2166
|
+
return this.options.state.loadFired;
|
|
2167
|
+
case "networkidle":
|
|
2168
|
+
return this.options.state.networkIdle;
|
|
2169
|
+
case "commit":
|
|
2170
|
+
return this.options.state.domContentFired;
|
|
2171
|
+
default:
|
|
2172
|
+
return true;
|
|
2173
|
+
}
|
|
2174
|
+
};
|
|
2175
|
+
if (checkState()) return;
|
|
2176
|
+
return new Promise((resolve, reject) => {
|
|
2177
|
+
const timer = setTimeout(() => {
|
|
2178
|
+
reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
|
|
2179
|
+
}, timeout);
|
|
2180
|
+
const check = () => {
|
|
2181
|
+
if (checkState()) {
|
|
2182
|
+
clearTimeout(timer);
|
|
2183
|
+
resolve();
|
|
2184
|
+
} else {
|
|
2185
|
+
setTimeout(check, 50);
|
|
2186
|
+
}
|
|
2187
|
+
};
|
|
2188
|
+
check();
|
|
2189
|
+
});
|
|
2190
|
+
}
|
|
2191
|
+
async waitForTimeout(ms) {
|
|
2192
|
+
await new Promise((resolve) => {
|
|
2193
|
+
const timer = setTimeout(resolve, ms);
|
|
2194
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
2197
|
+
};
|
|
2198
|
+
|
|
2199
|
+
// src/cdp-driver/page-dom.ts
|
|
2200
|
+
var DomQueryService = class {
|
|
2201
|
+
constructor(options) {
|
|
2202
|
+
this.options = options;
|
|
2203
|
+
}
|
|
2204
|
+
options;
|
|
2205
|
+
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2206
|
+
async querySelector(selector) {
|
|
2207
|
+
if (selector.startsWith("xpath=")) {
|
|
2208
|
+
const found = await this.options.evaluate(`
|
|
2209
|
+
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2210
|
+
`).catch(() => false);
|
|
2211
|
+
if (!found) return 0;
|
|
2212
|
+
try {
|
|
2213
|
+
const search = await this.options.conn.send(
|
|
2214
|
+
"DOM.performSearch",
|
|
2215
|
+
{ query: selector.slice(6) },
|
|
2216
|
+
this.options.sessionId
|
|
2217
|
+
);
|
|
2218
|
+
if (search.nodeId) return search.nodeId;
|
|
2219
|
+
} catch {
|
|
2220
|
+
}
|
|
2221
|
+
return 1;
|
|
2222
|
+
}
|
|
2223
|
+
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2224
|
+
const doc = await withTimeout(
|
|
2225
|
+
this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
|
|
2226
|
+
8e3
|
|
2227
|
+
);
|
|
2228
|
+
if (!doc) return 0;
|
|
2229
|
+
const result = await withTimeout(
|
|
2230
|
+
this.options.conn.send(
|
|
2231
|
+
"DOM.querySelector",
|
|
2232
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2233
|
+
this.options.sessionId
|
|
2234
|
+
),
|
|
2235
|
+
8e3
|
|
2236
|
+
);
|
|
2237
|
+
if (!result) return 0;
|
|
2238
|
+
return result.nodeId;
|
|
2239
|
+
}
|
|
2240
|
+
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2241
|
+
async querySelectorAll(selector) {
|
|
2242
|
+
const doc = await this.options.conn.send(
|
|
2243
|
+
"DOM.getDocument",
|
|
2244
|
+
{ depth: 0 },
|
|
2245
|
+
this.options.sessionId
|
|
2246
|
+
);
|
|
2247
|
+
const result = await this.options.conn.send(
|
|
2248
|
+
"DOM.querySelectorAll",
|
|
2249
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2250
|
+
this.options.sessionId
|
|
2251
|
+
);
|
|
2252
|
+
return result.nodeIds ?? [];
|
|
2253
|
+
}
|
|
2254
|
+
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2255
|
+
async resolveNode(nodeId) {
|
|
2256
|
+
const result = await this.options.conn.send(
|
|
2257
|
+
"DOM.resolveNode",
|
|
2258
|
+
{ nodeId },
|
|
2259
|
+
this.options.sessionId
|
|
2260
|
+
);
|
|
2261
|
+
return result.object.objectId;
|
|
2262
|
+
}
|
|
2263
|
+
/** Get the box model for a nodeId */
|
|
2264
|
+
async getBoxModel(nodeId) {
|
|
2265
|
+
try {
|
|
2266
|
+
const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
|
|
2267
|
+
const c = result.model?.content;
|
|
2268
|
+
if (!c || c.length < 8) return null;
|
|
2269
|
+
const x1 = c[0];
|
|
2270
|
+
const y1 = c[1];
|
|
2271
|
+
const x2 = c[4];
|
|
2272
|
+
const y2 = c[5];
|
|
2273
|
+
return {
|
|
2274
|
+
x: Math.min(x1, x2),
|
|
2275
|
+
y: Math.min(y1, y2),
|
|
2276
|
+
width: Math.abs(x2 - x1),
|
|
2277
|
+
height: Math.abs(y2 - y1)
|
|
2278
|
+
};
|
|
2279
|
+
} catch {
|
|
2280
|
+
return null;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
/** Call a function on a RemoteObject */
|
|
2284
|
+
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
2285
|
+
const result = await this.options.conn.send("Runtime.callFunctionOn", {
|
|
2286
|
+
objectId,
|
|
2287
|
+
functionDeclaration,
|
|
2288
|
+
arguments: args.map((a) => ({ value: a })),
|
|
2289
|
+
returnByValue: true
|
|
2290
|
+
}, this.options.sessionId);
|
|
2291
|
+
if (result.exceptionDetails) {
|
|
2292
|
+
throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
|
|
2293
|
+
}
|
|
2294
|
+
return result.result?.value;
|
|
2295
|
+
}
|
|
2296
|
+
/** Send a CDP command scoped to this page's session */
|
|
2297
|
+
async _cdpSend(method, params) {
|
|
2298
|
+
return this.options.conn.send(method, params, this.options.sessionId);
|
|
2299
|
+
}
|
|
2300
|
+
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2301
|
+
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2302
|
+
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2303
|
+
};
|
|
2304
|
+
|
|
2305
|
+
// src/cdp-driver/page-runtime.ts
|
|
2306
|
+
var RuntimeEvaluationService = class {
|
|
2307
|
+
constructor(options) {
|
|
2308
|
+
this.options = options;
|
|
2309
|
+
}
|
|
2310
|
+
options;
|
|
2311
|
+
async title() {
|
|
2312
|
+
let title = "";
|
|
2313
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
2314
|
+
try {
|
|
2315
|
+
title = await this.evaluate("document.title");
|
|
2316
|
+
if (title) return title;
|
|
2317
|
+
} catch {
|
|
2318
|
+
}
|
|
2319
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2320
|
+
}
|
|
2321
|
+
return title;
|
|
2322
|
+
}
|
|
2323
|
+
async content() {
|
|
2324
|
+
return this.evaluate("document.documentElement.outerHTML");
|
|
2325
|
+
}
|
|
2326
|
+
// ── Evaluation ──────────────────────────────────────────────
|
|
2327
|
+
async evaluate(fn, ...args) {
|
|
2328
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2329
|
+
this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
|
|
2330
|
+
});
|
|
2331
|
+
let expression;
|
|
2332
|
+
if (typeof fn === "string") {
|
|
2333
|
+
expression = fn;
|
|
2334
|
+
} else {
|
|
2335
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2336
|
+
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2337
|
+
}
|
|
2338
|
+
const result = await this.options.conn.send("Runtime.evaluate", {
|
|
2339
|
+
expression,
|
|
2340
|
+
returnByValue: true,
|
|
2341
|
+
awaitPromise: true
|
|
2342
|
+
}, this.options.sessionId);
|
|
2343
|
+
if (result.exceptionDetails) {
|
|
2344
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2345
|
+
throw new Error(`${detail}`);
|
|
2346
|
+
}
|
|
2347
|
+
return result.result?.value;
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2351
|
+
*
|
|
2352
|
+
* 双路径:
|
|
2353
|
+
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2354
|
+
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2355
|
+
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2356
|
+
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2357
|
+
*
|
|
2358
|
+
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2359
|
+
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2360
|
+
*/
|
|
2361
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2362
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2363
|
+
const evalIn = async (sessionId, contextId) => {
|
|
2364
|
+
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2365
|
+
if (contextId !== void 0) params.contextId = contextId;
|
|
2366
|
+
const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
|
|
2367
|
+
if (result.exceptionDetails) {
|
|
2368
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2369
|
+
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2370
|
+
}
|
|
2371
|
+
return result.result?.value;
|
|
2372
|
+
};
|
|
2373
|
+
const attachedA = await this.tryAttachViaTargets(urlIncludes);
|
|
2374
|
+
if (attachedA) {
|
|
2375
|
+
try {
|
|
2376
|
+
return await evalIn(attachedA);
|
|
2377
|
+
} finally {
|
|
2378
|
+
this.detachQuietly(attachedA);
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2382
|
+
const all = [];
|
|
2383
|
+
const walk = (node) => {
|
|
2384
|
+
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2385
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2386
|
+
};
|
|
2387
|
+
walk(tree.frameTree);
|
|
2388
|
+
const mainId = tree.frameTree?.frame?.id;
|
|
2389
|
+
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2390
|
+
if (target) {
|
|
2391
|
+
const contexts = [];
|
|
2392
|
+
const onCtx = (raw) => {
|
|
2393
|
+
const c = raw?.context;
|
|
2394
|
+
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2395
|
+
};
|
|
2396
|
+
this.options.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2397
|
+
try {
|
|
2398
|
+
await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
|
|
2399
|
+
});
|
|
2400
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
2401
|
+
} finally {
|
|
2402
|
+
this.options.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2403
|
+
}
|
|
2404
|
+
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2405
|
+
if (ctx) return evalIn(this.options.sessionId, ctx.id);
|
|
2406
|
+
}
|
|
2407
|
+
const attachedC = await this.tryAttachViaAutoAttach(urlIncludes);
|
|
2408
|
+
if (attachedC) {
|
|
2409
|
+
try {
|
|
2410
|
+
return await evalIn(attachedC);
|
|
2411
|
+
} finally {
|
|
2412
|
+
this.detachQuietly(attachedC);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
* 输入专用 frame session 解析(mouse/click/fill --frame)。
|
|
2419
|
+
*
|
|
2420
|
+
* 与 evaluateInFrame 的区别:必须拿到**真实 target session**(Input 域
|
|
2421
|
+
* 事件派发到该 session 才会进入 iframe 的渲染进程——主页面 session 上
|
|
2422
|
+
* 派发的输入进不去 OOPIF,qqmail 验证码 4 次页面级拖动全败的实证)。
|
|
2423
|
+
* 因此只走 A(getTargets attach)/ C(auto-attach)两路;同进程 frame
|
|
2424
|
+
* 没有 session,但 locator 层的坐标偏移本就支持同源 iframe,直接用普通
|
|
2425
|
+
* click/fill 即可。
|
|
2426
|
+
*
|
|
2427
|
+
* 坐标语义:返回的 session 上派发 Input 事件用 **iframe 局部坐标**
|
|
2428
|
+
* (与该 session 内 getBoundingClientRect 一致)。
|
|
2429
|
+
*/
|
|
2430
|
+
async resolveFrameSession(urlIncludes) {
|
|
2431
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2432
|
+
const viaTargets = await this.tryAttachViaTargets(urlIncludes);
|
|
2433
|
+
if (viaTargets) return viaTargets;
|
|
2434
|
+
const viaAuto = await this.tryAttachViaAutoAttach(urlIncludes);
|
|
2435
|
+
if (viaAuto) return viaAuto;
|
|
2436
|
+
try {
|
|
2437
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2438
|
+
const urls = [];
|
|
2439
|
+
const walk = (node) => {
|
|
2440
|
+
urls.push(node.frame.url);
|
|
2441
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2442
|
+
};
|
|
2443
|
+
walk(tree.frameTree);
|
|
2444
|
+
if (urls.some((u) => u.includes(urlIncludes))) {
|
|
2445
|
+
throw new Error(`frame "${urlIncludes}" \u662F\u540C\u8FDB\u7A0B iframe\uFF08\u65E0\u72EC\u7ACB target\uFF09\u2014\u2014\u666E\u901A click/fill/mouse \u5373\u53EF\uFF08locator \u5C42\u5DF2\u652F\u6301\u540C\u6E90 iframe \u5750\u6807\u504F\u79FB\uFF09`);
|
|
2446
|
+
}
|
|
2447
|
+
} catch (err) {
|
|
2448
|
+
if (err instanceof Error && err.message.includes("\u540C\u8FDB\u7A0B")) throw err;
|
|
2449
|
+
}
|
|
2450
|
+
throw new Error(`no OOPIF target for "${urlIncludes}"\uFF08\u7528 'xbrowser frames' \u67E5\u770B\u53EF\u89C1\u7684 iframe target\uFF1BOOPIF \u53EA\u5728 Target.getTargets \u91CC\u51FA\u73B0\uFF09`);
|
|
2451
|
+
}
|
|
2452
|
+
/** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
|
|
2453
|
+
async listFrameTargets() {
|
|
2454
|
+
try {
|
|
2455
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2456
|
+
return (tg.targetInfos || []).filter((t) => t.type === "iframe").map((t) => ({ url: t.url || "", targetId: t.targetId }));
|
|
2457
|
+
} catch {
|
|
2458
|
+
return [];
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
/** 路径 A:浏览器级 Target.getTargets 平铺 iframe target,按 URL 子串 attach。
|
|
2462
|
+
* 多次导航后列表里可能残留正在销毁的陈旧 target——attach 后用 location.href
|
|
2463
|
+
* 验证候选确实是活目标,不匹配则换下一个(验证码 iframe 重建场景实测会撞上)。 */
|
|
2464
|
+
async tryAttachViaTargets(urlIncludes) {
|
|
2465
|
+
try {
|
|
2466
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2467
|
+
const candidates = (tg.targetInfos || []).filter((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2468
|
+
for (const hit of candidates) {
|
|
2469
|
+
try {
|
|
2470
|
+
const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit.targetId, flatten: true });
|
|
2471
|
+
const probe = await this.options.conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, att.sessionId);
|
|
2472
|
+
const href = typeof probe.result?.value === "string" ? probe.result.value : "";
|
|
2473
|
+
if (probe.exceptionDetails || !href.includes(urlIncludes)) {
|
|
2474
|
+
this.detachQuietly(att.sessionId);
|
|
2475
|
+
continue;
|
|
2476
|
+
}
|
|
2477
|
+
return att.sessionId;
|
|
2478
|
+
} catch {
|
|
2479
|
+
continue;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
} catch {
|
|
2483
|
+
}
|
|
2484
|
+
return null;
|
|
2485
|
+
}
|
|
2486
|
+
/** 路径 C:Target.setAutoAttach 监听后续 attach 的 iframe target(兜底) */
|
|
2487
|
+
async tryAttachViaAutoAttach(urlIncludes) {
|
|
2488
|
+
const attached = [];
|
|
2489
|
+
const onAttach = (raw) => {
|
|
2490
|
+
const ev = raw;
|
|
2491
|
+
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2492
|
+
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2493
|
+
}
|
|
2494
|
+
};
|
|
2495
|
+
this.options.conn.on("Target.attachedToTarget", onAttach);
|
|
2496
|
+
try {
|
|
2497
|
+
await this.options.conn.send("Target.setAutoAttach", {
|
|
2498
|
+
autoAttach: true,
|
|
2499
|
+
waitForDebuggerOnStart: false,
|
|
2500
|
+
flatten: true
|
|
2501
|
+
}, this.options.sessionId);
|
|
2502
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
2503
|
+
} finally {
|
|
2504
|
+
this.options.conn.off("Target.attachedToTarget", onAttach);
|
|
2505
|
+
this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2509
|
+
return hit ? hit.sessionId : null;
|
|
2510
|
+
}
|
|
2511
|
+
detachQuietly(sessionId) {
|
|
2512
|
+
this.options.conn.send("Target.detachFromTarget", { sessionId }).catch(() => {
|
|
2513
|
+
});
|
|
2514
|
+
}
|
|
2515
|
+
/** evaluateHandle — evaluates fn and returns a handle for element bounding box */
|
|
2516
|
+
async evaluateHandle(fn, ...args) {
|
|
2517
|
+
let expression;
|
|
2518
|
+
if (typeof fn === "string") {
|
|
2519
|
+
expression = fn;
|
|
2520
|
+
} else {
|
|
2521
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2522
|
+
expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
|
|
2523
|
+
}
|
|
2524
|
+
const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
|
|
2525
|
+
let box = null;
|
|
2526
|
+
try {
|
|
2527
|
+
box = JSON.parse(result.result?.value);
|
|
2528
|
+
} catch {
|
|
2529
|
+
}
|
|
2530
|
+
return {
|
|
2531
|
+
asElement: () => box ? { boundingBox: async () => box } : null
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
async $eval(selector, fn, ...args) {
|
|
2535
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2536
|
+
const selJSON = JSON.stringify(selector);
|
|
2537
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2538
|
+
return this.evaluate(
|
|
2539
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2540
|
+
const el = xpathExpr
|
|
2541
|
+
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2542
|
+
: document.querySelector(sel);
|
|
2543
|
+
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2544
|
+
const fn = new Function('return ' + fnStr)();
|
|
2545
|
+
return fn(el, ...evalArgs);
|
|
2546
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2547
|
+
);
|
|
2548
|
+
}
|
|
2549
|
+
async $$eval(selector, fn, ...args) {
|
|
2550
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2551
|
+
const selJSON = JSON.stringify(selector);
|
|
2552
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2553
|
+
return this.evaluate(
|
|
2554
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2555
|
+
const els = xpathExpr
|
|
2556
|
+
? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
|
|
2557
|
+
: Array.from(document.querySelectorAll(sel));
|
|
2558
|
+
const fn = new Function('return ' + fnStr)();
|
|
2559
|
+
return fn(els, ...evalArgs);
|
|
2560
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2561
|
+
);
|
|
2562
|
+
}
|
|
2563
|
+
};
|
|
2564
|
+
|
|
2565
|
+
// src/cdp-driver/page-frame-input.ts
|
|
2566
|
+
function isSessionDeadError(err) {
|
|
2567
|
+
return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
|
|
2568
|
+
}
|
|
2569
|
+
var FrameInputService = class {
|
|
2570
|
+
constructor(deps) {
|
|
2571
|
+
this.deps = deps;
|
|
2572
|
+
}
|
|
2573
|
+
deps;
|
|
2574
|
+
/** urlIncludes → 已 attach 的 session + 鼠标实例(跨命令保持位置状态) */
|
|
2575
|
+
cache = /* @__PURE__ */ new Map();
|
|
2576
|
+
/**
|
|
2577
|
+
* 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
|
|
2578
|
+
* 缓存的 session 失效(iframe 重建/刷新)时自动重 attach;重 attach 会
|
|
2579
|
+
* 重置鼠标位置——调用方需重新读取目标元素坐标。
|
|
2580
|
+
*/
|
|
2581
|
+
async frameMouse(urlIncludes, opts = {}) {
|
|
2582
|
+
if (opts.fresh) this.cache.delete(urlIncludes);
|
|
2583
|
+
const cached = this.cache.get(urlIncludes);
|
|
2584
|
+
if (cached) {
|
|
2585
|
+
try {
|
|
2586
|
+
await this.deps.conn.send("Runtime.evaluate", { expression: "1", returnByValue: true }, cached.sessionId);
|
|
2587
|
+
return cached.mouse;
|
|
2588
|
+
} catch {
|
|
2589
|
+
this.cache.delete(urlIncludes);
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
const sessionId = await this.deps.resolveFrameSession(urlIncludes);
|
|
2593
|
+
const mouse = new XBMouseImpl(this.deps.conn, sessionId);
|
|
2594
|
+
this.cache.set(urlIncludes, { sessionId, mouse });
|
|
2595
|
+
return mouse;
|
|
2596
|
+
}
|
|
2597
|
+
/**
|
|
2598
|
+
* 带重试的 frame 鼠标操作:Chrome 异步销毁旧 OOPIF target 的窗口期里
|
|
2599
|
+
* (连续导航/验证码 iframe 重建),probe 通过后 dispatch 仍可能撞上死
|
|
2600
|
+
* session——session 失效时强制重 attach 再做一次。
|
|
2601
|
+
*/
|
|
2602
|
+
async runFrameMouse(urlIncludes, fn) {
|
|
2603
|
+
try {
|
|
2604
|
+
return await fn(await this.frameMouse(urlIncludes));
|
|
2605
|
+
} catch (err) {
|
|
2606
|
+
if (!isSessionDeadError(err)) throw err;
|
|
2607
|
+
this.cache.delete(urlIncludes);
|
|
2608
|
+
return fn(await this.frameMouse(urlIncludes, { fresh: true }));
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
/** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
|
|
2612
|
+
async clickInFrame(urlIncludes, selector, opts = {}) {
|
|
2613
|
+
const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
|
|
2614
|
+
const x = rect.x + rect.width / 2;
|
|
2615
|
+
const y = rect.y + rect.height / 2;
|
|
2616
|
+
await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
|
|
2617
|
+
return { x, y };
|
|
2618
|
+
}
|
|
2619
|
+
/** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
|
|
2620
|
+
async fillInFrame(urlIncludes, selector, text, opts = {}) {
|
|
2621
|
+
try {
|
|
2622
|
+
return await this.fillInFrameInner(urlIncludes, selector, text, opts);
|
|
2623
|
+
} catch (err) {
|
|
2624
|
+
if (!isSessionDeadError(err)) throw err;
|
|
2625
|
+
this.cache.delete(urlIncludes);
|
|
2626
|
+
return this.fillInFrameInner(urlIncludes, selector, text, opts);
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
|
|
2630
|
+
await this.clickInFrame(urlIncludes, selector, opts);
|
|
2631
|
+
const cached = this.cache.get(urlIncludes);
|
|
2632
|
+
if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
|
|
2633
|
+
await this.deps.evaluateInFrame(
|
|
2634
|
+
urlIncludes,
|
|
2635
|
+
`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
|
|
2636
|
+
);
|
|
2637
|
+
await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
|
|
2638
|
+
const readback = await this.deps.evaluateInFrame(
|
|
2639
|
+
urlIncludes,
|
|
2640
|
+
`(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
|
|
2641
|
+
);
|
|
2642
|
+
return { value: readback ?? "" };
|
|
2643
|
+
}
|
|
2644
|
+
/** 轮询 OOPIF 内元素 rect(等待元素出现/可测量) */
|
|
2645
|
+
async pollFrameRect(urlIncludes, selector, timeoutMs) {
|
|
2646
|
+
const expr = `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; const r = el.getBoundingClientRect(); if (r.width === 0 || r.height === 0) return null; return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`;
|
|
2647
|
+
const deadline = Date.now() + timeoutMs;
|
|
2648
|
+
let lastErr;
|
|
2649
|
+
while (Date.now() < deadline) {
|
|
2650
|
+
try {
|
|
2651
|
+
const rect = await this.deps.evaluateInFrame(urlIncludes, expr);
|
|
2652
|
+
if (rect) return rect;
|
|
2653
|
+
} catch (err) {
|
|
2654
|
+
lastErr = err;
|
|
2655
|
+
}
|
|
2656
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
2657
|
+
}
|
|
2658
|
+
throw new Error(`[frame ${urlIncludes}] element "${selector}" not found/visible within ${timeoutMs}ms${lastErr instanceof Error ? `\uFF08last: ${lastErr.message}\uFF09` : ""}`);
|
|
2659
|
+
}
|
|
2660
|
+
};
|
|
2661
|
+
|
|
2662
|
+
// src/cdp-driver/page.ts
|
|
2663
|
+
var XBPageImpl = class _XBPageImpl {
|
|
2664
|
+
conn;
|
|
2665
|
+
_emitter = new EventEmitter();
|
|
2666
|
+
_subscriptions = [];
|
|
2667
|
+
sessionId;
|
|
2668
|
+
_targetId;
|
|
2669
|
+
_contextImpl;
|
|
2670
|
+
_browserImpl;
|
|
2671
|
+
_closed = false;
|
|
2672
|
+
_url = "about:blank";
|
|
2673
|
+
_viewportSize = null;
|
|
2674
|
+
_loadState = {
|
|
2675
|
+
loadFired: true,
|
|
2676
|
+
domContentFired: true,
|
|
2677
|
+
networkIdle: true
|
|
2678
|
+
};
|
|
2679
|
+
mouse;
|
|
2680
|
+
keyboard;
|
|
2681
|
+
mediaService;
|
|
2682
|
+
fileInputService;
|
|
2683
|
+
networkWaitService;
|
|
2684
|
+
networkRouteService;
|
|
2685
|
+
navigationService;
|
|
2686
|
+
domQueryService;
|
|
2687
|
+
runtimeEvaluationService;
|
|
2688
|
+
frameInputService;
|
|
2689
|
+
// Network tracking for waitForLoadState('networkidle')
|
|
2690
|
+
inflightRequests = /* @__PURE__ */ new Set();
|
|
2691
|
+
networkIdleResolve = null;
|
|
2692
|
+
networkIdleTimer = null;
|
|
2693
|
+
static NETWORK_IDLE_MS = 500;
|
|
2694
|
+
constructor(conn, sessionId, targetId, context, browser) {
|
|
2695
|
+
this.conn = conn;
|
|
2696
|
+
this.sessionId = sessionId;
|
|
2697
|
+
this._targetId = targetId;
|
|
2698
|
+
this._contextImpl = context;
|
|
2699
|
+
this._browserImpl = browser;
|
|
2700
|
+
this.mouse = new XBMouseImpl(conn, sessionId);
|
|
2701
|
+
this.keyboard = new XBKeyboardImpl(conn, sessionId);
|
|
2702
|
+
this.mediaService = new MediaService({
|
|
2703
|
+
conn,
|
|
2704
|
+
sessionId,
|
|
2705
|
+
viewportSize: this._viewportSize,
|
|
2706
|
+
evaluate: (script) => this.evaluate(script),
|
|
2707
|
+
onViewportSize: (size) => {
|
|
2708
|
+
this._viewportSize = size;
|
|
2709
|
+
}
|
|
2710
|
+
});
|
|
2711
|
+
this.fileInputService = new FileInputService({
|
|
2712
|
+
conn,
|
|
2713
|
+
sessionId,
|
|
2714
|
+
evaluate: (script) => this.evaluate(script),
|
|
2715
|
+
mouse: this.mouse
|
|
2716
|
+
});
|
|
2717
|
+
this.networkWaitService = new NetworkWaitService({
|
|
2718
|
+
conn,
|
|
2719
|
+
sessionId,
|
|
2720
|
+
responses: this._networkResponses,
|
|
2721
|
+
requests: this._networkRequests,
|
|
2722
|
+
on: (event, handler) => this._emitter.on(event, handler),
|
|
2723
|
+
off: (event, handler) => this._emitter.removeListener(event, handler),
|
|
2724
|
+
currentUrl: () => this.url()
|
|
2725
|
+
});
|
|
2726
|
+
this.networkRouteService = new NetworkRouteService({
|
|
2727
|
+
conn,
|
|
2728
|
+
sessionId,
|
|
2729
|
+
emit: (event, ...args) => this._emit(event, ...args)
|
|
2730
|
+
});
|
|
2731
|
+
this.navigationService = new NavigationService({
|
|
2732
|
+
conn,
|
|
2733
|
+
sessionId,
|
|
2734
|
+
state: this._loadState,
|
|
2735
|
+
stealthConfig: this._contextImpl.stealthConfig,
|
|
2736
|
+
isClosed: () => this._closed,
|
|
2737
|
+
setUrl: (url) => {
|
|
2738
|
+
this._url = url;
|
|
2739
|
+
},
|
|
2740
|
+
currentUrl: () => this.url(),
|
|
2741
|
+
waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
|
|
2742
|
+
waitForTimeout: (ms) => this.waitForTimeout(ms),
|
|
2743
|
+
evaluate: (script) => this.evaluate(script)
|
|
2744
|
+
});
|
|
2745
|
+
this.runtimeEvaluationService = new RuntimeEvaluationService({
|
|
2746
|
+
conn,
|
|
2747
|
+
sessionId,
|
|
2748
|
+
isClosed: () => this._closed,
|
|
2749
|
+
url: () => this.url()
|
|
2750
|
+
});
|
|
2751
|
+
this.frameInputService = new FrameInputService({
|
|
2752
|
+
conn,
|
|
2753
|
+
resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
|
|
2754
|
+
evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
|
|
2755
|
+
});
|
|
2756
|
+
this.domQueryService = new DomQueryService({
|
|
2757
|
+
conn,
|
|
2758
|
+
sessionId,
|
|
2759
|
+
evaluate: (script) => this.evaluate(script)
|
|
2760
|
+
});
|
|
2761
|
+
}
|
|
2762
|
+
_emit(event, ...args) {
|
|
2763
|
+
this._emitter.emit(event, ...args);
|
|
2764
|
+
}
|
|
2765
|
+
/** Internal initialization — must be called after construction */
|
|
2766
|
+
async _init() {
|
|
2767
|
+
await this.conn.send("Page.enable", void 0, this.sessionId);
|
|
2768
|
+
await this.conn.send("Runtime.enable", void 0, this.sessionId);
|
|
2769
|
+
await this.conn.send("Network.enable", void 0, this.sessionId);
|
|
2770
|
+
await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
|
|
2771
|
+
});
|
|
2772
|
+
if (this._contextImpl.ignoreHTTPSErrors) {
|
|
2773
|
+
await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
|
|
2774
|
+
});
|
|
2775
|
+
await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
if (this._contextImpl.httpCredentials) {
|
|
2779
|
+
await this.conn.send("Fetch.enable", {
|
|
2780
|
+
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
1538
2781
|
handleAuthRequests: true
|
|
1539
2782
|
}, this.sessionId).catch(() => {
|
|
1540
2783
|
});
|
|
1541
2784
|
this._subscriptions.push(
|
|
1542
2785
|
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
1543
|
-
if (this.
|
|
2786
|
+
if (this.networkRouteService.isInterceptionEnabled) return;
|
|
1544
2787
|
const p = params;
|
|
1545
2788
|
this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
|
|
1546
2789
|
});
|
|
@@ -1719,9 +2962,9 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1719
2962
|
"Target.getTargetInfo",
|
|
1720
2963
|
{ targetId: this._targetId }
|
|
1721
2964
|
);
|
|
1722
|
-
|
|
1723
|
-
this.
|
|
1724
|
-
if (
|
|
2965
|
+
const curUrl = info.targetInfo?.url ?? info.url;
|
|
2966
|
+
if (curUrl) this._url = curUrl;
|
|
2967
|
+
if (curUrl && curUrl !== "about:blank" && curUrl !== "") {
|
|
1725
2968
|
this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
|
|
1726
2969
|
}
|
|
1727
2970
|
} catch {
|
|
@@ -1732,108 +2975,16 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1732
2975
|
}
|
|
1733
2976
|
// ── Navigation ──────────────────────────────────────────────
|
|
1734
2977
|
async goto(url, opts = {}) {
|
|
1735
|
-
|
|
1736
|
-
const waitUntil = opts.waitUntil ?? "load";
|
|
1737
|
-
const timeout = opts.timeout ?? 3e4;
|
|
1738
|
-
this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
|
|
1739
|
-
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
1740
|
-
try {
|
|
1741
|
-
await this.conn.send(
|
|
1742
|
-
"Page.addScriptToEvaluateOnNewDocument",
|
|
1743
|
-
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
|
|
1744
|
-
this.sessionId
|
|
1745
|
-
);
|
|
1746
|
-
} catch {
|
|
1747
|
-
}
|
|
1748
|
-
try {
|
|
1749
|
-
const rawUa = await this.conn.send(
|
|
1750
|
-
"Runtime.evaluate",
|
|
1751
|
-
{ expression: "navigator.userAgent", returnByValue: true },
|
|
1752
|
-
this.sessionId
|
|
1753
|
-
);
|
|
1754
|
-
const ua = rawUa?.value || "";
|
|
1755
|
-
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
1756
|
-
if (cleaned !== ua) {
|
|
1757
|
-
await this.conn.send(
|
|
1758
|
-
"Network.setUserAgentOverride",
|
|
1759
|
-
{ userAgent: cleaned },
|
|
1760
|
-
this.sessionId
|
|
1761
|
-
);
|
|
1762
|
-
}
|
|
1763
|
-
} catch {
|
|
1764
|
-
}
|
|
1765
|
-
}
|
|
1766
|
-
const result = await this.conn.send(
|
|
1767
|
-
"Page.navigate",
|
|
1768
|
-
{ url, referrer: opts.referer },
|
|
1769
|
-
this.sessionId
|
|
1770
|
-
);
|
|
1771
|
-
if (result.errorText) {
|
|
1772
|
-
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
1773
|
-
}
|
|
1774
|
-
if (waitUntil === "commit") {
|
|
1775
|
-
this._url = url;
|
|
1776
|
-
return {
|
|
1777
|
-
status: () => 0,
|
|
1778
|
-
ok: () => false,
|
|
1779
|
-
url: () => url,
|
|
1780
|
-
headers: () => ({})
|
|
1781
|
-
};
|
|
1782
|
-
}
|
|
1783
|
-
await this.waitForLoadState(waitUntil, timeout);
|
|
1784
|
-
this._url = url;
|
|
1785
|
-
const statusCode = 200;
|
|
1786
|
-
const finalUrl = url;
|
|
1787
|
-
const headers = {};
|
|
1788
|
-
return {
|
|
1789
|
-
status: () => statusCode,
|
|
1790
|
-
ok: () => statusCode >= 200 && statusCode < 300,
|
|
1791
|
-
url: () => finalUrl,
|
|
1792
|
-
headers: () => headers
|
|
1793
|
-
};
|
|
2978
|
+
return this.navigationService.goto(url, opts);
|
|
1794
2979
|
}
|
|
1795
2980
|
async goBack(opts = {}) {
|
|
1796
|
-
|
|
1797
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1798
|
-
if (navHistory.currentIndex > 0) {
|
|
1799
|
-
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
1800
|
-
if (prevUrl && prevUrl !== "about:blank") {
|
|
1801
|
-
await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
|
|
1802
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1803
|
-
});
|
|
1804
|
-
this._url = prevUrl;
|
|
1805
|
-
return;
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
|
-
} catch {
|
|
1809
|
-
}
|
|
1810
|
-
await this.evaluate("() => history.back()");
|
|
1811
|
-
await this.waitForTimeout(3e3);
|
|
1812
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
2981
|
+
return this.navigationService.goBack(opts);
|
|
1813
2982
|
}
|
|
1814
2983
|
async goForward(opts = {}) {
|
|
1815
|
-
|
|
1816
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1817
|
-
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
1818
|
-
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
1819
|
-
if (nextUrl && nextUrl !== "about:blank") {
|
|
1820
|
-
await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
|
|
1821
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1822
|
-
});
|
|
1823
|
-
this._url = nextUrl;
|
|
1824
|
-
return;
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
} catch {
|
|
1828
|
-
}
|
|
1829
|
-
await this.evaluate("() => history.forward()");
|
|
1830
|
-
await this.waitForTimeout(3e3);
|
|
1831
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
2984
|
+
return this.navigationService.goForward(opts);
|
|
1832
2985
|
}
|
|
1833
2986
|
async reload(opts = {}) {
|
|
1834
|
-
this.
|
|
1835
|
-
await this.conn.send("Page.reload", void 0, this.sessionId);
|
|
1836
|
-
await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2987
|
+
return this.navigationService.reload(opts);
|
|
1837
2988
|
}
|
|
1838
2989
|
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
1839
2990
|
if (this._closed) throw new Error("Page is closed");
|
|
@@ -1909,201 +3060,66 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1909
3060
|
while (Date.now() < deadline) {
|
|
1910
3061
|
try {
|
|
1911
3062
|
const result = await this.evaluate(
|
|
1912
|
-
`(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
1913
|
-
);
|
|
1914
|
-
if (result) return result;
|
|
1915
|
-
} catch (err) {
|
|
1916
|
-
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
1917
|
-
}
|
|
1918
|
-
const pollMs = typeof polling === "number" ? polling : 16;
|
|
1919
|
-
await this.waitForTimeout(pollMs);
|
|
1920
|
-
}
|
|
1921
|
-
const detail = lastError ? `
|
|
1922
|
-
Last error: ${lastError.message}` : "";
|
|
1923
|
-
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
1924
|
-
}
|
|
1925
|
-
url() {
|
|
1926
|
-
return this._url;
|
|
1927
|
-
}
|
|
1928
|
-
async title() {
|
|
1929
|
-
for (let i = 0; i < 20; i++) {
|
|
1930
|
-
try {
|
|
1931
|
-
this._title = await this.evaluate("document.title");
|
|
1932
|
-
if (this._title) return this._title;
|
|
1933
|
-
} catch {
|
|
1934
|
-
}
|
|
1935
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
1936
|
-
}
|
|
1937
|
-
try {
|
|
1938
|
-
const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
|
|
1939
|
-
if (info?.title) {
|
|
1940
|
-
this._title = info.title;
|
|
1941
|
-
return this._title;
|
|
1942
|
-
}
|
|
1943
|
-
} catch {
|
|
1944
|
-
}
|
|
1945
|
-
return this._title;
|
|
1946
|
-
}
|
|
1947
|
-
async content() {
|
|
1948
|
-
return this.evaluate("document.documentElement.outerHTML");
|
|
1949
|
-
}
|
|
1950
|
-
// ── Evaluation ──────────────────────────────────────────────
|
|
1951
|
-
async evaluate(fn, ...args) {
|
|
1952
|
-
if (this._closed) throw new Error("Page is closed");
|
|
1953
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
|
|
1954
|
-
});
|
|
1955
|
-
let expression;
|
|
1956
|
-
if (typeof fn === "string") {
|
|
1957
|
-
expression = fn;
|
|
1958
|
-
} else {
|
|
1959
|
-
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
1960
|
-
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
1961
|
-
}
|
|
1962
|
-
const result = await this.conn.send("Runtime.evaluate", {
|
|
1963
|
-
expression,
|
|
1964
|
-
returnByValue: true,
|
|
1965
|
-
awaitPromise: true
|
|
1966
|
-
}, this.sessionId);
|
|
1967
|
-
if (result.exceptionDetails) {
|
|
1968
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
1969
|
-
throw new Error(`${detail}`);
|
|
1970
|
-
}
|
|
1971
|
-
return result.result?.value;
|
|
1972
|
-
}
|
|
1973
|
-
/**
|
|
1974
|
-
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
1975
|
-
*
|
|
1976
|
-
* 双路径:
|
|
1977
|
-
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
1978
|
-
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
1979
|
-
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
1980
|
-
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
1981
|
-
*
|
|
1982
|
-
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
1983
|
-
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
1984
|
-
*/
|
|
1985
|
-
async evaluateInFrame(urlIncludes, expression) {
|
|
1986
|
-
if (this._closed) throw new Error("Page is closed");
|
|
1987
|
-
const evalIn = async (sessionId, contextId) => {
|
|
1988
|
-
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
1989
|
-
if (contextId !== void 0) params.contextId = contextId;
|
|
1990
|
-
const result = await this.conn.send("Runtime.evaluate", params, sessionId);
|
|
1991
|
-
if (result.exceptionDetails) {
|
|
1992
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
1993
|
-
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
1994
|
-
}
|
|
1995
|
-
return result.result?.value;
|
|
1996
|
-
};
|
|
1997
|
-
try {
|
|
1998
|
-
const tg = await this.conn.send("Target.getTargets", void 0);
|
|
1999
|
-
const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2000
|
-
if (hit2) {
|
|
2001
|
-
const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
|
|
2002
|
-
return evalIn(att.sessionId);
|
|
2003
|
-
}
|
|
2004
|
-
} catch {
|
|
2005
|
-
}
|
|
2006
|
-
const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
|
|
2007
|
-
const all = [];
|
|
2008
|
-
const walk = (node) => {
|
|
2009
|
-
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2010
|
-
for (const child of node.childFrames || []) walk(child);
|
|
2011
|
-
};
|
|
2012
|
-
walk(tree.frameTree);
|
|
2013
|
-
const mainId = tree.frameTree?.frame?.id;
|
|
2014
|
-
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2015
|
-
if (target) {
|
|
2016
|
-
const contexts = [];
|
|
2017
|
-
const onCtx = (raw) => {
|
|
2018
|
-
const c = raw?.context;
|
|
2019
|
-
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2020
|
-
};
|
|
2021
|
-
this.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2022
|
-
try {
|
|
2023
|
-
await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
|
|
2024
|
-
});
|
|
2025
|
-
await new Promise((r) => setTimeout(r, 400));
|
|
2026
|
-
} finally {
|
|
2027
|
-
this.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2028
|
-
}
|
|
2029
|
-
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2030
|
-
if (ctx) return evalIn(this.sessionId, ctx.id);
|
|
2031
|
-
}
|
|
2032
|
-
const attached = [];
|
|
2033
|
-
const onAttach = (raw) => {
|
|
2034
|
-
const ev = raw;
|
|
2035
|
-
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2036
|
-
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2037
|
-
}
|
|
2038
|
-
};
|
|
2039
|
-
this.conn.on("Target.attachedToTarget", onAttach);
|
|
2040
|
-
try {
|
|
2041
|
-
await this.conn.send("Target.setAutoAttach", {
|
|
2042
|
-
autoAttach: true,
|
|
2043
|
-
waitForDebuggerOnStart: false,
|
|
2044
|
-
flatten: true
|
|
2045
|
-
}, this.sessionId);
|
|
2046
|
-
await new Promise((r) => setTimeout(r, 600));
|
|
2047
|
-
} finally {
|
|
2048
|
-
this.conn.off("Target.attachedToTarget", onAttach);
|
|
2049
|
-
this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
|
|
2050
|
-
});
|
|
2051
|
-
}
|
|
2052
|
-
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2053
|
-
if (!hit) {
|
|
2054
|
-
throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
|
|
2055
|
-
}
|
|
2056
|
-
return evalIn(hit.sessionId);
|
|
2057
|
-
}
|
|
2058
|
-
/** evaluateHandle — evaluates fn and returns a handle for element bounding box */
|
|
2059
|
-
async evaluateHandle(fn, ...args) {
|
|
2060
|
-
let expression;
|
|
2061
|
-
if (typeof fn === "string") {
|
|
2062
|
-
expression = fn;
|
|
2063
|
-
} else {
|
|
2064
|
-
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2065
|
-
expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
|
|
2066
|
-
}
|
|
2067
|
-
const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
|
|
2068
|
-
let box = null;
|
|
2069
|
-
try {
|
|
2070
|
-
box = JSON.parse(result.result?.value);
|
|
2071
|
-
} catch {
|
|
3063
|
+
`(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
3064
|
+
);
|
|
3065
|
+
if (result) return result;
|
|
3066
|
+
} catch (err) {
|
|
3067
|
+
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
3068
|
+
}
|
|
3069
|
+
const pollMs = typeof polling === "number" ? polling : 16;
|
|
3070
|
+
await this.waitForTimeout(pollMs);
|
|
2072
3071
|
}
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
};
|
|
3072
|
+
const detail = lastError ? `
|
|
3073
|
+
Last error: ${lastError.message}` : "";
|
|
3074
|
+
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
3075
|
+
}
|
|
3076
|
+
url() {
|
|
3077
|
+
return this._url;
|
|
3078
|
+
}
|
|
3079
|
+
async title() {
|
|
3080
|
+
return this.runtimeEvaluationService.title();
|
|
3081
|
+
}
|
|
3082
|
+
async content() {
|
|
3083
|
+
return this.runtimeEvaluationService.content();
|
|
3084
|
+
}
|
|
3085
|
+
async evaluate(fn, ...args) {
|
|
3086
|
+
return this.runtimeEvaluationService.evaluate(fn, ...args);
|
|
3087
|
+
}
|
|
3088
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
3089
|
+
return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
|
|
3090
|
+
}
|
|
3091
|
+
/** 浏览器级 iframe target 列表(OOPIF 可见——frames 命令用) */
|
|
3092
|
+
async listFrameTargets() {
|
|
3093
|
+
return this.runtimeEvaluationService.listFrameTargets();
|
|
3094
|
+
}
|
|
3095
|
+
/**
|
|
3096
|
+
* 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
|
|
3097
|
+
* 坐标语义:iframe 局部坐标(与该 session 内 getBoundingClientRect 一致)。
|
|
3098
|
+
* session 失效自动重 attach(鼠标位置会重置,需重读目标坐标)。
|
|
3099
|
+
*/
|
|
3100
|
+
async frameMouse(urlIncludes, opts) {
|
|
3101
|
+
return this.frameInputService.frameMouse(urlIncludes, opts);
|
|
3102
|
+
}
|
|
3103
|
+
async runFrameMouse(urlIncludes, fn) {
|
|
3104
|
+
return this.frameInputService.runFrameMouse(urlIncludes, fn);
|
|
3105
|
+
}
|
|
3106
|
+
/** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
|
|
3107
|
+
async clickInFrame(urlIncludes, selector, opts) {
|
|
3108
|
+
return this.frameInputService.clickInFrame(urlIncludes, selector, opts);
|
|
3109
|
+
}
|
|
3110
|
+
/** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
|
|
3111
|
+
async fillInFrame(urlIncludes, selector, text, opts) {
|
|
3112
|
+
return this.frameInputService.fillInFrame(urlIncludes, selector, text, opts);
|
|
3113
|
+
}
|
|
3114
|
+
async evaluateHandle(script, ...args) {
|
|
3115
|
+
return this.runtimeEvaluationService.evaluateHandle(script, ...args);
|
|
2076
3116
|
}
|
|
2077
3117
|
async $eval(selector, fn, ...args) {
|
|
2078
|
-
|
|
2079
|
-
const selJSON = JSON.stringify(selector);
|
|
2080
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2081
|
-
return this.evaluate(
|
|
2082
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2083
|
-
const el = xpathExpr
|
|
2084
|
-
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2085
|
-
: document.querySelector(sel);
|
|
2086
|
-
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2087
|
-
const fn = new Function('return ' + fnStr)();
|
|
2088
|
-
return fn(el, ...evalArgs);
|
|
2089
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2090
|
-
);
|
|
3118
|
+
return this.runtimeEvaluationService.$eval(selector, fn, ...args);
|
|
2091
3119
|
}
|
|
2092
3120
|
async $$eval(selector, fn, ...args) {
|
|
2093
|
-
|
|
2094
|
-
const selJSON = JSON.stringify(selector);
|
|
2095
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2096
|
-
return this.evaluate(
|
|
2097
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2098
|
-
const els = xpathExpr
|
|
2099
|
-
? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
|
|
2100
|
-
: Array.from(document.querySelectorAll(sel));
|
|
2101
|
-
const fn = new Function('return ' + fnStr)();
|
|
2102
|
-
return fn(els, ...evalArgs);
|
|
2103
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2104
|
-
);
|
|
3121
|
+
return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
|
|
2105
3122
|
}
|
|
2106
|
-
// ── Locator ─────────────────────────────────────────────────
|
|
2107
3123
|
locator(selector) {
|
|
2108
3124
|
return new XBLocatorImpl(this, selector);
|
|
2109
3125
|
}
|
|
@@ -2224,88 +3240,20 @@ Last error: ${lastError.message}` : "";
|
|
|
2224
3240
|
}
|
|
2225
3241
|
// ── Screen ──────────────────────────────────────────────────
|
|
2226
3242
|
async screenshot(opts = {}) {
|
|
2227
|
-
|
|
2228
|
-
format: opts.type ?? "png"
|
|
2229
|
-
};
|
|
2230
|
-
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
2231
|
-
params.quality = opts.quality;
|
|
2232
|
-
}
|
|
2233
|
-
if (opts.fullPage) {
|
|
2234
|
-
params.captureBeyondViewport = true;
|
|
2235
|
-
}
|
|
2236
|
-
if (opts.clip) {
|
|
2237
|
-
const clip = {
|
|
2238
|
-
x: Math.round(opts.clip.x),
|
|
2239
|
-
y: Math.round(opts.clip.y),
|
|
2240
|
-
width: Math.round(Math.max(1, opts.clip.width)),
|
|
2241
|
-
height: Math.round(Math.max(1, opts.clip.height)),
|
|
2242
|
-
scale: 1
|
|
2243
|
-
};
|
|
2244
|
-
params.clip = clip;
|
|
2245
|
-
}
|
|
2246
|
-
if (opts.omitBackground) {
|
|
2247
|
-
params.omitBackground = true;
|
|
2248
|
-
}
|
|
2249
|
-
const result = await this.conn.send(
|
|
2250
|
-
"Page.captureScreenshot",
|
|
2251
|
-
params,
|
|
2252
|
-
this.sessionId
|
|
2253
|
-
);
|
|
2254
|
-
return Buffer.from(result.data, "base64");
|
|
3243
|
+
return this.mediaService.screenshot(opts);
|
|
2255
3244
|
}
|
|
2256
3245
|
async pdf(opts = {}) {
|
|
2257
|
-
|
|
2258
|
-
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
2259
|
-
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
2260
|
-
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
2261
|
-
if (opts.format) params.paperFormat = opts.format;
|
|
2262
|
-
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
2263
|
-
if (opts.margin) {
|
|
2264
|
-
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
2265
|
-
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
2266
|
-
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
2267
|
-
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
2268
|
-
}
|
|
2269
|
-
const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
|
|
2270
|
-
return Buffer.from(result.data, "base64");
|
|
3246
|
+
return this.mediaService.pdf(opts);
|
|
2271
3247
|
}
|
|
2272
3248
|
viewportSize() {
|
|
2273
|
-
return this._viewportSize
|
|
3249
|
+
return this._viewportSize;
|
|
2274
3250
|
}
|
|
2275
3251
|
async setViewportSize(size) {
|
|
2276
|
-
|
|
2277
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2278
|
-
{
|
|
2279
|
-
width: size.width,
|
|
2280
|
-
height: size.height,
|
|
2281
|
-
deviceScaleFactor: 1,
|
|
2282
|
-
mobile: false
|
|
2283
|
-
},
|
|
2284
|
-
this.sessionId
|
|
2285
|
-
);
|
|
2286
|
-
this._viewportSize = size;
|
|
3252
|
+
return this.mediaService.setViewportSize(size);
|
|
2287
3253
|
}
|
|
2288
|
-
/**
|
|
2289
|
-
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
2290
|
-
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
2291
|
-
*/
|
|
2292
3254
|
async setDeviceScaleFactor(dsf) {
|
|
2293
|
-
|
|
2294
|
-
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
2295
|
-
);
|
|
2296
|
-
await this.conn.send(
|
|
2297
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2298
|
-
{
|
|
2299
|
-
width: size.width,
|
|
2300
|
-
height: size.height,
|
|
2301
|
-
deviceScaleFactor: dsf,
|
|
2302
|
-
mobile: false
|
|
2303
|
-
},
|
|
2304
|
-
this.sessionId
|
|
2305
|
-
);
|
|
2306
|
-
this._viewportSize = size;
|
|
3255
|
+
return this.mediaService.setDeviceScaleFactor(dsf);
|
|
2307
3256
|
}
|
|
2308
|
-
// ── Scripts ─────────────────────────────────────────────────
|
|
2309
3257
|
async addInitScript(script) {
|
|
2310
3258
|
await this.conn.send(
|
|
2311
3259
|
"Page.addScriptToEvaluateOnNewDocument",
|
|
@@ -2433,83 +3381,17 @@ Last error: ${lastError.message}` : "";
|
|
|
2433
3381
|
}
|
|
2434
3382
|
}
|
|
2435
3383
|
// ── CDP helpers exposed for locator/element ─────────────────
|
|
2436
|
-
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2437
3384
|
async querySelector(selector) {
|
|
2438
|
-
|
|
2439
|
-
const found = await this.evaluate(`
|
|
2440
|
-
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2441
|
-
`).catch(() => false);
|
|
2442
|
-
if (!found) return 0;
|
|
2443
|
-
try {
|
|
2444
|
-
const search = await this.conn.send(
|
|
2445
|
-
"DOM.performSearch",
|
|
2446
|
-
{ query: selector.slice(6) },
|
|
2447
|
-
this.sessionId
|
|
2448
|
-
);
|
|
2449
|
-
if (search.nodeId) return search.nodeId;
|
|
2450
|
-
} catch {
|
|
2451
|
-
}
|
|
2452
|
-
return 1;
|
|
2453
|
-
}
|
|
2454
|
-
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2455
|
-
const doc = await withTimeout(
|
|
2456
|
-
this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
|
|
2457
|
-
8e3
|
|
2458
|
-
);
|
|
2459
|
-
if (!doc) return 0;
|
|
2460
|
-
const result = await withTimeout(
|
|
2461
|
-
this.conn.send(
|
|
2462
|
-
"DOM.querySelector",
|
|
2463
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2464
|
-
this.sessionId
|
|
2465
|
-
),
|
|
2466
|
-
8e3
|
|
2467
|
-
);
|
|
2468
|
-
if (!result) return 0;
|
|
2469
|
-
return result.nodeId;
|
|
3385
|
+
return this.domQueryService.querySelector(selector);
|
|
2470
3386
|
}
|
|
2471
|
-
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2472
3387
|
async querySelectorAll(selector) {
|
|
2473
|
-
|
|
2474
|
-
"DOM.getDocument",
|
|
2475
|
-
{ depth: 0 },
|
|
2476
|
-
this.sessionId
|
|
2477
|
-
);
|
|
2478
|
-
const result = await this.conn.send(
|
|
2479
|
-
"DOM.querySelectorAll",
|
|
2480
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2481
|
-
this.sessionId
|
|
2482
|
-
);
|
|
2483
|
-
return result.nodeIds ?? [];
|
|
3388
|
+
return this.domQueryService.querySelectorAll(selector);
|
|
2484
3389
|
}
|
|
2485
|
-
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2486
3390
|
async resolveNode(nodeId) {
|
|
2487
|
-
|
|
2488
|
-
"DOM.resolveNode",
|
|
2489
|
-
{ nodeId },
|
|
2490
|
-
this.sessionId
|
|
2491
|
-
);
|
|
2492
|
-
return result.object.objectId;
|
|
3391
|
+
return this.domQueryService.resolveNode(nodeId);
|
|
2493
3392
|
}
|
|
2494
|
-
/** Get the box model for a nodeId */
|
|
2495
3393
|
async getBoxModel(nodeId) {
|
|
2496
|
-
|
|
2497
|
-
const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
|
|
2498
|
-
const c = result.model?.content;
|
|
2499
|
-
if (!c || c.length < 8) return null;
|
|
2500
|
-
const x1 = c[0];
|
|
2501
|
-
const y1 = c[1];
|
|
2502
|
-
const x2 = c[4];
|
|
2503
|
-
const y2 = c[5];
|
|
2504
|
-
return {
|
|
2505
|
-
x: Math.min(x1, x2),
|
|
2506
|
-
y: Math.min(y1, y2),
|
|
2507
|
-
width: Math.abs(x2 - x1),
|
|
2508
|
-
height: Math.abs(y2 - y1)
|
|
2509
|
-
};
|
|
2510
|
-
} catch {
|
|
2511
|
-
return null;
|
|
2512
|
-
}
|
|
3394
|
+
return this.domQueryService.getBoxModel(nodeId);
|
|
2513
3395
|
}
|
|
2514
3396
|
/** Call a function on a RemoteObject */
|
|
2515
3397
|
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
@@ -2528,9 +3410,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2528
3410
|
async _cdpSend(method, params) {
|
|
2529
3411
|
return this.conn.send(method, params, this.sessionId);
|
|
2530
3412
|
}
|
|
2531
|
-
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2532
|
-
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2533
|
-
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2534
3413
|
setBeforeUnloadBehavior(mode) {
|
|
2535
3414
|
this._beforeUnloadAccept = mode === "accept";
|
|
2536
3415
|
}
|
|
@@ -2553,143 +3432,37 @@ Last error: ${lastError.message}` : "";
|
|
|
2553
3432
|
}
|
|
2554
3433
|
// ── Private: Event Setup ────────────────────────────────────
|
|
2555
3434
|
setupPageEvents() {
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
this.
|
|
2563
|
-
}
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
3435
|
+
setupPageEvents({
|
|
3436
|
+
conn: this.conn,
|
|
3437
|
+
sessionId: this.sessionId,
|
|
3438
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
|
|
3439
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3440
|
+
setUrl: (url) => {
|
|
3441
|
+
this._url = url;
|
|
3442
|
+
},
|
|
3443
|
+
currentUrl: () => this.url(),
|
|
3444
|
+
mainFrame: () => this.mainFrame(),
|
|
3445
|
+
markLoadFired: () => {
|
|
2567
3446
|
this._loadState.loadFired = true;
|
|
2568
|
-
}
|
|
2569
|
-
|
|
2570
|
-
this._subscriptions.push(
|
|
2571
|
-
this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
|
|
3447
|
+
},
|
|
3448
|
+
markDomContentFired: () => {
|
|
2572
3449
|
this._loadState.domContentFired = true;
|
|
2573
|
-
}
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
await this.conn.send("Page.handleJavaScriptDialog", {
|
|
2590
|
-
accept: false
|
|
2591
|
-
}, this.sessionId);
|
|
2592
|
-
}
|
|
2593
|
-
};
|
|
2594
|
-
this._emit("dialog", dialog);
|
|
2595
|
-
const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
|
|
2596
|
-
setTimeout(() => {
|
|
2597
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
|
|
2598
|
-
});
|
|
2599
|
-
}, 0);
|
|
2600
|
-
})
|
|
2601
|
-
);
|
|
2602
|
-
this._subscriptions.push(
|
|
2603
|
-
this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
|
|
2604
|
-
const p = params;
|
|
2605
|
-
let selector = "";
|
|
2606
|
-
try {
|
|
2607
|
-
const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2608
|
-
const attrs = result.node?.attributes || [];
|
|
2609
|
-
const idIdx = attrs.indexOf("id");
|
|
2610
|
-
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
2611
|
-
} catch {
|
|
2612
|
-
}
|
|
2613
|
-
if (!selector) {
|
|
2614
|
-
try {
|
|
2615
|
-
const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2616
|
-
const evalResult = await this.conn.send("Runtime.callFunctionOn", {
|
|
2617
|
-
objectId: result.objectId,
|
|
2618
|
-
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
2619
|
-
returnByValue: true
|
|
2620
|
-
}, this.sessionId);
|
|
2621
|
-
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
2622
|
-
} catch {
|
|
2623
|
-
}
|
|
2624
|
-
}
|
|
2625
|
-
const fileChooser = {
|
|
2626
|
-
selector,
|
|
2627
|
-
isMultiple: p.mode === "selectMultiple",
|
|
2628
|
-
setFiles: async (files) => {
|
|
2629
|
-
const fileArray = Array.isArray(files) ? files : [files];
|
|
2630
|
-
await this.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
2631
|
-
}
|
|
2632
|
-
};
|
|
2633
|
-
this._emit("filechooser", fileChooser);
|
|
2634
|
-
})
|
|
2635
|
-
);
|
|
2636
|
-
}
|
|
2637
|
-
setupNetworkEvents() {
|
|
2638
|
-
this._subscriptions.push(
|
|
2639
|
-
this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
|
|
2640
|
-
const p = params;
|
|
2641
|
-
this.inflightRequests.add(p.requestId);
|
|
2642
|
-
this._storeNetworkRequest(p.requestId, {
|
|
2643
|
-
url: p.request.url,
|
|
2644
|
-
method: p.request.method,
|
|
2645
|
-
headers: p.request.headers,
|
|
2646
|
-
postData: p.request.postData ?? null,
|
|
2647
|
-
resourceType: p.type
|
|
2648
|
-
});
|
|
2649
|
-
this._emit("request", createXBRequest(
|
|
2650
|
-
null,
|
|
2651
|
-
{
|
|
2652
|
-
requestId: p.requestId,
|
|
2653
|
-
url: p.request.url,
|
|
2654
|
-
method: p.request.method,
|
|
2655
|
-
headers: p.request.headers,
|
|
2656
|
-
postData: p.request.postData ?? null,
|
|
2657
|
-
resourceType: p.type
|
|
2658
|
-
}
|
|
2659
|
-
));
|
|
2660
|
-
this.checkNetworkIdle();
|
|
2661
|
-
})
|
|
2662
|
-
);
|
|
2663
|
-
this._subscriptions.push(
|
|
2664
|
-
this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
|
|
2665
|
-
const p = params;
|
|
2666
|
-
this._storeNetworkResponse(p.requestId, {
|
|
2667
|
-
status: p.response.status,
|
|
2668
|
-
url: p.response.url,
|
|
2669
|
-
headers: p.response.headers
|
|
2670
|
-
});
|
|
2671
|
-
this._emit("response", createXBResponse(
|
|
2672
|
-
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
2673
|
-
this.conn,
|
|
2674
|
-
this.sessionId
|
|
2675
|
-
));
|
|
2676
|
-
})
|
|
2677
|
-
);
|
|
2678
|
-
this._subscriptions.push(
|
|
2679
|
-
this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
|
|
2680
|
-
const p = params;
|
|
2681
|
-
this.inflightRequests.delete(p.requestId);
|
|
2682
|
-
this._emit("requestfinished", p);
|
|
2683
|
-
this.checkNetworkIdle();
|
|
2684
|
-
})
|
|
2685
|
-
);
|
|
2686
|
-
this._subscriptions.push(
|
|
2687
|
-
this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
|
|
2688
|
-
const p = params;
|
|
2689
|
-
this.inflightRequests.delete(p.requestId);
|
|
2690
|
-
this.checkNetworkIdle();
|
|
2691
|
-
})
|
|
2692
|
-
);
|
|
3450
|
+
},
|
|
3451
|
+
getBeforeUnloadAccept: () => this._beforeUnloadAccept,
|
|
3452
|
+
setInputFiles: (selector, files) => this.setInputFiles(selector, files)
|
|
3453
|
+
});
|
|
3454
|
+
}
|
|
3455
|
+
setupNetworkEvents() {
|
|
3456
|
+
setupNetworkEvents({
|
|
3457
|
+
conn: this.conn,
|
|
3458
|
+
sessionId: this.sessionId,
|
|
3459
|
+
state: { inflightRequests: this.inflightRequests },
|
|
3460
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3461
|
+
storeRequest: (id, data) => this._storeNetworkRequest(id, data),
|
|
3462
|
+
storeResponse: (id, data) => this._storeNetworkResponse(id, data),
|
|
3463
|
+
checkNetworkIdle: () => this.checkNetworkIdle(),
|
|
3464
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
|
|
3465
|
+
});
|
|
2693
3466
|
}
|
|
2694
3467
|
setupConsoleEvents() {
|
|
2695
3468
|
this._subscriptions.push(
|
|
@@ -2735,8 +3508,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2735
3508
|
// ── Network Data Store (for waitForResponse/waitForRequest) ──
|
|
2736
3509
|
_networkResponses = /* @__PURE__ */ new Map();
|
|
2737
3510
|
_networkRequests = /* @__PURE__ */ new Map();
|
|
2738
|
-
_routeHandlers = [];
|
|
2739
|
-
_interceptionEnabled = false;
|
|
2740
3511
|
_beforeUnloadAccept = true;
|
|
2741
3512
|
/** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
|
|
2742
3513
|
_storeNetworkRequest(requestId, data) {
|
|
@@ -2745,284 +3516,30 @@ Last error: ${lastError.message}` : "";
|
|
|
2745
3516
|
_storeNetworkResponse(requestId, data) {
|
|
2746
3517
|
this._networkResponses.set(requestId, { requestId, ...data });
|
|
2747
3518
|
}
|
|
2748
|
-
// ── waitForResponse ─────────────────────────────────────────
|
|
2749
3519
|
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
2750
|
-
|
|
2751
|
-
const predicate = createResponsePredicate(urlOrPredicate);
|
|
2752
|
-
for (const [, data] of this._networkResponses) {
|
|
2753
|
-
const response = createXBResponse(data, this.conn, this.sessionId);
|
|
2754
|
-
if (predicate(response)) return response;
|
|
2755
|
-
}
|
|
2756
|
-
return new Promise((resolve, reject) => {
|
|
2757
|
-
const timer = setTimeout(() => {
|
|
2758
|
-
this._emitter.removeListener("response", handler);
|
|
2759
|
-
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
2760
|
-
}, timeout);
|
|
2761
|
-
const handler = (params) => {
|
|
2762
|
-
let response;
|
|
2763
|
-
const respObj = params;
|
|
2764
|
-
if (respObj.response) {
|
|
2765
|
-
const data = {
|
|
2766
|
-
requestId: respObj.requestId || "",
|
|
2767
|
-
status: respObj.response.status || 0,
|
|
2768
|
-
url: respObj.response.url || "",
|
|
2769
|
-
headers: respObj.response.headers || {}
|
|
2770
|
-
};
|
|
2771
|
-
response = createXBResponse(data, this.conn, this.sessionId);
|
|
2772
|
-
} else if (typeof params.status === "function") {
|
|
2773
|
-
response = params;
|
|
2774
|
-
} else {
|
|
2775
|
-
return;
|
|
2776
|
-
}
|
|
2777
|
-
if (predicate(response)) {
|
|
2778
|
-
clearTimeout(timer);
|
|
2779
|
-
this._emitter.removeListener("response", handler);
|
|
2780
|
-
resolve(response);
|
|
2781
|
-
}
|
|
2782
|
-
};
|
|
2783
|
-
this._emitter.on("response", handler);
|
|
2784
|
-
});
|
|
3520
|
+
return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
|
|
2785
3521
|
}
|
|
2786
|
-
// ── waitForRequest ──────────────────────────────────────────
|
|
2787
3522
|
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
2788
|
-
|
|
2789
|
-
const predicate = createRequestPredicate(urlOrPredicate);
|
|
2790
|
-
for (const [, data] of this._networkRequests) {
|
|
2791
|
-
const request = createXBRequest(this, data);
|
|
2792
|
-
if (predicate(request)) return request;
|
|
2793
|
-
}
|
|
2794
|
-
return new Promise((resolve, reject) => {
|
|
2795
|
-
const timer = setTimeout(() => {
|
|
2796
|
-
this._emitter.removeListener("request", handler);
|
|
2797
|
-
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
2798
|
-
}, timeout);
|
|
2799
|
-
const handler = (params) => {
|
|
2800
|
-
let request;
|
|
2801
|
-
const reqObj = params;
|
|
2802
|
-
if (reqObj.request) {
|
|
2803
|
-
request = createXBRequest(this, {
|
|
2804
|
-
requestId: reqObj.requestId || "",
|
|
2805
|
-
url: reqObj.request.url || "",
|
|
2806
|
-
method: reqObj.request.method || "",
|
|
2807
|
-
headers: reqObj.request.headers || {},
|
|
2808
|
-
postData: reqObj.request.postData ?? null,
|
|
2809
|
-
resourceType: reqObj.type || ""
|
|
2810
|
-
});
|
|
2811
|
-
} else if (typeof params.url === "function") {
|
|
2812
|
-
request = params;
|
|
2813
|
-
} else {
|
|
2814
|
-
return;
|
|
2815
|
-
}
|
|
2816
|
-
if (predicate(request)) {
|
|
2817
|
-
clearTimeout(timer);
|
|
2818
|
-
this._emitter.removeListener("request", handler);
|
|
2819
|
-
resolve(request);
|
|
2820
|
-
}
|
|
2821
|
-
};
|
|
2822
|
-
this._emitter.on("request", handler);
|
|
2823
|
-
});
|
|
3523
|
+
return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
|
|
2824
3524
|
}
|
|
2825
|
-
// ── waitForURL ──────────────────────────────────────────────
|
|
2826
3525
|
async waitForURL(url, opts = {}) {
|
|
2827
|
-
|
|
2828
|
-
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
2829
|
-
if (checkFn(this._url)) return;
|
|
2830
|
-
return new Promise((resolve, reject) => {
|
|
2831
|
-
const timer = setTimeout(() => {
|
|
2832
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2833
|
-
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
2834
|
-
}, timeout);
|
|
2835
|
-
const handler = () => {
|
|
2836
|
-
if (checkFn(this._url)) {
|
|
2837
|
-
clearTimeout(timer);
|
|
2838
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2839
|
-
resolve();
|
|
2840
|
-
}
|
|
2841
|
-
};
|
|
2842
|
-
this._emitter.on("framenavigated", handler);
|
|
2843
|
-
});
|
|
2844
|
-
}
|
|
2845
|
-
// ── route / unroute ─────────────────────────────────────────
|
|
2846
|
-
async route(url, handler) {
|
|
2847
|
-
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2848
|
-
this._routeHandlers.push({ pattern: String(url), regex, handler });
|
|
2849
|
-
if (!this._interceptionEnabled) {
|
|
2850
|
-
this._interceptionEnabled = true;
|
|
2851
|
-
await this.conn.send("Fetch.enable", {
|
|
2852
|
-
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
2853
|
-
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
2854
|
-
// 会顶掉 _init 的 auth 配置)
|
|
2855
|
-
handleAuthRequests: true
|
|
2856
|
-
}, this.sessionId);
|
|
2857
|
-
this._subscriptions.push(
|
|
2858
|
-
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
2859
|
-
this._handleRequestPaused(params);
|
|
2860
|
-
})
|
|
2861
|
-
);
|
|
2862
|
-
}
|
|
3526
|
+
return this.networkWaitService.waitForURL(url, opts);
|
|
2863
3527
|
}
|
|
2864
|
-
async
|
|
2865
|
-
|
|
2866
|
-
this._routeHandlers = this._routeHandlers.filter(
|
|
2867
|
-
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2868
|
-
);
|
|
2869
|
-
if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
|
|
2870
|
-
this._interceptionEnabled = false;
|
|
2871
|
-
await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
|
|
2872
|
-
});
|
|
2873
|
-
}
|
|
3528
|
+
async route(pattern, handler) {
|
|
3529
|
+
return this.networkRouteService.route(pattern, handler);
|
|
2874
3530
|
}
|
|
2875
|
-
async
|
|
2876
|
-
|
|
2877
|
-
for (const { regex, handler } of this._routeHandlers) {
|
|
2878
|
-
if (regex.test(requestUrl)) {
|
|
2879
|
-
this._emit("request", createXBRequest(
|
|
2880
|
-
null,
|
|
2881
|
-
{
|
|
2882
|
-
requestId: params.requestId,
|
|
2883
|
-
url: params.request.url,
|
|
2884
|
-
method: params.request.method,
|
|
2885
|
-
headers: params.request.headers,
|
|
2886
|
-
postData: params.request.postData ?? null,
|
|
2887
|
-
resourceType: params.resourceType
|
|
2888
|
-
}
|
|
2889
|
-
));
|
|
2890
|
-
const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
|
|
2891
|
-
try {
|
|
2892
|
-
await handler(route);
|
|
2893
|
-
} catch {
|
|
2894
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
2895
|
-
requestId: params.requestId
|
|
2896
|
-
}, this.sessionId).catch(() => {
|
|
2897
|
-
});
|
|
2898
|
-
}
|
|
2899
|
-
return;
|
|
2900
|
-
}
|
|
2901
|
-
}
|
|
2902
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
2903
|
-
requestId: params.requestId
|
|
2904
|
-
}, this.sessionId).catch(() => {
|
|
2905
|
-
});
|
|
3531
|
+
async unroute(pattern) {
|
|
3532
|
+
return this.networkRouteService.unroute(pattern);
|
|
2906
3533
|
}
|
|
2907
|
-
// ── setInputFiles ───────────────────────────────────────────
|
|
2908
|
-
/**
|
|
2909
|
-
* sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
|
|
2910
|
-
* dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
|
|
2911
|
-
* 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
|
|
2912
|
-
* 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
|
|
2913
|
-
* 中心)。
|
|
2914
|
-
*/
|
|
2915
3534
|
async dropFiles(selector, payload) {
|
|
2916
|
-
|
|
2917
|
-
(function() {
|
|
2918
|
-
var el = ${queryJS(selector)};
|
|
2919
|
-
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
2920
|
-
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
2921
|
-
var bin = atob(b64);
|
|
2922
|
-
var buf = new Uint8Array(bin.length);
|
|
2923
|
-
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
2924
|
-
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
2925
|
-
var dt = new DataTransfer();
|
|
2926
|
-
dt.items.add(file);
|
|
2927
|
-
var rect = el.getBoundingClientRect();
|
|
2928
|
-
var opts = {
|
|
2929
|
-
bubbles: true, cancelable: true,
|
|
2930
|
-
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
2931
|
-
};
|
|
2932
|
-
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
2933
|
-
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
2934
|
-
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
2935
|
-
})()
|
|
2936
|
-
`);
|
|
3535
|
+
return this.fileInputService.dropFiles(selector, payload);
|
|
2937
3536
|
}
|
|
2938
3537
|
async setInputFiles(selector, files) {
|
|
2939
|
-
|
|
2940
|
-
const fileList = fileArr.map((f) => ({
|
|
2941
|
-
name: f.name,
|
|
2942
|
-
type: f.mimeType,
|
|
2943
|
-
dataBase64: f.buffer.toString("base64")
|
|
2944
|
-
}));
|
|
2945
|
-
await this.evaluate(`
|
|
2946
|
-
(function() {
|
|
2947
|
-
var selector = ${JSON.stringify(selector)};
|
|
2948
|
-
var input = ${queryJS(selector)};
|
|
2949
|
-
if (!input) throw new Error('Element not found: ' + selector);
|
|
2950
|
-
|
|
2951
|
-
var fileList = ${JSON.stringify(fileList)};
|
|
2952
|
-
var dt = new DataTransfer();
|
|
2953
|
-
|
|
2954
|
-
fileList.forEach(function(f) {
|
|
2955
|
-
var binary = atob(f.dataBase64);
|
|
2956
|
-
var bytes = new Uint8Array(binary.length);
|
|
2957
|
-
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
2958
|
-
var blob = new Blob([bytes], { type: f.type });
|
|
2959
|
-
var file = new File([blob], f.name, { type: f.type });
|
|
2960
|
-
dt.items.add(file);
|
|
2961
|
-
});
|
|
2962
|
-
|
|
2963
|
-
input.files = dt.files;
|
|
2964
|
-
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2965
|
-
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
2966
|
-
})()
|
|
2967
|
-
`);
|
|
3538
|
+
return this.fileInputService.setInputFiles(selector, files);
|
|
2968
3539
|
}
|
|
2969
|
-
// ── dragAndDrop ─────────────────────────────────────────────
|
|
2970
3540
|
async dragAndDrop(source, target) {
|
|
2971
|
-
|
|
2972
|
-
(function() {
|
|
2973
|
-
const el = ${queryJS(source)};
|
|
2974
|
-
if (!el) throw new Error('Source not found: ${source}');
|
|
2975
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
2976
|
-
const r = el.getBoundingClientRect();
|
|
2977
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
2978
|
-
})()
|
|
2979
|
-
`);
|
|
2980
|
-
const targetRect = await this.evaluate(`
|
|
2981
|
-
(function() {
|
|
2982
|
-
const el = ${queryJS(target)};
|
|
2983
|
-
if (!el) throw new Error('Target not found: ${target}');
|
|
2984
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
2985
|
-
const r = el.getBoundingClientRect();
|
|
2986
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
2987
|
-
})()
|
|
2988
|
-
`);
|
|
2989
|
-
const sx = sourceRect.x + sourceRect.width / 2;
|
|
2990
|
-
const sy = sourceRect.y + sourceRect.height / 2;
|
|
2991
|
-
const tx = targetRect.x + targetRect.width / 2;
|
|
2992
|
-
const ty = targetRect.y + targetRect.height / 2;
|
|
2993
|
-
try {
|
|
2994
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
2995
|
-
type: "dragStart",
|
|
2996
|
-
x: sx,
|
|
2997
|
-
y: sy,
|
|
2998
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
2999
|
-
}, this.sessionId);
|
|
3000
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3001
|
-
type: "dragOver",
|
|
3002
|
-
x: tx,
|
|
3003
|
-
y: ty,
|
|
3004
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3005
|
-
}, this.sessionId);
|
|
3006
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3007
|
-
type: "drop",
|
|
3008
|
-
x: tx,
|
|
3009
|
-
y: ty,
|
|
3010
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3011
|
-
}, this.sessionId);
|
|
3012
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3013
|
-
type: "dragCancel",
|
|
3014
|
-
x: sx,
|
|
3015
|
-
y: sy,
|
|
3016
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3017
|
-
}, this.sessionId);
|
|
3018
|
-
} catch {
|
|
3019
|
-
await this.mouse.move(sx, sy);
|
|
3020
|
-
await this.mouse.down();
|
|
3021
|
-
await this.mouse.move(tx, ty, { steps: 10 });
|
|
3022
|
-
await this.mouse.up();
|
|
3023
|
-
}
|
|
3541
|
+
return this.fileInputService.dragAndDrop(source, target);
|
|
3024
3542
|
}
|
|
3025
|
-
// ── setOfflineMode ──────────────────────────────────────────
|
|
3026
3543
|
async setOfflineMode(offline) {
|
|
3027
3544
|
await this.conn.send("Network.emulateNetworkConditions", {
|
|
3028
3545
|
offline,
|
|
@@ -3318,12 +3835,22 @@ var XBBrowserImpl = class {
|
|
|
3318
3835
|
this._exitHandler = null;
|
|
3319
3836
|
}
|
|
3320
3837
|
if (this.childProcess) {
|
|
3321
|
-
const { killChrome: killChrome2 } = await import("./launcher-
|
|
3838
|
+
const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3322
3839
|
await killChrome2(this.childProcess, this.tmpDir);
|
|
3323
3840
|
}
|
|
3324
3841
|
await this.conn.close();
|
|
3325
3842
|
this._emitter.emit("disconnected");
|
|
3326
3843
|
}
|
|
3844
|
+
async disconnect() {
|
|
3845
|
+
if (this._disconnected) return;
|
|
3846
|
+
this._disconnected = true;
|
|
3847
|
+
if (this._exitHandler) {
|
|
3848
|
+
process.removeListener("exit", this._exitHandler);
|
|
3849
|
+
this._exitHandler = null;
|
|
3850
|
+
}
|
|
3851
|
+
await this.conn.close();
|
|
3852
|
+
this._emitter.emit("disconnected");
|
|
3853
|
+
}
|
|
3327
3854
|
async newContext(opts = {}) {
|
|
3328
3855
|
if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
|
|
3329
3856
|
opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
|
|
@@ -3488,7 +4015,7 @@ var XBBrowserImpl = class {
|
|
|
3488
4015
|
if (pageTargets.length === 0 && httpFallbackUrl) {
|
|
3489
4016
|
console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
|
|
3490
4017
|
try {
|
|
3491
|
-
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-
|
|
4018
|
+
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3492
4019
|
const httpPages = await getCDPTargets2(httpFallbackUrl);
|
|
3493
4020
|
console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
|
|
3494
4021
|
for (const p of httpPages) {
|
|
@@ -3934,6 +4461,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
|
|
|
3934
4461
|
return null;
|
|
3935
4462
|
}
|
|
3936
4463
|
|
|
4464
|
+
// src/cdp-interceptor/rules/humanize-transform.ts
|
|
4465
|
+
var CURSOR_KEY = "humanize-cursor";
|
|
4466
|
+
var KEYS_KEY = "humanize-keys";
|
|
4467
|
+
var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
|
|
4468
|
+
var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
|
|
4469
|
+
function rand2(min, max) {
|
|
4470
|
+
return min + Math.random() * (max - min);
|
|
4471
|
+
}
|
|
4472
|
+
function roundCoordinate(value) {
|
|
4473
|
+
return Math.round(value * 100) / 100;
|
|
4474
|
+
}
|
|
4475
|
+
function humanMousePath(fromX, fromY, toX, toY) {
|
|
4476
|
+
const dist = Math.hypot(toX - fromX, toY - fromY);
|
|
4477
|
+
const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
|
|
4478
|
+
const shortMove = dist < 120;
|
|
4479
|
+
const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
|
|
4480
|
+
const dir = Math.random() < 0.5 ? 1 : -1;
|
|
4481
|
+
const dx = toX - fromX;
|
|
4482
|
+
const dy = toY - fromY;
|
|
4483
|
+
const d = dist || 1;
|
|
4484
|
+
const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
|
|
4485
|
+
const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
|
|
4486
|
+
const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
|
|
4487
|
+
const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
|
|
4488
|
+
const amp = shortMove ? Math.min(2, 3.2) : 3.2;
|
|
4489
|
+
const points = [];
|
|
4490
|
+
for (let i = 1; i <= n; i++) {
|
|
4491
|
+
const t = i / n;
|
|
4492
|
+
const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
|
|
4493
|
+
const mt = 1 - eased;
|
|
4494
|
+
const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
|
|
4495
|
+
const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
|
|
4496
|
+
points.push({
|
|
4497
|
+
x: roundCoordinate(px + rand2(-amp, amp)),
|
|
4498
|
+
y: roundCoordinate(py + rand2(-amp, amp)),
|
|
4499
|
+
delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
|
|
4500
|
+
});
|
|
4501
|
+
}
|
|
4502
|
+
if (!shortMove) {
|
|
4503
|
+
const over = rand2(6, 14);
|
|
4504
|
+
points.push({
|
|
4505
|
+
x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
|
|
4506
|
+
y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
|
|
4507
|
+
delay: Math.round(rand2(14, 30))
|
|
4508
|
+
});
|
|
4509
|
+
points.push({
|
|
4510
|
+
x: roundCoordinate(toX + dx / d * over * 0.4),
|
|
4511
|
+
y: roundCoordinate(toY + dy / d * over * 0.4),
|
|
4512
|
+
delay: Math.round(rand2(14, 30))
|
|
4513
|
+
});
|
|
4514
|
+
}
|
|
4515
|
+
points.push({
|
|
4516
|
+
x: roundCoordinate(toX + rand2(-1, 1)),
|
|
4517
|
+
y: roundCoordinate(toY + rand2(-1, 1)),
|
|
4518
|
+
delay: Math.round(rand2(14, 30))
|
|
4519
|
+
});
|
|
4520
|
+
return points;
|
|
4521
|
+
}
|
|
4522
|
+
function characterKeyEvents(text) {
|
|
4523
|
+
const events = [];
|
|
4524
|
+
for (const char of text) {
|
|
4525
|
+
if (char === "\n") {
|
|
4526
|
+
events.push(
|
|
4527
|
+
{ type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
|
|
4528
|
+
{ type: "char", text: "\r" },
|
|
4529
|
+
{ type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
|
|
4530
|
+
);
|
|
4531
|
+
continue;
|
|
4532
|
+
}
|
|
4533
|
+
events.push(
|
|
4534
|
+
{ type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
|
|
4535
|
+
{ type: "char", text: char },
|
|
4536
|
+
{ type: "keyUp", key: char }
|
|
4537
|
+
);
|
|
4538
|
+
}
|
|
4539
|
+
return events;
|
|
4540
|
+
}
|
|
4541
|
+
function isMouseEvent(method) {
|
|
4542
|
+
return method === "Input.dispatchMouseEvent";
|
|
4543
|
+
}
|
|
4544
|
+
var humanizeTransformRule = {
|
|
4545
|
+
id: "humanize-transform",
|
|
4546
|
+
name: "Humanize Trusted Input Transform",
|
|
4547
|
+
priority: 45,
|
|
4548
|
+
canHandle(ctx) {
|
|
4549
|
+
return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
|
|
4550
|
+
},
|
|
4551
|
+
evaluate(ctx) {
|
|
4552
|
+
if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
|
|
4553
|
+
return this.transformMouseEvent(ctx);
|
|
4554
|
+
},
|
|
4555
|
+
transformMouseEvent(ctx) {
|
|
4556
|
+
const params = ctx.params;
|
|
4557
|
+
if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
|
|
4558
|
+
const x = params.x;
|
|
4559
|
+
const y = params.y;
|
|
4560
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
4561
|
+
ctx.sessionState.set(CURSOR_KEY, { x, y });
|
|
4562
|
+
}
|
|
4563
|
+
return null;
|
|
4564
|
+
}
|
|
4565
|
+
const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
|
|
4566
|
+
const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
|
|
4567
|
+
ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
|
|
4568
|
+
if (jump < 32) return null;
|
|
4569
|
+
const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
|
|
4570
|
+
return {
|
|
4571
|
+
ruleId: this.id,
|
|
4572
|
+
action: "transform",
|
|
4573
|
+
severity: "info",
|
|
4574
|
+
reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
|
|
4575
|
+
suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
|
|
4576
|
+
transformedParams: { __sequence: path.map((point) => ({
|
|
4577
|
+
method: "Input.dispatchMouseEvent",
|
|
4578
|
+
params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
|
|
4579
|
+
delayMs: point.delay
|
|
4580
|
+
})) }
|
|
4581
|
+
};
|
|
4582
|
+
},
|
|
4583
|
+
transformInsertText(ctx) {
|
|
4584
|
+
const params = ctx.params;
|
|
4585
|
+
const text = params.text ?? "";
|
|
4586
|
+
if (!text) return null;
|
|
4587
|
+
const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
|
|
4588
|
+
const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
|
|
4589
|
+
const events = characterKeyEvents(text).map((event, index) => ({
|
|
4590
|
+
method: "Input.dispatchKeyEvent",
|
|
4591
|
+
params: event,
|
|
4592
|
+
delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
|
|
4593
|
+
}));
|
|
4594
|
+
timing.lastDelay = bucket;
|
|
4595
|
+
ctx.sessionState.set(KEYS_KEY, timing);
|
|
4596
|
+
return {
|
|
4597
|
+
ruleId: this.id,
|
|
4598
|
+
action: "transform",
|
|
4599
|
+
severity: "info",
|
|
4600
|
+
reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
|
|
4601
|
+
suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
|
|
4602
|
+
transformedParams: { __sequence: events }
|
|
4603
|
+
};
|
|
4604
|
+
}
|
|
4605
|
+
};
|
|
4606
|
+
|
|
3937
4607
|
// src/cdp-interceptor/rules/automation-signals.ts
|
|
3938
4608
|
var AUTOMATION_PATTERNS = [
|
|
3939
4609
|
// ── Playwright markers ─────────────────────────
|
|
@@ -4452,6 +5122,7 @@ var BUILTIN_RULES = [
|
|
|
4452
5122
|
eventSimulationRule,
|
|
4453
5123
|
mouseTrajectoryRule,
|
|
4454
5124
|
inputKeystrokeRule,
|
|
5125
|
+
humanizeTransformRule,
|
|
4455
5126
|
emulationOverrideRule,
|
|
4456
5127
|
networkAnomalyRule,
|
|
4457
5128
|
pageLifecycleRule
|
|
@@ -4484,8 +5155,10 @@ function createRuleEngine(customRules) {
|
|
|
4484
5155
|
if (isProbeMarked(code)) return null;
|
|
4485
5156
|
} catch {
|
|
4486
5157
|
}
|
|
5158
|
+
const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
|
|
4487
5159
|
for (const rule of rules) {
|
|
4488
5160
|
if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
|
|
5161
|
+
if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
|
|
4489
5162
|
const decision = rule.evaluate(fullCtx);
|
|
4490
5163
|
if (!decision) continue;
|
|
4491
5164
|
if (decision.action !== "pass") return decision;
|
|
@@ -4627,6 +5300,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
|
|
|
4627
5300
|
if (decision && decision.action === "block") {
|
|
4628
5301
|
throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
|
|
4629
5302
|
}
|
|
5303
|
+
if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
|
|
5304
|
+
const sequence = decision.transformedParams.__sequence;
|
|
5305
|
+
let last;
|
|
5306
|
+
for (const step of sequence) {
|
|
5307
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
5308
|
+
last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
|
|
5309
|
+
}
|
|
5310
|
+
return last;
|
|
5311
|
+
}
|
|
4630
5312
|
}
|
|
4631
5313
|
if (this.closed) {
|
|
4632
5314
|
throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
|
|
@@ -4869,7 +5551,7 @@ async function launch(options = {}) {
|
|
|
4869
5551
|
const bv = await conn.send("Browser.getVersion");
|
|
4870
5552
|
const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
|
|
4871
5553
|
if (m && !options.stealthConfig?.uaChProfile) {
|
|
4872
|
-
const { deriveUaChProfileForBinary } = await import("./stealth-
|
|
5554
|
+
const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
|
|
4873
5555
|
stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
|
|
4874
5556
|
}
|
|
4875
5557
|
} catch {
|