@xbrowser/cli 1.28.0 → 1.29.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/dist/{browser-NYYCR4O7.js → browser-2K3XYAKM.js} +5 -3
- package/dist/{browser-ZD53IMUJ.js → browser-OTEMG5NL.js} +6 -4
- package/dist/{browser-4IYIHZ6R.js → browser-XD3IOU5I.js} +8 -6
- package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-AAS55KT2.js} +4 -4
- package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-O5I7SJ24.js} +3 -3
- package/dist/{cdp-driver-HB744QB4.js → cdp-driver-XTPY7EXP.js} +1296 -852
- package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
- package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
- package/dist/{chunk-3PUOISKE.js → chunk-CO2ZVOVT.js} +496 -452
- package/dist/{chunk-V6KGBU5J.js → chunk-FCPVQFTQ.js} +1011 -1038
- package/dist/{chunk-WK3INZLA.js → chunk-GDKKVT2P.js} +750 -651
- package/dist/{chunk-HSYRAV3H.js → chunk-LFSLNHW5.js} +1846 -1358
- package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
- package/dist/{chunk-J3HXZVSN.js → chunk-N5XTLNKS.js} +1166 -868
- package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
- package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
- package/dist/{chunk-ME5FO5YV.js → chunk-NQPXZ74W.js} +1296 -852
- package/dist/{chunk-KECYFWJO.js → chunk-P33R7F2D.js} +413 -384
- package/dist/{chunk-OEC7ZSFW.js → chunk-SCYBNSOG.js} +1560 -1461
- package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
- package/dist/{chunk-IR6C24P7.js → chunk-UZ6XPUBD.js} +1030 -1048
- package/dist/cli.js +3398 -3357
- package/dist/daemon-main.js +737 -707
- package/dist/index.d.ts +362 -474
- package/dist/index.js +5730 -5689
- 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/{server-JXF3JOAM.js → server-LNZTDAKT.js} +4 -4
- package/dist/{server-26SE6YZR.js → server-ZTI2K5YJ.js} +7 -7
- package/dist/{session-recorder-GEZVQBKW.js → session-recorder-DF2YGH2E.js} +1 -1
- package/dist/{session-recorder-563ISSJK.js → session-recorder-R3GDGXLJ.js} +1 -1
- package/dist/{session-replayer-TXTNTG33.js → session-replayer-CLTZ2URU.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 +6 -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";
|
|
@@ -1331,6 +1331,216 @@ var XBElementHandleImpl = class {
|
|
|
1331
1331
|
}
|
|
1332
1332
|
};
|
|
1333
1333
|
|
|
1334
|
+
// src/cdp-driver/page-media.ts
|
|
1335
|
+
var MediaService = class {
|
|
1336
|
+
constructor(options) {
|
|
1337
|
+
this.options = options;
|
|
1338
|
+
}
|
|
1339
|
+
options;
|
|
1340
|
+
async screenshot(opts = {}) {
|
|
1341
|
+
const params = {
|
|
1342
|
+
format: opts.type ?? "png"
|
|
1343
|
+
};
|
|
1344
|
+
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
1345
|
+
params.quality = opts.quality;
|
|
1346
|
+
}
|
|
1347
|
+
if (opts.fullPage) {
|
|
1348
|
+
params.captureBeyondViewport = true;
|
|
1349
|
+
}
|
|
1350
|
+
if (opts.clip) {
|
|
1351
|
+
const clip = {
|
|
1352
|
+
x: Math.round(opts.clip.x),
|
|
1353
|
+
y: Math.round(opts.clip.y),
|
|
1354
|
+
width: Math.round(Math.max(1, opts.clip.width)),
|
|
1355
|
+
height: Math.round(Math.max(1, opts.clip.height)),
|
|
1356
|
+
scale: 1
|
|
1357
|
+
};
|
|
1358
|
+
params.clip = clip;
|
|
1359
|
+
}
|
|
1360
|
+
if (opts.omitBackground) {
|
|
1361
|
+
params.omitBackground = true;
|
|
1362
|
+
}
|
|
1363
|
+
const result = await this.options.conn.send(
|
|
1364
|
+
"Page.captureScreenshot",
|
|
1365
|
+
params,
|
|
1366
|
+
this.options.sessionId
|
|
1367
|
+
);
|
|
1368
|
+
return Buffer.from(result.data, "base64");
|
|
1369
|
+
}
|
|
1370
|
+
async pdf(opts = {}) {
|
|
1371
|
+
const params = {};
|
|
1372
|
+
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
1373
|
+
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
1374
|
+
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
1375
|
+
if (opts.format) params.paperFormat = opts.format;
|
|
1376
|
+
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
1377
|
+
if (opts.margin) {
|
|
1378
|
+
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
1379
|
+
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
1380
|
+
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
1381
|
+
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
1382
|
+
}
|
|
1383
|
+
const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
|
|
1384
|
+
return Buffer.from(result.data, "base64");
|
|
1385
|
+
}
|
|
1386
|
+
viewportSize() {
|
|
1387
|
+
return this.options.viewportSize ?? null;
|
|
1388
|
+
}
|
|
1389
|
+
async setViewportSize(size) {
|
|
1390
|
+
await this.options.conn.send(
|
|
1391
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1392
|
+
{
|
|
1393
|
+
width: size.width,
|
|
1394
|
+
height: size.height,
|
|
1395
|
+
deviceScaleFactor: 1,
|
|
1396
|
+
mobile: false
|
|
1397
|
+
},
|
|
1398
|
+
this.options.sessionId
|
|
1399
|
+
);
|
|
1400
|
+
this.options.onViewportSize(size);
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
1404
|
+
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
1405
|
+
*/
|
|
1406
|
+
async setDeviceScaleFactor(dsf) {
|
|
1407
|
+
const size = this.options.viewportSize ?? await this.options.evaluate(
|
|
1408
|
+
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
1409
|
+
);
|
|
1410
|
+
await this.options.conn.send(
|
|
1411
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1412
|
+
{
|
|
1413
|
+
width: size.width,
|
|
1414
|
+
height: size.height,
|
|
1415
|
+
deviceScaleFactor: dsf,
|
|
1416
|
+
mobile: false
|
|
1417
|
+
},
|
|
1418
|
+
this.options.sessionId
|
|
1419
|
+
);
|
|
1420
|
+
this.options.onViewportSize(size);
|
|
1421
|
+
}
|
|
1422
|
+
// ── Scripts ─────────────────────────────────────────────────
|
|
1423
|
+
};
|
|
1424
|
+
|
|
1425
|
+
// src/cdp-driver/page-file-input.ts
|
|
1426
|
+
var FileInputService = class {
|
|
1427
|
+
constructor(options) {
|
|
1428
|
+
this.options = options;
|
|
1429
|
+
}
|
|
1430
|
+
options;
|
|
1431
|
+
async dropFiles(selector, payload) {
|
|
1432
|
+
await this.options.evaluate(`
|
|
1433
|
+
(function() {
|
|
1434
|
+
var el = ${queryJS(selector)};
|
|
1435
|
+
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
1436
|
+
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
1437
|
+
var bin = atob(b64);
|
|
1438
|
+
var buf = new Uint8Array(bin.length);
|
|
1439
|
+
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
1440
|
+
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
1441
|
+
var dt = new DataTransfer();
|
|
1442
|
+
dt.items.add(file);
|
|
1443
|
+
var rect = el.getBoundingClientRect();
|
|
1444
|
+
var opts = {
|
|
1445
|
+
bubbles: true, cancelable: true,
|
|
1446
|
+
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
1447
|
+
};
|
|
1448
|
+
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
1449
|
+
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
1450
|
+
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
1451
|
+
})()
|
|
1452
|
+
`);
|
|
1453
|
+
}
|
|
1454
|
+
async setInputFiles(selector, files) {
|
|
1455
|
+
const fileArr = Array.isArray(files) ? files : [files];
|
|
1456
|
+
const fileList = fileArr.map((f) => ({
|
|
1457
|
+
name: f.name,
|
|
1458
|
+
type: f.mimeType,
|
|
1459
|
+
dataBase64: f.buffer.toString("base64")
|
|
1460
|
+
}));
|
|
1461
|
+
await this.options.evaluate(`
|
|
1462
|
+
(function() {
|
|
1463
|
+
var selector = ${JSON.stringify(selector)};
|
|
1464
|
+
var input = ${queryJS(selector)};
|
|
1465
|
+
if (!input) throw new Error('Element not found: ' + selector);
|
|
1466
|
+
|
|
1467
|
+
var fileList = ${JSON.stringify(fileList)};
|
|
1468
|
+
var dt = new DataTransfer();
|
|
1469
|
+
|
|
1470
|
+
fileList.forEach(function(f) {
|
|
1471
|
+
var binary = atob(f.dataBase64);
|
|
1472
|
+
var bytes = new Uint8Array(binary.length);
|
|
1473
|
+
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1474
|
+
var blob = new Blob([bytes], { type: f.type });
|
|
1475
|
+
var file = new File([blob], f.name, { type: f.type });
|
|
1476
|
+
dt.items.add(file);
|
|
1477
|
+
});
|
|
1478
|
+
|
|
1479
|
+
input.files = dt.files;
|
|
1480
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1481
|
+
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1482
|
+
})()
|
|
1483
|
+
`);
|
|
1484
|
+
}
|
|
1485
|
+
// ── dragAndDrop ─────────────────────────────────────────────
|
|
1486
|
+
async dragAndDrop(source, target) {
|
|
1487
|
+
const sourceRect = await this.options.evaluate(`
|
|
1488
|
+
(function() {
|
|
1489
|
+
const el = ${queryJS(source)};
|
|
1490
|
+
if (!el) throw new Error('Source not found: ${source}');
|
|
1491
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1492
|
+
const r = el.getBoundingClientRect();
|
|
1493
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1494
|
+
})()
|
|
1495
|
+
`);
|
|
1496
|
+
const targetRect = await this.options.evaluate(`
|
|
1497
|
+
(function() {
|
|
1498
|
+
const el = ${queryJS(target)};
|
|
1499
|
+
if (!el) throw new Error('Target not found: ${target}');
|
|
1500
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1501
|
+
const r = el.getBoundingClientRect();
|
|
1502
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1503
|
+
})()
|
|
1504
|
+
`);
|
|
1505
|
+
const sx = sourceRect.x + sourceRect.width / 2;
|
|
1506
|
+
const sy = sourceRect.y + sourceRect.height / 2;
|
|
1507
|
+
const tx = targetRect.x + targetRect.width / 2;
|
|
1508
|
+
const ty = targetRect.y + targetRect.height / 2;
|
|
1509
|
+
try {
|
|
1510
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1511
|
+
type: "dragStart",
|
|
1512
|
+
x: sx,
|
|
1513
|
+
y: sy,
|
|
1514
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1515
|
+
}, this.options.sessionId);
|
|
1516
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1517
|
+
type: "dragOver",
|
|
1518
|
+
x: tx,
|
|
1519
|
+
y: ty,
|
|
1520
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1521
|
+
}, this.options.sessionId);
|
|
1522
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1523
|
+
type: "drop",
|
|
1524
|
+
x: tx,
|
|
1525
|
+
y: ty,
|
|
1526
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1527
|
+
}, this.options.sessionId);
|
|
1528
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1529
|
+
type: "dragCancel",
|
|
1530
|
+
x: sx,
|
|
1531
|
+
y: sy,
|
|
1532
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1533
|
+
}, this.options.sessionId);
|
|
1534
|
+
} catch {
|
|
1535
|
+
await this.options.mouse.move(sx, sy);
|
|
1536
|
+
await this.options.mouse.down();
|
|
1537
|
+
await this.options.mouse.move(tx, ty, { steps: 10 });
|
|
1538
|
+
await this.options.mouse.up();
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
// ── setOfflineMode ──────────────────────────────────────────
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1334
1544
|
// src/cdp-driver/page-helpers.ts
|
|
1335
1545
|
function globToRegex(glob) {
|
|
1336
1546
|
let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
|
|
@@ -1479,8 +1689,777 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
|
|
|
1479
1689
|
emitter.emit("response", response);
|
|
1480
1690
|
}
|
|
1481
1691
|
}
|
|
1482
|
-
};
|
|
1483
|
-
}
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// src/cdp-driver/page-network-events.ts
|
|
1696
|
+
function setupNetworkEvents(options) {
|
|
1697
|
+
options.addSubscription(
|
|
1698
|
+
options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
|
|
1699
|
+
const p = params;
|
|
1700
|
+
options.state.inflightRequests.add(p.requestId);
|
|
1701
|
+
options.storeRequest(p.requestId, {
|
|
1702
|
+
url: p.request.url,
|
|
1703
|
+
method: p.request.method,
|
|
1704
|
+
headers: p.request.headers,
|
|
1705
|
+
postData: p.request.postData ?? null,
|
|
1706
|
+
resourceType: p.type
|
|
1707
|
+
});
|
|
1708
|
+
options.emit("request", createXBRequest(
|
|
1709
|
+
null,
|
|
1710
|
+
{
|
|
1711
|
+
requestId: p.requestId,
|
|
1712
|
+
url: p.request.url,
|
|
1713
|
+
method: p.request.method,
|
|
1714
|
+
headers: p.request.headers,
|
|
1715
|
+
postData: p.request.postData ?? null,
|
|
1716
|
+
resourceType: p.type
|
|
1717
|
+
}
|
|
1718
|
+
));
|
|
1719
|
+
options.checkNetworkIdle();
|
|
1720
|
+
})
|
|
1721
|
+
);
|
|
1722
|
+
options.addSubscription(
|
|
1723
|
+
options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
|
|
1724
|
+
const p = params;
|
|
1725
|
+
options.storeResponse(p.requestId, {
|
|
1726
|
+
status: p.response.status,
|
|
1727
|
+
url: p.response.url,
|
|
1728
|
+
headers: p.response.headers
|
|
1729
|
+
});
|
|
1730
|
+
options.emit("response", createXBResponse(
|
|
1731
|
+
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
1732
|
+
options.conn,
|
|
1733
|
+
options.sessionId
|
|
1734
|
+
));
|
|
1735
|
+
})
|
|
1736
|
+
);
|
|
1737
|
+
options.addSubscription(
|
|
1738
|
+
options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
|
|
1739
|
+
const p = params;
|
|
1740
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1741
|
+
options.emit("requestfinished", p);
|
|
1742
|
+
options.checkNetworkIdle();
|
|
1743
|
+
})
|
|
1744
|
+
);
|
|
1745
|
+
options.addSubscription(
|
|
1746
|
+
options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
|
|
1747
|
+
const p = params;
|
|
1748
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1749
|
+
options.checkNetworkIdle();
|
|
1750
|
+
})
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
// src/cdp-driver/page-lifecycle-events.ts
|
|
1755
|
+
function setupPageEvents(options) {
|
|
1756
|
+
options.addSubscription(
|
|
1757
|
+
options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
|
|
1758
|
+
const p = params;
|
|
1759
|
+
if (p.frame) {
|
|
1760
|
+
options.setUrl(p.frame.url);
|
|
1761
|
+
}
|
|
1762
|
+
options.emit("framenavigated", options.mainFrame());
|
|
1763
|
+
})
|
|
1764
|
+
);
|
|
1765
|
+
options.addSubscription(
|
|
1766
|
+
options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
|
|
1767
|
+
options.markLoadFired();
|
|
1768
|
+
})
|
|
1769
|
+
);
|
|
1770
|
+
options.addSubscription(
|
|
1771
|
+
options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
|
|
1772
|
+
options.markDomContentFired();
|
|
1773
|
+
})
|
|
1774
|
+
);
|
|
1775
|
+
options.addSubscription(
|
|
1776
|
+
options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
|
|
1777
|
+
const p = params;
|
|
1778
|
+
const dialog = {
|
|
1779
|
+
type: p.type,
|
|
1780
|
+
message: () => p.message,
|
|
1781
|
+
defaultValue: () => p.defaultValue,
|
|
1782
|
+
accept: async (text) => {
|
|
1783
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1784
|
+
accept: true,
|
|
1785
|
+
promptText: text
|
|
1786
|
+
}, options.sessionId);
|
|
1787
|
+
},
|
|
1788
|
+
dismiss: async () => {
|
|
1789
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1790
|
+
accept: false
|
|
1791
|
+
}, options.sessionId);
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
options.emit("dialog", dialog);
|
|
1795
|
+
const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
|
|
1796
|
+
setTimeout(() => {
|
|
1797
|
+
options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
|
|
1798
|
+
});
|
|
1799
|
+
}, 0);
|
|
1800
|
+
})
|
|
1801
|
+
);
|
|
1802
|
+
options.addSubscription(
|
|
1803
|
+
options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
|
|
1804
|
+
const p = params;
|
|
1805
|
+
let selector = "";
|
|
1806
|
+
try {
|
|
1807
|
+
const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1808
|
+
const attrs = result.node?.attributes || [];
|
|
1809
|
+
const idIdx = attrs.indexOf("id");
|
|
1810
|
+
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
1811
|
+
} catch {
|
|
1812
|
+
}
|
|
1813
|
+
if (!selector) {
|
|
1814
|
+
try {
|
|
1815
|
+
const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1816
|
+
const evalResult = await options.conn.send("Runtime.callFunctionOn", {
|
|
1817
|
+
objectId: result.objectId,
|
|
1818
|
+
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
1819
|
+
returnByValue: true
|
|
1820
|
+
}, options.sessionId);
|
|
1821
|
+
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
1822
|
+
} catch {
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const fileChooser = {
|
|
1826
|
+
selector,
|
|
1827
|
+
isMultiple: p.mode === "selectMultiple",
|
|
1828
|
+
setFiles: async (files) => {
|
|
1829
|
+
const fileArray = Array.isArray(files) ? files : [files];
|
|
1830
|
+
await options.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
1831
|
+
}
|
|
1832
|
+
};
|
|
1833
|
+
options.emit("filechooser", fileChooser);
|
|
1834
|
+
})
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
// src/cdp-driver/page-network-waits.ts
|
|
1839
|
+
var NetworkWaitService = class {
|
|
1840
|
+
constructor(options) {
|
|
1841
|
+
this.options = options;
|
|
1842
|
+
}
|
|
1843
|
+
options;
|
|
1844
|
+
// ── waitForResponse ─────────────────────────────────────────
|
|
1845
|
+
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
1846
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1847
|
+
const predicate = createResponsePredicate(urlOrPredicate);
|
|
1848
|
+
for (const [, data] of this.options.responses) {
|
|
1849
|
+
const response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1850
|
+
if (predicate(response)) return response;
|
|
1851
|
+
}
|
|
1852
|
+
return new Promise((resolve, reject) => {
|
|
1853
|
+
const timer = setTimeout(() => {
|
|
1854
|
+
this.options.off("response", handler);
|
|
1855
|
+
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
1856
|
+
}, timeout);
|
|
1857
|
+
const handler = (params) => {
|
|
1858
|
+
let response;
|
|
1859
|
+
const respObj = params;
|
|
1860
|
+
if (respObj.response) {
|
|
1861
|
+
const data = {
|
|
1862
|
+
requestId: respObj.requestId || "",
|
|
1863
|
+
status: respObj.response.status || 0,
|
|
1864
|
+
url: respObj.response.url || "",
|
|
1865
|
+
headers: respObj.response.headers || {}
|
|
1866
|
+
};
|
|
1867
|
+
response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1868
|
+
} else if (typeof params.status === "function") {
|
|
1869
|
+
response = params;
|
|
1870
|
+
} else {
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
if (predicate(response)) {
|
|
1874
|
+
clearTimeout(timer);
|
|
1875
|
+
this.options.off("response", handler);
|
|
1876
|
+
resolve(response);
|
|
1877
|
+
}
|
|
1878
|
+
};
|
|
1879
|
+
this.options.on("response", handler);
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
// ── waitForRequest ──────────────────────────────────────────
|
|
1883
|
+
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
1884
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1885
|
+
const predicate = createRequestPredicate(urlOrPredicate);
|
|
1886
|
+
for (const [, data] of this.options.requests) {
|
|
1887
|
+
const request = createXBRequest(this.pageLike(), data);
|
|
1888
|
+
if (predicate(request)) return request;
|
|
1889
|
+
}
|
|
1890
|
+
return new Promise((resolve, reject) => {
|
|
1891
|
+
const timer = setTimeout(() => {
|
|
1892
|
+
this.options.off("request", handler);
|
|
1893
|
+
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
1894
|
+
}, timeout);
|
|
1895
|
+
const handler = (params) => {
|
|
1896
|
+
let request;
|
|
1897
|
+
const reqObj = params;
|
|
1898
|
+
if (reqObj.request) {
|
|
1899
|
+
request = createXBRequest(this.pageLike(), {
|
|
1900
|
+
requestId: reqObj.requestId || "",
|
|
1901
|
+
url: reqObj.request.url || "",
|
|
1902
|
+
method: reqObj.request.method || "",
|
|
1903
|
+
headers: reqObj.request.headers || {},
|
|
1904
|
+
postData: reqObj.request.postData ?? null,
|
|
1905
|
+
resourceType: reqObj.type || ""
|
|
1906
|
+
});
|
|
1907
|
+
} else if (typeof params.url === "function") {
|
|
1908
|
+
request = params;
|
|
1909
|
+
} else {
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
if (predicate(request)) {
|
|
1913
|
+
clearTimeout(timer);
|
|
1914
|
+
this.options.off("request", handler);
|
|
1915
|
+
resolve(request);
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
this.options.on("request", handler);
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
// ── waitForURL ──────────────────────────────────────────────
|
|
1922
|
+
async waitForURL(url, opts = {}) {
|
|
1923
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1924
|
+
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
1925
|
+
if (checkFn(this.options.currentUrl())) return;
|
|
1926
|
+
return new Promise((resolve, reject) => {
|
|
1927
|
+
const timer = setTimeout(() => {
|
|
1928
|
+
this.options.off("framenavigated", handler);
|
|
1929
|
+
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
1930
|
+
}, timeout);
|
|
1931
|
+
const handler = () => {
|
|
1932
|
+
if (checkFn(this.options.currentUrl())) {
|
|
1933
|
+
clearTimeout(timer);
|
|
1934
|
+
this.options.off("framenavigated", handler);
|
|
1935
|
+
resolve();
|
|
1936
|
+
}
|
|
1937
|
+
};
|
|
1938
|
+
this.options.on("framenavigated", handler);
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
pageLike() {
|
|
1942
|
+
return {
|
|
1943
|
+
_networkResponses: this.options.responses,
|
|
1944
|
+
_connection: this.options.conn,
|
|
1945
|
+
sessionId: this.options.sessionId
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
};
|
|
1949
|
+
|
|
1950
|
+
// src/cdp-driver/page-routes.ts
|
|
1951
|
+
var NetworkRouteService = class {
|
|
1952
|
+
constructor(options) {
|
|
1953
|
+
this.options = options;
|
|
1954
|
+
}
|
|
1955
|
+
options;
|
|
1956
|
+
routeHandlers = [];
|
|
1957
|
+
interceptionEnabled = false;
|
|
1958
|
+
get isInterceptionEnabled() {
|
|
1959
|
+
return this.interceptionEnabled;
|
|
1960
|
+
}
|
|
1961
|
+
subscriptions = [];
|
|
1962
|
+
async route(url, handler) {
|
|
1963
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
1964
|
+
this.routeHandlers.push({ pattern: String(url), regex, handler });
|
|
1965
|
+
if (!this.interceptionEnabled) {
|
|
1966
|
+
this.interceptionEnabled = true;
|
|
1967
|
+
await this.options.conn.send("Fetch.enable", {
|
|
1968
|
+
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
1969
|
+
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
1970
|
+
// 会顶掉 _init 的 auth 配置)
|
|
1971
|
+
handleAuthRequests: true
|
|
1972
|
+
}, this.options.sessionId);
|
|
1973
|
+
this.subscriptions.push(
|
|
1974
|
+
this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
|
|
1975
|
+
this._handleRequestPaused(params);
|
|
1976
|
+
})
|
|
1977
|
+
);
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
async unroute(url, handler) {
|
|
1981
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
1982
|
+
this.routeHandlers = this.routeHandlers.filter(
|
|
1983
|
+
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
1984
|
+
);
|
|
1985
|
+
if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
|
|
1986
|
+
this.interceptionEnabled = false;
|
|
1987
|
+
await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async _handleRequestPaused(params) {
|
|
1992
|
+
const requestUrl = params.request.url;
|
|
1993
|
+
for (const { regex, handler } of this.routeHandlers) {
|
|
1994
|
+
if (regex.test(requestUrl)) {
|
|
1995
|
+
this.options.emit("request", createXBRequest(
|
|
1996
|
+
null,
|
|
1997
|
+
{
|
|
1998
|
+
requestId: params.requestId,
|
|
1999
|
+
url: params.request.url,
|
|
2000
|
+
method: params.request.method,
|
|
2001
|
+
headers: params.request.headers,
|
|
2002
|
+
postData: params.request.postData ?? null,
|
|
2003
|
+
resourceType: params.resourceType
|
|
2004
|
+
}
|
|
2005
|
+
));
|
|
2006
|
+
const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
|
|
2007
|
+
try {
|
|
2008
|
+
await handler(route);
|
|
2009
|
+
} catch {
|
|
2010
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2011
|
+
requestId: params.requestId
|
|
2012
|
+
}, this.options.sessionId).catch(() => {
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
return;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2019
|
+
requestId: params.requestId
|
|
2020
|
+
}, this.options.sessionId).catch(() => {
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
|
|
2025
|
+
// src/cdp-driver/page-navigation.ts
|
|
2026
|
+
var NavigationService = class {
|
|
2027
|
+
constructor(options) {
|
|
2028
|
+
this.options = options;
|
|
2029
|
+
}
|
|
2030
|
+
options;
|
|
2031
|
+
async goto(url, opts = {}) {
|
|
2032
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2033
|
+
const waitUntil = opts.waitUntil ?? "load";
|
|
2034
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2035
|
+
this.options.state.loadFired = false;
|
|
2036
|
+
this.options.state.domContentFired = false;
|
|
2037
|
+
this.options.state.networkIdle = false;
|
|
2038
|
+
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
2039
|
+
try {
|
|
2040
|
+
await this.options.conn.send(
|
|
2041
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2042
|
+
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
|
|
2043
|
+
this.options.sessionId
|
|
2044
|
+
);
|
|
2045
|
+
} catch {
|
|
2046
|
+
}
|
|
2047
|
+
try {
|
|
2048
|
+
const rawUa = await this.options.conn.send(
|
|
2049
|
+
"Runtime.evaluate",
|
|
2050
|
+
{ expression: "navigator.userAgent", returnByValue: true },
|
|
2051
|
+
this.options.sessionId
|
|
2052
|
+
);
|
|
2053
|
+
const ua = rawUa?.value || "";
|
|
2054
|
+
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
2055
|
+
if (cleaned !== ua) {
|
|
2056
|
+
await this.options.conn.send(
|
|
2057
|
+
"Network.setUserAgentOverride",
|
|
2058
|
+
{ userAgent: cleaned },
|
|
2059
|
+
this.options.sessionId
|
|
2060
|
+
);
|
|
2061
|
+
}
|
|
2062
|
+
} catch {
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
const result = await this.options.conn.send(
|
|
2066
|
+
"Page.navigate",
|
|
2067
|
+
{ url, referrer: opts.referer },
|
|
2068
|
+
this.options.sessionId
|
|
2069
|
+
);
|
|
2070
|
+
if (result.errorText) {
|
|
2071
|
+
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
2072
|
+
}
|
|
2073
|
+
if (waitUntil === "commit") {
|
|
2074
|
+
this.options.setUrl(url);
|
|
2075
|
+
return {
|
|
2076
|
+
status: () => 0,
|
|
2077
|
+
ok: () => false,
|
|
2078
|
+
url: () => url,
|
|
2079
|
+
headers: () => ({})
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
await this.options.waitForLoadState(waitUntil, timeout);
|
|
2083
|
+
this.options.setUrl(url);
|
|
2084
|
+
const statusCode = 200;
|
|
2085
|
+
const finalUrl = url;
|
|
2086
|
+
const headers = {};
|
|
2087
|
+
return {
|
|
2088
|
+
status: () => statusCode,
|
|
2089
|
+
ok: () => statusCode >= 200 && statusCode < 300,
|
|
2090
|
+
url: () => finalUrl,
|
|
2091
|
+
headers: () => headers
|
|
2092
|
+
};
|
|
2093
|
+
}
|
|
2094
|
+
async goBack(opts = {}) {
|
|
2095
|
+
try {
|
|
2096
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2097
|
+
if (navHistory.currentIndex > 0) {
|
|
2098
|
+
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
2099
|
+
if (prevUrl && prevUrl !== "about:blank") {
|
|
2100
|
+
await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
|
|
2101
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2102
|
+
});
|
|
2103
|
+
this.options.setUrl(prevUrl);
|
|
2104
|
+
return;
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
} catch {
|
|
2108
|
+
}
|
|
2109
|
+
await this.options.evaluate("() => history.back()");
|
|
2110
|
+
await this.options.waitForTimeout(3e3);
|
|
2111
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2112
|
+
}
|
|
2113
|
+
async goForward(opts = {}) {
|
|
2114
|
+
try {
|
|
2115
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2116
|
+
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
2117
|
+
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
2118
|
+
if (nextUrl && nextUrl !== "about:blank") {
|
|
2119
|
+
await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
|
|
2120
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2121
|
+
});
|
|
2122
|
+
this.options.setUrl(nextUrl);
|
|
2123
|
+
return;
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
} catch {
|
|
2127
|
+
}
|
|
2128
|
+
await this.options.evaluate("() => history.forward()");
|
|
2129
|
+
await this.options.waitForTimeout(3e3);
|
|
2130
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2131
|
+
}
|
|
2132
|
+
async reload(opts = {}) {
|
|
2133
|
+
this.options.state.loadFired = false;
|
|
2134
|
+
this.options.state.domContentFired = false;
|
|
2135
|
+
this.options.state.networkIdle = false;
|
|
2136
|
+
await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
|
|
2137
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2138
|
+
}
|
|
2139
|
+
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
2140
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2141
|
+
const checkState = () => {
|
|
2142
|
+
switch (state) {
|
|
2143
|
+
case "domcontentloaded":
|
|
2144
|
+
return this.options.state.domContentFired;
|
|
2145
|
+
case "load":
|
|
2146
|
+
return this.options.state.loadFired;
|
|
2147
|
+
case "networkidle":
|
|
2148
|
+
return this.options.state.networkIdle;
|
|
2149
|
+
case "commit":
|
|
2150
|
+
return this.options.state.domContentFired;
|
|
2151
|
+
default:
|
|
2152
|
+
return true;
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
if (checkState()) return;
|
|
2156
|
+
return new Promise((resolve, reject) => {
|
|
2157
|
+
const timer = setTimeout(() => {
|
|
2158
|
+
reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
|
|
2159
|
+
}, timeout);
|
|
2160
|
+
const check = () => {
|
|
2161
|
+
if (checkState()) {
|
|
2162
|
+
clearTimeout(timer);
|
|
2163
|
+
resolve();
|
|
2164
|
+
} else {
|
|
2165
|
+
setTimeout(check, 50);
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
check();
|
|
2169
|
+
});
|
|
2170
|
+
}
|
|
2171
|
+
async waitForTimeout(ms) {
|
|
2172
|
+
await new Promise((resolve) => {
|
|
2173
|
+
const timer = setTimeout(resolve, ms);
|
|
2174
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
};
|
|
2178
|
+
|
|
2179
|
+
// src/cdp-driver/page-dom.ts
|
|
2180
|
+
var DomQueryService = class {
|
|
2181
|
+
constructor(options) {
|
|
2182
|
+
this.options = options;
|
|
2183
|
+
}
|
|
2184
|
+
options;
|
|
2185
|
+
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2186
|
+
async querySelector(selector) {
|
|
2187
|
+
if (selector.startsWith("xpath=")) {
|
|
2188
|
+
const found = await this.options.evaluate(`
|
|
2189
|
+
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2190
|
+
`).catch(() => false);
|
|
2191
|
+
if (!found) return 0;
|
|
2192
|
+
try {
|
|
2193
|
+
const search = await this.options.conn.send(
|
|
2194
|
+
"DOM.performSearch",
|
|
2195
|
+
{ query: selector.slice(6) },
|
|
2196
|
+
this.options.sessionId
|
|
2197
|
+
);
|
|
2198
|
+
if (search.nodeId) return search.nodeId;
|
|
2199
|
+
} catch {
|
|
2200
|
+
}
|
|
2201
|
+
return 1;
|
|
2202
|
+
}
|
|
2203
|
+
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2204
|
+
const doc = await withTimeout(
|
|
2205
|
+
this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
|
|
2206
|
+
8e3
|
|
2207
|
+
);
|
|
2208
|
+
if (!doc) return 0;
|
|
2209
|
+
const result = await withTimeout(
|
|
2210
|
+
this.options.conn.send(
|
|
2211
|
+
"DOM.querySelector",
|
|
2212
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2213
|
+
this.options.sessionId
|
|
2214
|
+
),
|
|
2215
|
+
8e3
|
|
2216
|
+
);
|
|
2217
|
+
if (!result) return 0;
|
|
2218
|
+
return result.nodeId;
|
|
2219
|
+
}
|
|
2220
|
+
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2221
|
+
async querySelectorAll(selector) {
|
|
2222
|
+
const doc = await this.options.conn.send(
|
|
2223
|
+
"DOM.getDocument",
|
|
2224
|
+
{ depth: 0 },
|
|
2225
|
+
this.options.sessionId
|
|
2226
|
+
);
|
|
2227
|
+
const result = await this.options.conn.send(
|
|
2228
|
+
"DOM.querySelectorAll",
|
|
2229
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2230
|
+
this.options.sessionId
|
|
2231
|
+
);
|
|
2232
|
+
return result.nodeIds ?? [];
|
|
2233
|
+
}
|
|
2234
|
+
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2235
|
+
async resolveNode(nodeId) {
|
|
2236
|
+
const result = await this.options.conn.send(
|
|
2237
|
+
"DOM.resolveNode",
|
|
2238
|
+
{ nodeId },
|
|
2239
|
+
this.options.sessionId
|
|
2240
|
+
);
|
|
2241
|
+
return result.object.objectId;
|
|
2242
|
+
}
|
|
2243
|
+
/** Get the box model for a nodeId */
|
|
2244
|
+
async getBoxModel(nodeId) {
|
|
2245
|
+
try {
|
|
2246
|
+
const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
|
|
2247
|
+
const c = result.model?.content;
|
|
2248
|
+
if (!c || c.length < 8) return null;
|
|
2249
|
+
const x1 = c[0];
|
|
2250
|
+
const y1 = c[1];
|
|
2251
|
+
const x2 = c[4];
|
|
2252
|
+
const y2 = c[5];
|
|
2253
|
+
return {
|
|
2254
|
+
x: Math.min(x1, x2),
|
|
2255
|
+
y: Math.min(y1, y2),
|
|
2256
|
+
width: Math.abs(x2 - x1),
|
|
2257
|
+
height: Math.abs(y2 - y1)
|
|
2258
|
+
};
|
|
2259
|
+
} catch {
|
|
2260
|
+
return null;
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
/** Call a function on a RemoteObject */
|
|
2264
|
+
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
2265
|
+
const result = await this.options.conn.send("Runtime.callFunctionOn", {
|
|
2266
|
+
objectId,
|
|
2267
|
+
functionDeclaration,
|
|
2268
|
+
arguments: args.map((a) => ({ value: a })),
|
|
2269
|
+
returnByValue: true
|
|
2270
|
+
}, this.options.sessionId);
|
|
2271
|
+
if (result.exceptionDetails) {
|
|
2272
|
+
throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
|
|
2273
|
+
}
|
|
2274
|
+
return result.result?.value;
|
|
2275
|
+
}
|
|
2276
|
+
/** Send a CDP command scoped to this page's session */
|
|
2277
|
+
async _cdpSend(method, params) {
|
|
2278
|
+
return this.options.conn.send(method, params, this.options.sessionId);
|
|
2279
|
+
}
|
|
2280
|
+
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2281
|
+
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2282
|
+
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2283
|
+
};
|
|
2284
|
+
|
|
2285
|
+
// src/cdp-driver/page-runtime.ts
|
|
2286
|
+
var RuntimeEvaluationService = class {
|
|
2287
|
+
constructor(options) {
|
|
2288
|
+
this.options = options;
|
|
2289
|
+
}
|
|
2290
|
+
options;
|
|
2291
|
+
async title() {
|
|
2292
|
+
let title = "";
|
|
2293
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
2294
|
+
try {
|
|
2295
|
+
title = await this.evaluate("document.title");
|
|
2296
|
+
if (title) return title;
|
|
2297
|
+
} catch {
|
|
2298
|
+
}
|
|
2299
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2300
|
+
}
|
|
2301
|
+
return title;
|
|
2302
|
+
}
|
|
2303
|
+
async content() {
|
|
2304
|
+
return this.evaluate("document.documentElement.outerHTML");
|
|
2305
|
+
}
|
|
2306
|
+
// ── Evaluation ──────────────────────────────────────────────
|
|
2307
|
+
async evaluate(fn, ...args) {
|
|
2308
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2309
|
+
this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
|
|
2310
|
+
});
|
|
2311
|
+
let expression;
|
|
2312
|
+
if (typeof fn === "string") {
|
|
2313
|
+
expression = fn;
|
|
2314
|
+
} else {
|
|
2315
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2316
|
+
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2317
|
+
}
|
|
2318
|
+
const result = await this.options.conn.send("Runtime.evaluate", {
|
|
2319
|
+
expression,
|
|
2320
|
+
returnByValue: true,
|
|
2321
|
+
awaitPromise: true
|
|
2322
|
+
}, this.options.sessionId);
|
|
2323
|
+
if (result.exceptionDetails) {
|
|
2324
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2325
|
+
throw new Error(`${detail}`);
|
|
2326
|
+
}
|
|
2327
|
+
return result.result?.value;
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2331
|
+
*
|
|
2332
|
+
* 双路径:
|
|
2333
|
+
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2334
|
+
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2335
|
+
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2336
|
+
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2337
|
+
*
|
|
2338
|
+
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2339
|
+
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2340
|
+
*/
|
|
2341
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2342
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2343
|
+
const evalIn = async (sessionId, contextId) => {
|
|
2344
|
+
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2345
|
+
if (contextId !== void 0) params.contextId = contextId;
|
|
2346
|
+
const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
|
|
2347
|
+
if (result.exceptionDetails) {
|
|
2348
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2349
|
+
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2350
|
+
}
|
|
2351
|
+
return result.result?.value;
|
|
2352
|
+
};
|
|
2353
|
+
try {
|
|
2354
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2355
|
+
const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2356
|
+
if (hit2) {
|
|
2357
|
+
const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
|
|
2358
|
+
return evalIn(att.sessionId);
|
|
2359
|
+
}
|
|
2360
|
+
} catch {
|
|
2361
|
+
}
|
|
2362
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2363
|
+
const all = [];
|
|
2364
|
+
const walk = (node) => {
|
|
2365
|
+
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2366
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2367
|
+
};
|
|
2368
|
+
walk(tree.frameTree);
|
|
2369
|
+
const mainId = tree.frameTree?.frame?.id;
|
|
2370
|
+
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2371
|
+
if (target) {
|
|
2372
|
+
const contexts = [];
|
|
2373
|
+
const onCtx = (raw) => {
|
|
2374
|
+
const c = raw?.context;
|
|
2375
|
+
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2376
|
+
};
|
|
2377
|
+
this.options.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2378
|
+
try {
|
|
2379
|
+
await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
|
|
2380
|
+
});
|
|
2381
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
2382
|
+
} finally {
|
|
2383
|
+
this.options.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2384
|
+
}
|
|
2385
|
+
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2386
|
+
if (ctx) return evalIn(this.options.sessionId, ctx.id);
|
|
2387
|
+
}
|
|
2388
|
+
const attached = [];
|
|
2389
|
+
const onAttach = (raw) => {
|
|
2390
|
+
const ev = raw;
|
|
2391
|
+
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2392
|
+
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2393
|
+
}
|
|
2394
|
+
};
|
|
2395
|
+
this.options.conn.on("Target.attachedToTarget", onAttach);
|
|
2396
|
+
try {
|
|
2397
|
+
await this.options.conn.send("Target.setAutoAttach", {
|
|
2398
|
+
autoAttach: true,
|
|
2399
|
+
waitForDebuggerOnStart: false,
|
|
2400
|
+
flatten: true
|
|
2401
|
+
}, this.options.sessionId);
|
|
2402
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
2403
|
+
} finally {
|
|
2404
|
+
this.options.conn.off("Target.attachedToTarget", onAttach);
|
|
2405
|
+
this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2409
|
+
if (!hit) {
|
|
2410
|
+
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`);
|
|
2411
|
+
}
|
|
2412
|
+
return evalIn(hit.sessionId);
|
|
2413
|
+
}
|
|
2414
|
+
/** evaluateHandle — evaluates fn and returns a handle for element bounding box */
|
|
2415
|
+
async evaluateHandle(fn, ...args) {
|
|
2416
|
+
let expression;
|
|
2417
|
+
if (typeof fn === "string") {
|
|
2418
|
+
expression = fn;
|
|
2419
|
+
} else {
|
|
2420
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2421
|
+
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;})()`;
|
|
2422
|
+
}
|
|
2423
|
+
const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
|
|
2424
|
+
let box = null;
|
|
2425
|
+
try {
|
|
2426
|
+
box = JSON.parse(result.result?.value);
|
|
2427
|
+
} catch {
|
|
2428
|
+
}
|
|
2429
|
+
return {
|
|
2430
|
+
asElement: () => box ? { boundingBox: async () => box } : null
|
|
2431
|
+
};
|
|
2432
|
+
}
|
|
2433
|
+
async $eval(selector, fn, ...args) {
|
|
2434
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2435
|
+
const selJSON = JSON.stringify(selector);
|
|
2436
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2437
|
+
return this.evaluate(
|
|
2438
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2439
|
+
const el = xpathExpr
|
|
2440
|
+
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2441
|
+
: document.querySelector(sel);
|
|
2442
|
+
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2443
|
+
const fn = new Function('return ' + fnStr)();
|
|
2444
|
+
return fn(el, ...evalArgs);
|
|
2445
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2446
|
+
);
|
|
2447
|
+
}
|
|
2448
|
+
async $$eval(selector, fn, ...args) {
|
|
2449
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2450
|
+
const selJSON = JSON.stringify(selector);
|
|
2451
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2452
|
+
return this.evaluate(
|
|
2453
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2454
|
+
const els = xpathExpr
|
|
2455
|
+
? (() => { 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; })()
|
|
2456
|
+
: Array.from(document.querySelectorAll(sel));
|
|
2457
|
+
const fn = new Function('return ' + fnStr)();
|
|
2458
|
+
return fn(els, ...evalArgs);
|
|
2459
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2460
|
+
);
|
|
2461
|
+
}
|
|
2462
|
+
};
|
|
1484
2463
|
|
|
1485
2464
|
// src/cdp-driver/page.ts
|
|
1486
2465
|
var XBPageImpl = class _XBPageImpl {
|
|
@@ -1493,7 +2472,6 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1493
2472
|
_browserImpl;
|
|
1494
2473
|
_closed = false;
|
|
1495
2474
|
_url = "about:blank";
|
|
1496
|
-
_title = "";
|
|
1497
2475
|
_viewportSize = null;
|
|
1498
2476
|
_loadState = {
|
|
1499
2477
|
loadFired: true,
|
|
@@ -1502,6 +2480,13 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1502
2480
|
};
|
|
1503
2481
|
mouse;
|
|
1504
2482
|
keyboard;
|
|
2483
|
+
mediaService;
|
|
2484
|
+
fileInputService;
|
|
2485
|
+
networkWaitService;
|
|
2486
|
+
networkRouteService;
|
|
2487
|
+
navigationService;
|
|
2488
|
+
domQueryService;
|
|
2489
|
+
runtimeEvaluationService;
|
|
1505
2490
|
// Network tracking for waitForLoadState('networkidle')
|
|
1506
2491
|
inflightRequests = /* @__PURE__ */ new Set();
|
|
1507
2492
|
networkIdleResolve = null;
|
|
@@ -1515,6 +2500,60 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1515
2500
|
this._browserImpl = browser;
|
|
1516
2501
|
this.mouse = new XBMouseImpl(conn, sessionId);
|
|
1517
2502
|
this.keyboard = new XBKeyboardImpl(conn, sessionId);
|
|
2503
|
+
this.mediaService = new MediaService({
|
|
2504
|
+
conn,
|
|
2505
|
+
sessionId,
|
|
2506
|
+
viewportSize: this._viewportSize,
|
|
2507
|
+
evaluate: (script) => this.evaluate(script),
|
|
2508
|
+
onViewportSize: (size) => {
|
|
2509
|
+
this._viewportSize = size;
|
|
2510
|
+
}
|
|
2511
|
+
});
|
|
2512
|
+
this.fileInputService = new FileInputService({
|
|
2513
|
+
conn,
|
|
2514
|
+
sessionId,
|
|
2515
|
+
evaluate: (script) => this.evaluate(script),
|
|
2516
|
+
mouse: this.mouse
|
|
2517
|
+
});
|
|
2518
|
+
this.networkWaitService = new NetworkWaitService({
|
|
2519
|
+
conn,
|
|
2520
|
+
sessionId,
|
|
2521
|
+
responses: this._networkResponses,
|
|
2522
|
+
requests: this._networkRequests,
|
|
2523
|
+
on: (event, handler) => this._emitter.on(event, handler),
|
|
2524
|
+
off: (event, handler) => this._emitter.removeListener(event, handler),
|
|
2525
|
+
currentUrl: () => this.url()
|
|
2526
|
+
});
|
|
2527
|
+
this.networkRouteService = new NetworkRouteService({
|
|
2528
|
+
conn,
|
|
2529
|
+
sessionId,
|
|
2530
|
+
emit: (event, ...args) => this._emit(event, ...args)
|
|
2531
|
+
});
|
|
2532
|
+
this.navigationService = new NavigationService({
|
|
2533
|
+
conn,
|
|
2534
|
+
sessionId,
|
|
2535
|
+
state: this._loadState,
|
|
2536
|
+
stealthConfig: this._contextImpl.stealthConfig,
|
|
2537
|
+
isClosed: () => this._closed,
|
|
2538
|
+
setUrl: (url) => {
|
|
2539
|
+
this._url = url;
|
|
2540
|
+
},
|
|
2541
|
+
currentUrl: () => this.url(),
|
|
2542
|
+
waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
|
|
2543
|
+
waitForTimeout: (ms) => this.waitForTimeout(ms),
|
|
2544
|
+
evaluate: (script) => this.evaluate(script)
|
|
2545
|
+
});
|
|
2546
|
+
this.runtimeEvaluationService = new RuntimeEvaluationService({
|
|
2547
|
+
conn,
|
|
2548
|
+
sessionId,
|
|
2549
|
+
isClosed: () => this._closed,
|
|
2550
|
+
url: () => this.url()
|
|
2551
|
+
});
|
|
2552
|
+
this.domQueryService = new DomQueryService({
|
|
2553
|
+
conn,
|
|
2554
|
+
sessionId,
|
|
2555
|
+
evaluate: (script) => this.evaluate(script)
|
|
2556
|
+
});
|
|
1518
2557
|
}
|
|
1519
2558
|
_emit(event, ...args) {
|
|
1520
2559
|
this._emitter.emit(event, ...args);
|
|
@@ -1540,7 +2579,7 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1540
2579
|
});
|
|
1541
2580
|
this._subscriptions.push(
|
|
1542
2581
|
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
1543
|
-
if (this.
|
|
2582
|
+
if (this.networkRouteService.isInterceptionEnabled) return;
|
|
1544
2583
|
const p = params;
|
|
1545
2584
|
this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
|
|
1546
2585
|
});
|
|
@@ -1720,7 +2759,6 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1720
2759
|
{ targetId: this._targetId }
|
|
1721
2760
|
);
|
|
1722
2761
|
this._url = info.url;
|
|
1723
|
-
this._title = info.title;
|
|
1724
2762
|
if (info.url && info.url !== "about:blank" && info.url !== "") {
|
|
1725
2763
|
this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
|
|
1726
2764
|
}
|
|
@@ -1732,108 +2770,16 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1732
2770
|
}
|
|
1733
2771
|
// ── Navigation ──────────────────────────────────────────────
|
|
1734
2772
|
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
|
-
};
|
|
2773
|
+
return this.navigationService.goto(url, opts);
|
|
1794
2774
|
}
|
|
1795
2775
|
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);
|
|
2776
|
+
return this.navigationService.goBack(opts);
|
|
1813
2777
|
}
|
|
1814
2778
|
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);
|
|
2779
|
+
return this.navigationService.goForward(opts);
|
|
1832
2780
|
}
|
|
1833
2781
|
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);
|
|
2782
|
+
return this.navigationService.reload(opts);
|
|
1837
2783
|
}
|
|
1838
2784
|
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
1839
2785
|
if (this._closed) throw new Error("Page is closed");
|
|
@@ -1904,206 +2850,48 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1904
2850
|
const timeout = opts.timeout ?? 3e4;
|
|
1905
2851
|
const polling = opts.polling ?? 100;
|
|
1906
2852
|
const deadline = Date.now() + timeout;
|
|
1907
|
-
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
1908
|
-
let lastError = null;
|
|
1909
|
-
while (Date.now() < deadline) {
|
|
1910
|
-
try {
|
|
1911
|
-
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 {
|
|
2853
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2854
|
+
let lastError = null;
|
|
2855
|
+
while (Date.now() < deadline) {
|
|
2856
|
+
try {
|
|
2857
|
+
const result = await this.evaluate(
|
|
2858
|
+
`(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(", ") : ""})`
|
|
2859
|
+
);
|
|
2860
|
+
if (result) return result;
|
|
2861
|
+
} catch (err) {
|
|
2862
|
+
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
2863
|
+
}
|
|
2864
|
+
const pollMs = typeof polling === "number" ? polling : 16;
|
|
2865
|
+
await this.waitForTimeout(pollMs);
|
|
2072
2866
|
}
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
};
|
|
2867
|
+
const detail = lastError ? `
|
|
2868
|
+
Last error: ${lastError.message}` : "";
|
|
2869
|
+
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
2870
|
+
}
|
|
2871
|
+
url() {
|
|
2872
|
+
return this._url;
|
|
2873
|
+
}
|
|
2874
|
+
async title() {
|
|
2875
|
+
return this.runtimeEvaluationService.title();
|
|
2876
|
+
}
|
|
2877
|
+
async content() {
|
|
2878
|
+
return this.runtimeEvaluationService.content();
|
|
2879
|
+
}
|
|
2880
|
+
async evaluate(fn, ...args) {
|
|
2881
|
+
return this.runtimeEvaluationService.evaluate(fn, ...args);
|
|
2882
|
+
}
|
|
2883
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2884
|
+
return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
|
|
2885
|
+
}
|
|
2886
|
+
async evaluateHandle(script, ...args) {
|
|
2887
|
+
return this.runtimeEvaluationService.evaluateHandle(script, ...args);
|
|
2076
2888
|
}
|
|
2077
2889
|
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
|
-
);
|
|
2890
|
+
return this.runtimeEvaluationService.$eval(selector, fn, ...args);
|
|
2091
2891
|
}
|
|
2092
2892
|
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
|
-
);
|
|
2893
|
+
return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
|
|
2105
2894
|
}
|
|
2106
|
-
// ── Locator ─────────────────────────────────────────────────
|
|
2107
2895
|
locator(selector) {
|
|
2108
2896
|
return new XBLocatorImpl(this, selector);
|
|
2109
2897
|
}
|
|
@@ -2224,88 +3012,20 @@ Last error: ${lastError.message}` : "";
|
|
|
2224
3012
|
}
|
|
2225
3013
|
// ── Screen ──────────────────────────────────────────────────
|
|
2226
3014
|
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");
|
|
3015
|
+
return this.mediaService.screenshot(opts);
|
|
2255
3016
|
}
|
|
2256
3017
|
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");
|
|
3018
|
+
return this.mediaService.pdf(opts);
|
|
2271
3019
|
}
|
|
2272
3020
|
viewportSize() {
|
|
2273
|
-
return this._viewportSize
|
|
3021
|
+
return this._viewportSize;
|
|
2274
3022
|
}
|
|
2275
3023
|
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;
|
|
3024
|
+
return this.mediaService.setViewportSize(size);
|
|
2287
3025
|
}
|
|
2288
|
-
/**
|
|
2289
|
-
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
2290
|
-
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
2291
|
-
*/
|
|
2292
3026
|
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;
|
|
3027
|
+
return this.mediaService.setDeviceScaleFactor(dsf);
|
|
2307
3028
|
}
|
|
2308
|
-
// ── Scripts ─────────────────────────────────────────────────
|
|
2309
3029
|
async addInitScript(script) {
|
|
2310
3030
|
await this.conn.send(
|
|
2311
3031
|
"Page.addScriptToEvaluateOnNewDocument",
|
|
@@ -2433,83 +3153,17 @@ Last error: ${lastError.message}` : "";
|
|
|
2433
3153
|
}
|
|
2434
3154
|
}
|
|
2435
3155
|
// ── CDP helpers exposed for locator/element ─────────────────
|
|
2436
|
-
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2437
3156
|
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;
|
|
3157
|
+
return this.domQueryService.querySelector(selector);
|
|
2470
3158
|
}
|
|
2471
|
-
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2472
3159
|
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 ?? [];
|
|
3160
|
+
return this.domQueryService.querySelectorAll(selector);
|
|
2484
3161
|
}
|
|
2485
|
-
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2486
3162
|
async resolveNode(nodeId) {
|
|
2487
|
-
|
|
2488
|
-
"DOM.resolveNode",
|
|
2489
|
-
{ nodeId },
|
|
2490
|
-
this.sessionId
|
|
2491
|
-
);
|
|
2492
|
-
return result.object.objectId;
|
|
3163
|
+
return this.domQueryService.resolveNode(nodeId);
|
|
2493
3164
|
}
|
|
2494
|
-
/** Get the box model for a nodeId */
|
|
2495
3165
|
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
|
-
}
|
|
3166
|
+
return this.domQueryService.getBoxModel(nodeId);
|
|
2513
3167
|
}
|
|
2514
3168
|
/** Call a function on a RemoteObject */
|
|
2515
3169
|
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
@@ -2528,9 +3182,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2528
3182
|
async _cdpSend(method, params) {
|
|
2529
3183
|
return this.conn.send(method, params, this.sessionId);
|
|
2530
3184
|
}
|
|
2531
|
-
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2532
|
-
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2533
|
-
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2534
3185
|
setBeforeUnloadBehavior(mode) {
|
|
2535
3186
|
this._beforeUnloadAccept = mode === "accept";
|
|
2536
3187
|
}
|
|
@@ -2551,146 +3202,40 @@ Last error: ${lastError.message}` : "";
|
|
|
2551
3202
|
_subscribe(event, handler) {
|
|
2552
3203
|
return this.conn.subscribe(event, this.sessionId, handler);
|
|
2553
3204
|
}
|
|
2554
|
-
// ── Private: Event Setup ────────────────────────────────────
|
|
2555
|
-
setupPageEvents() {
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
this.
|
|
2563
|
-
}
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
this._loadState.loadFired = true;
|
|
2568
|
-
}
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
);
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
dismiss: async () => {
|
|
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
|
-
);
|
|
2693
|
-
}
|
|
3205
|
+
// ── Private: Event Setup ────────────────────────────────────
|
|
3206
|
+
setupPageEvents() {
|
|
3207
|
+
setupPageEvents({
|
|
3208
|
+
conn: this.conn,
|
|
3209
|
+
sessionId: this.sessionId,
|
|
3210
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
|
|
3211
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3212
|
+
setUrl: (url) => {
|
|
3213
|
+
this._url = url;
|
|
3214
|
+
},
|
|
3215
|
+
currentUrl: () => this.url(),
|
|
3216
|
+
mainFrame: () => this.mainFrame(),
|
|
3217
|
+
markLoadFired: () => {
|
|
3218
|
+
this._loadState.loadFired = true;
|
|
3219
|
+
},
|
|
3220
|
+
markDomContentFired: () => {
|
|
3221
|
+
this._loadState.domContentFired = true;
|
|
3222
|
+
},
|
|
3223
|
+
getBeforeUnloadAccept: () => this._beforeUnloadAccept,
|
|
3224
|
+
setInputFiles: (selector, files) => this.setInputFiles(selector, files)
|
|
3225
|
+
});
|
|
3226
|
+
}
|
|
3227
|
+
setupNetworkEvents() {
|
|
3228
|
+
setupNetworkEvents({
|
|
3229
|
+
conn: this.conn,
|
|
3230
|
+
sessionId: this.sessionId,
|
|
3231
|
+
state: { inflightRequests: this.inflightRequests },
|
|
3232
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3233
|
+
storeRequest: (id, data) => this._storeNetworkRequest(id, data),
|
|
3234
|
+
storeResponse: (id, data) => this._storeNetworkResponse(id, data),
|
|
3235
|
+
checkNetworkIdle: () => this.checkNetworkIdle(),
|
|
3236
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
|
|
3237
|
+
});
|
|
3238
|
+
}
|
|
2694
3239
|
setupConsoleEvents() {
|
|
2695
3240
|
this._subscriptions.push(
|
|
2696
3241
|
this.conn.subscribe("Runtime.consoleAPICalled", this.sessionId, (params) => {
|
|
@@ -2735,8 +3280,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2735
3280
|
// ── Network Data Store (for waitForResponse/waitForRequest) ──
|
|
2736
3281
|
_networkResponses = /* @__PURE__ */ new Map();
|
|
2737
3282
|
_networkRequests = /* @__PURE__ */ new Map();
|
|
2738
|
-
_routeHandlers = [];
|
|
2739
|
-
_interceptionEnabled = false;
|
|
2740
3283
|
_beforeUnloadAccept = true;
|
|
2741
3284
|
/** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
|
|
2742
3285
|
_storeNetworkRequest(requestId, data) {
|
|
@@ -2745,284 +3288,30 @@ Last error: ${lastError.message}` : "";
|
|
|
2745
3288
|
_storeNetworkResponse(requestId, data) {
|
|
2746
3289
|
this._networkResponses.set(requestId, { requestId, ...data });
|
|
2747
3290
|
}
|
|
2748
|
-
// ── waitForResponse ─────────────────────────────────────────
|
|
2749
3291
|
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
|
-
});
|
|
3292
|
+
return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
|
|
2785
3293
|
}
|
|
2786
|
-
// ── waitForRequest ──────────────────────────────────────────
|
|
2787
3294
|
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
|
-
});
|
|
3295
|
+
return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
|
|
2824
3296
|
}
|
|
2825
|
-
// ── waitForURL ──────────────────────────────────────────────
|
|
2826
3297
|
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
|
-
}
|
|
3298
|
+
return this.networkWaitService.waitForURL(url, opts);
|
|
2863
3299
|
}
|
|
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
|
-
}
|
|
3300
|
+
async route(pattern, handler) {
|
|
3301
|
+
return this.networkRouteService.route(pattern, handler);
|
|
2874
3302
|
}
|
|
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
|
-
});
|
|
3303
|
+
async unroute(pattern) {
|
|
3304
|
+
return this.networkRouteService.unroute(pattern);
|
|
2906
3305
|
}
|
|
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
3306
|
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
|
-
`);
|
|
3307
|
+
return this.fileInputService.dropFiles(selector, payload);
|
|
2937
3308
|
}
|
|
2938
3309
|
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
|
-
`);
|
|
3310
|
+
return this.fileInputService.setInputFiles(selector, files);
|
|
2968
3311
|
}
|
|
2969
|
-
// ── dragAndDrop ─────────────────────────────────────────────
|
|
2970
3312
|
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
|
-
}
|
|
3313
|
+
return this.fileInputService.dragAndDrop(source, target);
|
|
3024
3314
|
}
|
|
3025
|
-
// ── setOfflineMode ──────────────────────────────────────────
|
|
3026
3315
|
async setOfflineMode(offline) {
|
|
3027
3316
|
await this.conn.send("Network.emulateNetworkConditions", {
|
|
3028
3317
|
offline,
|
|
@@ -3318,7 +3607,7 @@ var XBBrowserImpl = class {
|
|
|
3318
3607
|
this._exitHandler = null;
|
|
3319
3608
|
}
|
|
3320
3609
|
if (this.childProcess) {
|
|
3321
|
-
const { killChrome: killChrome2 } = await import("./launcher-
|
|
3610
|
+
const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3322
3611
|
await killChrome2(this.childProcess, this.tmpDir);
|
|
3323
3612
|
}
|
|
3324
3613
|
await this.conn.close();
|
|
@@ -3488,7 +3777,7 @@ var XBBrowserImpl = class {
|
|
|
3488
3777
|
if (pageTargets.length === 0 && httpFallbackUrl) {
|
|
3489
3778
|
console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
|
|
3490
3779
|
try {
|
|
3491
|
-
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-
|
|
3780
|
+
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3492
3781
|
const httpPages = await getCDPTargets2(httpFallbackUrl);
|
|
3493
3782
|
console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
|
|
3494
3783
|
for (const p of httpPages) {
|
|
@@ -3934,6 +4223,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
|
|
|
3934
4223
|
return null;
|
|
3935
4224
|
}
|
|
3936
4225
|
|
|
4226
|
+
// src/cdp-interceptor/rules/humanize-transform.ts
|
|
4227
|
+
var CURSOR_KEY = "humanize-cursor";
|
|
4228
|
+
var KEYS_KEY = "humanize-keys";
|
|
4229
|
+
var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
|
|
4230
|
+
var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
|
|
4231
|
+
function rand2(min, max) {
|
|
4232
|
+
return min + Math.random() * (max - min);
|
|
4233
|
+
}
|
|
4234
|
+
function roundCoordinate(value) {
|
|
4235
|
+
return Math.round(value * 100) / 100;
|
|
4236
|
+
}
|
|
4237
|
+
function humanMousePath(fromX, fromY, toX, toY) {
|
|
4238
|
+
const dist = Math.hypot(toX - fromX, toY - fromY);
|
|
4239
|
+
const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
|
|
4240
|
+
const shortMove = dist < 120;
|
|
4241
|
+
const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
|
|
4242
|
+
const dir = Math.random() < 0.5 ? 1 : -1;
|
|
4243
|
+
const dx = toX - fromX;
|
|
4244
|
+
const dy = toY - fromY;
|
|
4245
|
+
const d = dist || 1;
|
|
4246
|
+
const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
|
|
4247
|
+
const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
|
|
4248
|
+
const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
|
|
4249
|
+
const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
|
|
4250
|
+
const amp = shortMove ? Math.min(2, 3.2) : 3.2;
|
|
4251
|
+
const points = [];
|
|
4252
|
+
for (let i = 1; i <= n; i++) {
|
|
4253
|
+
const t = i / n;
|
|
4254
|
+
const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
|
|
4255
|
+
const mt = 1 - eased;
|
|
4256
|
+
const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
|
|
4257
|
+
const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
|
|
4258
|
+
points.push({
|
|
4259
|
+
x: roundCoordinate(px + rand2(-amp, amp)),
|
|
4260
|
+
y: roundCoordinate(py + rand2(-amp, amp)),
|
|
4261
|
+
delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
|
|
4262
|
+
});
|
|
4263
|
+
}
|
|
4264
|
+
if (!shortMove) {
|
|
4265
|
+
const over = rand2(6, 14);
|
|
4266
|
+
points.push({
|
|
4267
|
+
x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
|
|
4268
|
+
y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
|
|
4269
|
+
delay: Math.round(rand2(14, 30))
|
|
4270
|
+
});
|
|
4271
|
+
points.push({
|
|
4272
|
+
x: roundCoordinate(toX + dx / d * over * 0.4),
|
|
4273
|
+
y: roundCoordinate(toY + dy / d * over * 0.4),
|
|
4274
|
+
delay: Math.round(rand2(14, 30))
|
|
4275
|
+
});
|
|
4276
|
+
}
|
|
4277
|
+
points.push({
|
|
4278
|
+
x: roundCoordinate(toX + rand2(-1, 1)),
|
|
4279
|
+
y: roundCoordinate(toY + rand2(-1, 1)),
|
|
4280
|
+
delay: Math.round(rand2(14, 30))
|
|
4281
|
+
});
|
|
4282
|
+
return points;
|
|
4283
|
+
}
|
|
4284
|
+
function characterKeyEvents(text) {
|
|
4285
|
+
const events = [];
|
|
4286
|
+
for (const char of text) {
|
|
4287
|
+
if (char === "\n") {
|
|
4288
|
+
events.push(
|
|
4289
|
+
{ type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
|
|
4290
|
+
{ type: "char", text: "\r" },
|
|
4291
|
+
{ type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
|
|
4292
|
+
);
|
|
4293
|
+
continue;
|
|
4294
|
+
}
|
|
4295
|
+
events.push(
|
|
4296
|
+
{ type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
|
|
4297
|
+
{ type: "char", text: char },
|
|
4298
|
+
{ type: "keyUp", key: char }
|
|
4299
|
+
);
|
|
4300
|
+
}
|
|
4301
|
+
return events;
|
|
4302
|
+
}
|
|
4303
|
+
function isMouseEvent(method) {
|
|
4304
|
+
return method === "Input.dispatchMouseEvent";
|
|
4305
|
+
}
|
|
4306
|
+
var humanizeTransformRule = {
|
|
4307
|
+
id: "humanize-transform",
|
|
4308
|
+
name: "Humanize Trusted Input Transform",
|
|
4309
|
+
priority: 45,
|
|
4310
|
+
canHandle(ctx) {
|
|
4311
|
+
return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
|
|
4312
|
+
},
|
|
4313
|
+
evaluate(ctx) {
|
|
4314
|
+
if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
|
|
4315
|
+
return this.transformMouseEvent(ctx);
|
|
4316
|
+
},
|
|
4317
|
+
transformMouseEvent(ctx) {
|
|
4318
|
+
const params = ctx.params;
|
|
4319
|
+
if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
|
|
4320
|
+
const x = params.x;
|
|
4321
|
+
const y = params.y;
|
|
4322
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
4323
|
+
ctx.sessionState.set(CURSOR_KEY, { x, y });
|
|
4324
|
+
}
|
|
4325
|
+
return null;
|
|
4326
|
+
}
|
|
4327
|
+
const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
|
|
4328
|
+
const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
|
|
4329
|
+
ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
|
|
4330
|
+
if (jump < 32) return null;
|
|
4331
|
+
const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
|
|
4332
|
+
return {
|
|
4333
|
+
ruleId: this.id,
|
|
4334
|
+
action: "transform",
|
|
4335
|
+
severity: "info",
|
|
4336
|
+
reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
|
|
4337
|
+
suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
|
|
4338
|
+
transformedParams: { __sequence: path.map((point) => ({
|
|
4339
|
+
method: "Input.dispatchMouseEvent",
|
|
4340
|
+
params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
|
|
4341
|
+
delayMs: point.delay
|
|
4342
|
+
})) }
|
|
4343
|
+
};
|
|
4344
|
+
},
|
|
4345
|
+
transformInsertText(ctx) {
|
|
4346
|
+
const params = ctx.params;
|
|
4347
|
+
const text = params.text ?? "";
|
|
4348
|
+
if (!text) return null;
|
|
4349
|
+
const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
|
|
4350
|
+
const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
|
|
4351
|
+
const events = characterKeyEvents(text).map((event, index) => ({
|
|
4352
|
+
method: "Input.dispatchKeyEvent",
|
|
4353
|
+
params: event,
|
|
4354
|
+
delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
|
|
4355
|
+
}));
|
|
4356
|
+
timing.lastDelay = bucket;
|
|
4357
|
+
ctx.sessionState.set(KEYS_KEY, timing);
|
|
4358
|
+
return {
|
|
4359
|
+
ruleId: this.id,
|
|
4360
|
+
action: "transform",
|
|
4361
|
+
severity: "info",
|
|
4362
|
+
reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
|
|
4363
|
+
suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
|
|
4364
|
+
transformedParams: { __sequence: events }
|
|
4365
|
+
};
|
|
4366
|
+
}
|
|
4367
|
+
};
|
|
4368
|
+
|
|
3937
4369
|
// src/cdp-interceptor/rules/automation-signals.ts
|
|
3938
4370
|
var AUTOMATION_PATTERNS = [
|
|
3939
4371
|
// ── Playwright markers ─────────────────────────
|
|
@@ -4452,6 +4884,7 @@ var BUILTIN_RULES = [
|
|
|
4452
4884
|
eventSimulationRule,
|
|
4453
4885
|
mouseTrajectoryRule,
|
|
4454
4886
|
inputKeystrokeRule,
|
|
4887
|
+
humanizeTransformRule,
|
|
4455
4888
|
emulationOverrideRule,
|
|
4456
4889
|
networkAnomalyRule,
|
|
4457
4890
|
pageLifecycleRule
|
|
@@ -4484,8 +4917,10 @@ function createRuleEngine(customRules) {
|
|
|
4484
4917
|
if (isProbeMarked(code)) return null;
|
|
4485
4918
|
} catch {
|
|
4486
4919
|
}
|
|
4920
|
+
const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
|
|
4487
4921
|
for (const rule of rules) {
|
|
4488
4922
|
if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
|
|
4923
|
+
if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
|
|
4489
4924
|
const decision = rule.evaluate(fullCtx);
|
|
4490
4925
|
if (!decision) continue;
|
|
4491
4926
|
if (decision.action !== "pass") return decision;
|
|
@@ -4627,6 +5062,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
|
|
|
4627
5062
|
if (decision && decision.action === "block") {
|
|
4628
5063
|
throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
|
|
4629
5064
|
}
|
|
5065
|
+
if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
|
|
5066
|
+
const sequence = decision.transformedParams.__sequence;
|
|
5067
|
+
let last;
|
|
5068
|
+
for (const step of sequence) {
|
|
5069
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
5070
|
+
last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
|
|
5071
|
+
}
|
|
5072
|
+
return last;
|
|
5073
|
+
}
|
|
4630
5074
|
}
|
|
4631
5075
|
if (this.closed) {
|
|
4632
5076
|
throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
|
|
@@ -4869,7 +5313,7 @@ async function launch(options = {}) {
|
|
|
4869
5313
|
const bv = await conn.send("Browser.getVersion");
|
|
4870
5314
|
const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
|
|
4871
5315
|
if (m && !options.stealthConfig?.uaChProfile) {
|
|
4872
|
-
const { deriveUaChProfileForBinary } = await import("./stealth-
|
|
5316
|
+
const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
|
|
4873
5317
|
stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
|
|
4874
5318
|
}
|
|
4875
5319
|
} catch {
|