@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
|
@@ -5,17 +5,17 @@ import {
|
|
|
5
5
|
landingOffset,
|
|
6
6
|
rand,
|
|
7
7
|
typingDelay
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-SMYSNO4M.js";
|
|
9
9
|
import {
|
|
10
10
|
connectToCDP,
|
|
11
11
|
launchChrome
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-2KPI5GKP.js";
|
|
13
13
|
import {
|
|
14
14
|
errMsg
|
|
15
15
|
} from "./chunk-GDKLH7ZY.js";
|
|
16
16
|
import {
|
|
17
17
|
createRuleEngine
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-6UJU2FJK.js";
|
|
19
19
|
import {
|
|
20
20
|
__require
|
|
21
21
|
} from "./chunk-KFQGP6VL.js";
|
|
@@ -1432,6 +1432,216 @@ var XBElementHandleImpl = class {
|
|
|
1432
1432
|
}
|
|
1433
1433
|
};
|
|
1434
1434
|
|
|
1435
|
+
// src/cdp-driver/page-media.ts
|
|
1436
|
+
var MediaService = class {
|
|
1437
|
+
constructor(options) {
|
|
1438
|
+
this.options = options;
|
|
1439
|
+
}
|
|
1440
|
+
options;
|
|
1441
|
+
async screenshot(opts = {}) {
|
|
1442
|
+
const params = {
|
|
1443
|
+
format: opts.type ?? "png"
|
|
1444
|
+
};
|
|
1445
|
+
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
1446
|
+
params.quality = opts.quality;
|
|
1447
|
+
}
|
|
1448
|
+
if (opts.fullPage) {
|
|
1449
|
+
params.captureBeyondViewport = true;
|
|
1450
|
+
}
|
|
1451
|
+
if (opts.clip) {
|
|
1452
|
+
const clip = {
|
|
1453
|
+
x: Math.round(opts.clip.x),
|
|
1454
|
+
y: Math.round(opts.clip.y),
|
|
1455
|
+
width: Math.round(Math.max(1, opts.clip.width)),
|
|
1456
|
+
height: Math.round(Math.max(1, opts.clip.height)),
|
|
1457
|
+
scale: 1
|
|
1458
|
+
};
|
|
1459
|
+
params.clip = clip;
|
|
1460
|
+
}
|
|
1461
|
+
if (opts.omitBackground) {
|
|
1462
|
+
params.omitBackground = true;
|
|
1463
|
+
}
|
|
1464
|
+
const result = await this.options.conn.send(
|
|
1465
|
+
"Page.captureScreenshot",
|
|
1466
|
+
params,
|
|
1467
|
+
this.options.sessionId
|
|
1468
|
+
);
|
|
1469
|
+
return Buffer.from(result.data, "base64");
|
|
1470
|
+
}
|
|
1471
|
+
async pdf(opts = {}) {
|
|
1472
|
+
const params = {};
|
|
1473
|
+
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
1474
|
+
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
1475
|
+
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
1476
|
+
if (opts.format) params.paperFormat = opts.format;
|
|
1477
|
+
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
1478
|
+
if (opts.margin) {
|
|
1479
|
+
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
1480
|
+
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
1481
|
+
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
1482
|
+
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
1483
|
+
}
|
|
1484
|
+
const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
|
|
1485
|
+
return Buffer.from(result.data, "base64");
|
|
1486
|
+
}
|
|
1487
|
+
viewportSize() {
|
|
1488
|
+
return this.options.viewportSize ?? null;
|
|
1489
|
+
}
|
|
1490
|
+
async setViewportSize(size) {
|
|
1491
|
+
await this.options.conn.send(
|
|
1492
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1493
|
+
{
|
|
1494
|
+
width: size.width,
|
|
1495
|
+
height: size.height,
|
|
1496
|
+
deviceScaleFactor: 1,
|
|
1497
|
+
mobile: false
|
|
1498
|
+
},
|
|
1499
|
+
this.options.sessionId
|
|
1500
|
+
);
|
|
1501
|
+
this.options.onViewportSize(size);
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
1505
|
+
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
1506
|
+
*/
|
|
1507
|
+
async setDeviceScaleFactor(dsf) {
|
|
1508
|
+
const size = this.options.viewportSize ?? await this.options.evaluate(
|
|
1509
|
+
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
1510
|
+
);
|
|
1511
|
+
await this.options.conn.send(
|
|
1512
|
+
"Emulation.setDeviceMetricsOverride",
|
|
1513
|
+
{
|
|
1514
|
+
width: size.width,
|
|
1515
|
+
height: size.height,
|
|
1516
|
+
deviceScaleFactor: dsf,
|
|
1517
|
+
mobile: false
|
|
1518
|
+
},
|
|
1519
|
+
this.options.sessionId
|
|
1520
|
+
);
|
|
1521
|
+
this.options.onViewportSize(size);
|
|
1522
|
+
}
|
|
1523
|
+
// ── Scripts ─────────────────────────────────────────────────
|
|
1524
|
+
};
|
|
1525
|
+
|
|
1526
|
+
// src/cdp-driver/page-file-input.ts
|
|
1527
|
+
var FileInputService = class {
|
|
1528
|
+
constructor(options) {
|
|
1529
|
+
this.options = options;
|
|
1530
|
+
}
|
|
1531
|
+
options;
|
|
1532
|
+
async dropFiles(selector, payload) {
|
|
1533
|
+
await this.options.evaluate(`
|
|
1534
|
+
(function() {
|
|
1535
|
+
var el = ${queryJS(selector)};
|
|
1536
|
+
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
1537
|
+
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
1538
|
+
var bin = atob(b64);
|
|
1539
|
+
var buf = new Uint8Array(bin.length);
|
|
1540
|
+
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
1541
|
+
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
1542
|
+
var dt = new DataTransfer();
|
|
1543
|
+
dt.items.add(file);
|
|
1544
|
+
var rect = el.getBoundingClientRect();
|
|
1545
|
+
var opts = {
|
|
1546
|
+
bubbles: true, cancelable: true,
|
|
1547
|
+
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
1548
|
+
};
|
|
1549
|
+
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
1550
|
+
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
1551
|
+
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
1552
|
+
})()
|
|
1553
|
+
`);
|
|
1554
|
+
}
|
|
1555
|
+
async setInputFiles(selector, files) {
|
|
1556
|
+
const fileArr = Array.isArray(files) ? files : [files];
|
|
1557
|
+
const fileList = fileArr.map((f) => ({
|
|
1558
|
+
name: f.name,
|
|
1559
|
+
type: f.mimeType,
|
|
1560
|
+
dataBase64: f.buffer.toString("base64")
|
|
1561
|
+
}));
|
|
1562
|
+
await this.options.evaluate(`
|
|
1563
|
+
(function() {
|
|
1564
|
+
var selector = ${JSON.stringify(selector)};
|
|
1565
|
+
var input = ${queryJS(selector)};
|
|
1566
|
+
if (!input) throw new Error('Element not found: ' + selector);
|
|
1567
|
+
|
|
1568
|
+
var fileList = ${JSON.stringify(fileList)};
|
|
1569
|
+
var dt = new DataTransfer();
|
|
1570
|
+
|
|
1571
|
+
fileList.forEach(function(f) {
|
|
1572
|
+
var binary = atob(f.dataBase64);
|
|
1573
|
+
var bytes = new Uint8Array(binary.length);
|
|
1574
|
+
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1575
|
+
var blob = new Blob([bytes], { type: f.type });
|
|
1576
|
+
var file = new File([blob], f.name, { type: f.type });
|
|
1577
|
+
dt.items.add(file);
|
|
1578
|
+
});
|
|
1579
|
+
|
|
1580
|
+
input.files = dt.files;
|
|
1581
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1582
|
+
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1583
|
+
})()
|
|
1584
|
+
`);
|
|
1585
|
+
}
|
|
1586
|
+
// ── dragAndDrop ─────────────────────────────────────────────
|
|
1587
|
+
async dragAndDrop(source, target) {
|
|
1588
|
+
const sourceRect = await this.options.evaluate(`
|
|
1589
|
+
(function() {
|
|
1590
|
+
const el = ${queryJS(source)};
|
|
1591
|
+
if (!el) throw new Error('Source not found: ${source}');
|
|
1592
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1593
|
+
const r = el.getBoundingClientRect();
|
|
1594
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1595
|
+
})()
|
|
1596
|
+
`);
|
|
1597
|
+
const targetRect = await this.options.evaluate(`
|
|
1598
|
+
(function() {
|
|
1599
|
+
const el = ${queryJS(target)};
|
|
1600
|
+
if (!el) throw new Error('Target not found: ${target}');
|
|
1601
|
+
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
1602
|
+
const r = el.getBoundingClientRect();
|
|
1603
|
+
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
1604
|
+
})()
|
|
1605
|
+
`);
|
|
1606
|
+
const sx = sourceRect.x + sourceRect.width / 2;
|
|
1607
|
+
const sy = sourceRect.y + sourceRect.height / 2;
|
|
1608
|
+
const tx = targetRect.x + targetRect.width / 2;
|
|
1609
|
+
const ty = targetRect.y + targetRect.height / 2;
|
|
1610
|
+
try {
|
|
1611
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1612
|
+
type: "dragStart",
|
|
1613
|
+
x: sx,
|
|
1614
|
+
y: sy,
|
|
1615
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1616
|
+
}, this.options.sessionId);
|
|
1617
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1618
|
+
type: "dragOver",
|
|
1619
|
+
x: tx,
|
|
1620
|
+
y: ty,
|
|
1621
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1622
|
+
}, this.options.sessionId);
|
|
1623
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1624
|
+
type: "drop",
|
|
1625
|
+
x: tx,
|
|
1626
|
+
y: ty,
|
|
1627
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1628
|
+
}, this.options.sessionId);
|
|
1629
|
+
await this.options.conn.send("Input.dispatchDragEvent", {
|
|
1630
|
+
type: "dragCancel",
|
|
1631
|
+
x: sx,
|
|
1632
|
+
y: sy,
|
|
1633
|
+
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
1634
|
+
}, this.options.sessionId);
|
|
1635
|
+
} catch {
|
|
1636
|
+
await this.options.mouse.move(sx, sy);
|
|
1637
|
+
await this.options.mouse.down();
|
|
1638
|
+
await this.options.mouse.move(tx, ty, { steps: 10 });
|
|
1639
|
+
await this.options.mouse.up();
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
// ── setOfflineMode ──────────────────────────────────────────
|
|
1643
|
+
};
|
|
1644
|
+
|
|
1435
1645
|
// src/cdp-driver/page-helpers.ts
|
|
1436
1646
|
function globToRegex(glob) {
|
|
1437
1647
|
let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
|
|
@@ -1580,8 +1790,777 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
|
|
|
1580
1790
|
emitter.emit("response", response);
|
|
1581
1791
|
}
|
|
1582
1792
|
}
|
|
1583
|
-
};
|
|
1584
|
-
}
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
// src/cdp-driver/page-network-events.ts
|
|
1797
|
+
function setupNetworkEvents(options) {
|
|
1798
|
+
options.addSubscription(
|
|
1799
|
+
options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
|
|
1800
|
+
const p = params;
|
|
1801
|
+
options.state.inflightRequests.add(p.requestId);
|
|
1802
|
+
options.storeRequest(p.requestId, {
|
|
1803
|
+
url: p.request.url,
|
|
1804
|
+
method: p.request.method,
|
|
1805
|
+
headers: p.request.headers,
|
|
1806
|
+
postData: p.request.postData ?? null,
|
|
1807
|
+
resourceType: p.type
|
|
1808
|
+
});
|
|
1809
|
+
options.emit("request", createXBRequest(
|
|
1810
|
+
null,
|
|
1811
|
+
{
|
|
1812
|
+
requestId: p.requestId,
|
|
1813
|
+
url: p.request.url,
|
|
1814
|
+
method: p.request.method,
|
|
1815
|
+
headers: p.request.headers,
|
|
1816
|
+
postData: p.request.postData ?? null,
|
|
1817
|
+
resourceType: p.type
|
|
1818
|
+
}
|
|
1819
|
+
));
|
|
1820
|
+
options.checkNetworkIdle();
|
|
1821
|
+
})
|
|
1822
|
+
);
|
|
1823
|
+
options.addSubscription(
|
|
1824
|
+
options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
|
|
1825
|
+
const p = params;
|
|
1826
|
+
options.storeResponse(p.requestId, {
|
|
1827
|
+
status: p.response.status,
|
|
1828
|
+
url: p.response.url,
|
|
1829
|
+
headers: p.response.headers
|
|
1830
|
+
});
|
|
1831
|
+
options.emit("response", createXBResponse(
|
|
1832
|
+
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
1833
|
+
options.conn,
|
|
1834
|
+
options.sessionId
|
|
1835
|
+
));
|
|
1836
|
+
})
|
|
1837
|
+
);
|
|
1838
|
+
options.addSubscription(
|
|
1839
|
+
options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
|
|
1840
|
+
const p = params;
|
|
1841
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1842
|
+
options.emit("requestfinished", p);
|
|
1843
|
+
options.checkNetworkIdle();
|
|
1844
|
+
})
|
|
1845
|
+
);
|
|
1846
|
+
options.addSubscription(
|
|
1847
|
+
options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
|
|
1848
|
+
const p = params;
|
|
1849
|
+
options.state.inflightRequests.delete(p.requestId);
|
|
1850
|
+
options.checkNetworkIdle();
|
|
1851
|
+
})
|
|
1852
|
+
);
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
// src/cdp-driver/page-lifecycle-events.ts
|
|
1856
|
+
function setupPageEvents(options) {
|
|
1857
|
+
options.addSubscription(
|
|
1858
|
+
options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
|
|
1859
|
+
const p = params;
|
|
1860
|
+
if (p.frame) {
|
|
1861
|
+
options.setUrl(p.frame.url);
|
|
1862
|
+
}
|
|
1863
|
+
options.emit("framenavigated", options.mainFrame());
|
|
1864
|
+
})
|
|
1865
|
+
);
|
|
1866
|
+
options.addSubscription(
|
|
1867
|
+
options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
|
|
1868
|
+
options.markLoadFired();
|
|
1869
|
+
})
|
|
1870
|
+
);
|
|
1871
|
+
options.addSubscription(
|
|
1872
|
+
options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
|
|
1873
|
+
options.markDomContentFired();
|
|
1874
|
+
})
|
|
1875
|
+
);
|
|
1876
|
+
options.addSubscription(
|
|
1877
|
+
options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
|
|
1878
|
+
const p = params;
|
|
1879
|
+
const dialog = {
|
|
1880
|
+
type: p.type,
|
|
1881
|
+
message: () => p.message,
|
|
1882
|
+
defaultValue: () => p.defaultValue,
|
|
1883
|
+
accept: async (text) => {
|
|
1884
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1885
|
+
accept: true,
|
|
1886
|
+
promptText: text
|
|
1887
|
+
}, options.sessionId);
|
|
1888
|
+
},
|
|
1889
|
+
dismiss: async () => {
|
|
1890
|
+
await options.conn.send("Page.handleJavaScriptDialog", {
|
|
1891
|
+
accept: false
|
|
1892
|
+
}, options.sessionId);
|
|
1893
|
+
}
|
|
1894
|
+
};
|
|
1895
|
+
options.emit("dialog", dialog);
|
|
1896
|
+
const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
|
|
1897
|
+
setTimeout(() => {
|
|
1898
|
+
options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
|
|
1899
|
+
});
|
|
1900
|
+
}, 0);
|
|
1901
|
+
})
|
|
1902
|
+
);
|
|
1903
|
+
options.addSubscription(
|
|
1904
|
+
options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
|
|
1905
|
+
const p = params;
|
|
1906
|
+
let selector = "";
|
|
1907
|
+
try {
|
|
1908
|
+
const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1909
|
+
const attrs = result.node?.attributes || [];
|
|
1910
|
+
const idIdx = attrs.indexOf("id");
|
|
1911
|
+
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
1912
|
+
} catch {
|
|
1913
|
+
}
|
|
1914
|
+
if (!selector) {
|
|
1915
|
+
try {
|
|
1916
|
+
const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
|
|
1917
|
+
const evalResult = await options.conn.send("Runtime.callFunctionOn", {
|
|
1918
|
+
objectId: result.objectId,
|
|
1919
|
+
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
1920
|
+
returnByValue: true
|
|
1921
|
+
}, options.sessionId);
|
|
1922
|
+
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
1923
|
+
} catch {
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
const fileChooser = {
|
|
1927
|
+
selector,
|
|
1928
|
+
isMultiple: p.mode === "selectMultiple",
|
|
1929
|
+
setFiles: async (files) => {
|
|
1930
|
+
const fileArray = Array.isArray(files) ? files : [files];
|
|
1931
|
+
await options.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
1932
|
+
}
|
|
1933
|
+
};
|
|
1934
|
+
options.emit("filechooser", fileChooser);
|
|
1935
|
+
})
|
|
1936
|
+
);
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
// src/cdp-driver/page-network-waits.ts
|
|
1940
|
+
var NetworkWaitService = class {
|
|
1941
|
+
constructor(options) {
|
|
1942
|
+
this.options = options;
|
|
1943
|
+
}
|
|
1944
|
+
options;
|
|
1945
|
+
// ── waitForResponse ─────────────────────────────────────────
|
|
1946
|
+
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
1947
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1948
|
+
const predicate = createResponsePredicate(urlOrPredicate);
|
|
1949
|
+
for (const [, data] of this.options.responses) {
|
|
1950
|
+
const response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1951
|
+
if (predicate(response)) return response;
|
|
1952
|
+
}
|
|
1953
|
+
return new Promise((resolve, reject) => {
|
|
1954
|
+
const timer = setTimeout(() => {
|
|
1955
|
+
this.options.off("response", handler);
|
|
1956
|
+
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
1957
|
+
}, timeout);
|
|
1958
|
+
const handler = (params) => {
|
|
1959
|
+
let response;
|
|
1960
|
+
const respObj = params;
|
|
1961
|
+
if (respObj.response) {
|
|
1962
|
+
const data = {
|
|
1963
|
+
requestId: respObj.requestId || "",
|
|
1964
|
+
status: respObj.response.status || 0,
|
|
1965
|
+
url: respObj.response.url || "",
|
|
1966
|
+
headers: respObj.response.headers || {}
|
|
1967
|
+
};
|
|
1968
|
+
response = createXBResponse(data, this.options.conn, this.options.sessionId);
|
|
1969
|
+
} else if (typeof params.status === "function") {
|
|
1970
|
+
response = params;
|
|
1971
|
+
} else {
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
if (predicate(response)) {
|
|
1975
|
+
clearTimeout(timer);
|
|
1976
|
+
this.options.off("response", handler);
|
|
1977
|
+
resolve(response);
|
|
1978
|
+
}
|
|
1979
|
+
};
|
|
1980
|
+
this.options.on("response", handler);
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
// ── waitForRequest ──────────────────────────────────────────
|
|
1984
|
+
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
1985
|
+
const timeout = opts.timeout ?? 3e4;
|
|
1986
|
+
const predicate = createRequestPredicate(urlOrPredicate);
|
|
1987
|
+
for (const [, data] of this.options.requests) {
|
|
1988
|
+
const request = createXBRequest(this.pageLike(), data);
|
|
1989
|
+
if (predicate(request)) return request;
|
|
1990
|
+
}
|
|
1991
|
+
return new Promise((resolve, reject) => {
|
|
1992
|
+
const timer = setTimeout(() => {
|
|
1993
|
+
this.options.off("request", handler);
|
|
1994
|
+
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
1995
|
+
}, timeout);
|
|
1996
|
+
const handler = (params) => {
|
|
1997
|
+
let request;
|
|
1998
|
+
const reqObj = params;
|
|
1999
|
+
if (reqObj.request) {
|
|
2000
|
+
request = createXBRequest(this.pageLike(), {
|
|
2001
|
+
requestId: reqObj.requestId || "",
|
|
2002
|
+
url: reqObj.request.url || "",
|
|
2003
|
+
method: reqObj.request.method || "",
|
|
2004
|
+
headers: reqObj.request.headers || {},
|
|
2005
|
+
postData: reqObj.request.postData ?? null,
|
|
2006
|
+
resourceType: reqObj.type || ""
|
|
2007
|
+
});
|
|
2008
|
+
} else if (typeof params.url === "function") {
|
|
2009
|
+
request = params;
|
|
2010
|
+
} else {
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
if (predicate(request)) {
|
|
2014
|
+
clearTimeout(timer);
|
|
2015
|
+
this.options.off("request", handler);
|
|
2016
|
+
resolve(request);
|
|
2017
|
+
}
|
|
2018
|
+
};
|
|
2019
|
+
this.options.on("request", handler);
|
|
2020
|
+
});
|
|
2021
|
+
}
|
|
2022
|
+
// ── waitForURL ──────────────────────────────────────────────
|
|
2023
|
+
async waitForURL(url, opts = {}) {
|
|
2024
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2025
|
+
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
2026
|
+
if (checkFn(this.options.currentUrl())) return;
|
|
2027
|
+
return new Promise((resolve, reject) => {
|
|
2028
|
+
const timer = setTimeout(() => {
|
|
2029
|
+
this.options.off("framenavigated", handler);
|
|
2030
|
+
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
2031
|
+
}, timeout);
|
|
2032
|
+
const handler = () => {
|
|
2033
|
+
if (checkFn(this.options.currentUrl())) {
|
|
2034
|
+
clearTimeout(timer);
|
|
2035
|
+
this.options.off("framenavigated", handler);
|
|
2036
|
+
resolve();
|
|
2037
|
+
}
|
|
2038
|
+
};
|
|
2039
|
+
this.options.on("framenavigated", handler);
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
pageLike() {
|
|
2043
|
+
return {
|
|
2044
|
+
_networkResponses: this.options.responses,
|
|
2045
|
+
_connection: this.options.conn,
|
|
2046
|
+
sessionId: this.options.sessionId
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
|
|
2051
|
+
// src/cdp-driver/page-routes.ts
|
|
2052
|
+
var NetworkRouteService = class {
|
|
2053
|
+
constructor(options) {
|
|
2054
|
+
this.options = options;
|
|
2055
|
+
}
|
|
2056
|
+
options;
|
|
2057
|
+
routeHandlers = [];
|
|
2058
|
+
interceptionEnabled = false;
|
|
2059
|
+
get isInterceptionEnabled() {
|
|
2060
|
+
return this.interceptionEnabled;
|
|
2061
|
+
}
|
|
2062
|
+
subscriptions = [];
|
|
2063
|
+
async route(url, handler) {
|
|
2064
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2065
|
+
this.routeHandlers.push({ pattern: String(url), regex, handler });
|
|
2066
|
+
if (!this.interceptionEnabled) {
|
|
2067
|
+
this.interceptionEnabled = true;
|
|
2068
|
+
await this.options.conn.send("Fetch.enable", {
|
|
2069
|
+
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
2070
|
+
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
2071
|
+
// 会顶掉 _init 的 auth 配置)
|
|
2072
|
+
handleAuthRequests: true
|
|
2073
|
+
}, this.options.sessionId);
|
|
2074
|
+
this.subscriptions.push(
|
|
2075
|
+
this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
|
|
2076
|
+
this._handleRequestPaused(params);
|
|
2077
|
+
})
|
|
2078
|
+
);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
async unroute(url, handler) {
|
|
2082
|
+
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2083
|
+
this.routeHandlers = this.routeHandlers.filter(
|
|
2084
|
+
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2085
|
+
);
|
|
2086
|
+
if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
|
|
2087
|
+
this.interceptionEnabled = false;
|
|
2088
|
+
await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
async _handleRequestPaused(params) {
|
|
2093
|
+
const requestUrl = params.request.url;
|
|
2094
|
+
for (const { regex, handler } of this.routeHandlers) {
|
|
2095
|
+
if (regex.test(requestUrl)) {
|
|
2096
|
+
this.options.emit("request", createXBRequest(
|
|
2097
|
+
null,
|
|
2098
|
+
{
|
|
2099
|
+
requestId: params.requestId,
|
|
2100
|
+
url: params.request.url,
|
|
2101
|
+
method: params.request.method,
|
|
2102
|
+
headers: params.request.headers,
|
|
2103
|
+
postData: params.request.postData ?? null,
|
|
2104
|
+
resourceType: params.resourceType
|
|
2105
|
+
}
|
|
2106
|
+
));
|
|
2107
|
+
const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
|
|
2108
|
+
try {
|
|
2109
|
+
await handler(route);
|
|
2110
|
+
} catch {
|
|
2111
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2112
|
+
requestId: params.requestId
|
|
2113
|
+
}, this.options.sessionId).catch(() => {
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
await this.options.conn.send("Fetch.continueRequest", {
|
|
2120
|
+
requestId: params.requestId
|
|
2121
|
+
}, this.options.sessionId).catch(() => {
|
|
2122
|
+
});
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
2125
|
+
|
|
2126
|
+
// src/cdp-driver/page-navigation.ts
|
|
2127
|
+
var NavigationService = class {
|
|
2128
|
+
constructor(options) {
|
|
2129
|
+
this.options = options;
|
|
2130
|
+
}
|
|
2131
|
+
options;
|
|
2132
|
+
async goto(url, opts = {}) {
|
|
2133
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2134
|
+
const waitUntil = opts.waitUntil ?? "load";
|
|
2135
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2136
|
+
this.options.state.loadFired = false;
|
|
2137
|
+
this.options.state.domContentFired = false;
|
|
2138
|
+
this.options.state.networkIdle = false;
|
|
2139
|
+
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
2140
|
+
try {
|
|
2141
|
+
await this.options.conn.send(
|
|
2142
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2143
|
+
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
|
|
2144
|
+
this.options.sessionId
|
|
2145
|
+
);
|
|
2146
|
+
} catch {
|
|
2147
|
+
}
|
|
2148
|
+
try {
|
|
2149
|
+
const rawUa = await this.options.conn.send(
|
|
2150
|
+
"Runtime.evaluate",
|
|
2151
|
+
{ expression: "navigator.userAgent", returnByValue: true },
|
|
2152
|
+
this.options.sessionId
|
|
2153
|
+
);
|
|
2154
|
+
const ua = rawUa?.value || "";
|
|
2155
|
+
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
2156
|
+
if (cleaned !== ua) {
|
|
2157
|
+
await this.options.conn.send(
|
|
2158
|
+
"Network.setUserAgentOverride",
|
|
2159
|
+
{ userAgent: cleaned },
|
|
2160
|
+
this.options.sessionId
|
|
2161
|
+
);
|
|
2162
|
+
}
|
|
2163
|
+
} catch {
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
const result = await this.options.conn.send(
|
|
2167
|
+
"Page.navigate",
|
|
2168
|
+
{ url, referrer: opts.referer },
|
|
2169
|
+
this.options.sessionId
|
|
2170
|
+
);
|
|
2171
|
+
if (result.errorText) {
|
|
2172
|
+
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
2173
|
+
}
|
|
2174
|
+
if (waitUntil === "commit") {
|
|
2175
|
+
this.options.setUrl(url);
|
|
2176
|
+
return {
|
|
2177
|
+
status: () => 0,
|
|
2178
|
+
ok: () => false,
|
|
2179
|
+
url: () => url,
|
|
2180
|
+
headers: () => ({})
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
await this.options.waitForLoadState(waitUntil, timeout);
|
|
2184
|
+
this.options.setUrl(url);
|
|
2185
|
+
const statusCode = 200;
|
|
2186
|
+
const finalUrl = url;
|
|
2187
|
+
const headers = {};
|
|
2188
|
+
return {
|
|
2189
|
+
status: () => statusCode,
|
|
2190
|
+
ok: () => statusCode >= 200 && statusCode < 300,
|
|
2191
|
+
url: () => finalUrl,
|
|
2192
|
+
headers: () => headers
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
async goBack(opts = {}) {
|
|
2196
|
+
try {
|
|
2197
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2198
|
+
if (navHistory.currentIndex > 0) {
|
|
2199
|
+
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
2200
|
+
if (prevUrl && prevUrl !== "about:blank") {
|
|
2201
|
+
await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
|
|
2202
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2203
|
+
});
|
|
2204
|
+
this.options.setUrl(prevUrl);
|
|
2205
|
+
return;
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
} catch {
|
|
2209
|
+
}
|
|
2210
|
+
await this.options.evaluate("() => history.back()");
|
|
2211
|
+
await this.options.waitForTimeout(3e3);
|
|
2212
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2213
|
+
}
|
|
2214
|
+
async goForward(opts = {}) {
|
|
2215
|
+
try {
|
|
2216
|
+
const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
|
|
2217
|
+
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
2218
|
+
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
2219
|
+
if (nextUrl && nextUrl !== "about:blank") {
|
|
2220
|
+
await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
|
|
2221
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
2222
|
+
});
|
|
2223
|
+
this.options.setUrl(nextUrl);
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
} catch {
|
|
2228
|
+
}
|
|
2229
|
+
await this.options.evaluate("() => history.forward()");
|
|
2230
|
+
await this.options.waitForTimeout(3e3);
|
|
2231
|
+
this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
|
|
2232
|
+
}
|
|
2233
|
+
async reload(opts = {}) {
|
|
2234
|
+
this.options.state.loadFired = false;
|
|
2235
|
+
this.options.state.domContentFired = false;
|
|
2236
|
+
this.options.state.networkIdle = false;
|
|
2237
|
+
await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
|
|
2238
|
+
await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2239
|
+
}
|
|
2240
|
+
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
2241
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2242
|
+
const checkState = () => {
|
|
2243
|
+
switch (state) {
|
|
2244
|
+
case "domcontentloaded":
|
|
2245
|
+
return this.options.state.domContentFired;
|
|
2246
|
+
case "load":
|
|
2247
|
+
return this.options.state.loadFired;
|
|
2248
|
+
case "networkidle":
|
|
2249
|
+
return this.options.state.networkIdle;
|
|
2250
|
+
case "commit":
|
|
2251
|
+
return this.options.state.domContentFired;
|
|
2252
|
+
default:
|
|
2253
|
+
return true;
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
if (checkState()) return;
|
|
2257
|
+
return new Promise((resolve, reject) => {
|
|
2258
|
+
const timer = setTimeout(() => {
|
|
2259
|
+
reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
|
|
2260
|
+
}, timeout);
|
|
2261
|
+
const check = () => {
|
|
2262
|
+
if (checkState()) {
|
|
2263
|
+
clearTimeout(timer);
|
|
2264
|
+
resolve();
|
|
2265
|
+
} else {
|
|
2266
|
+
setTimeout(check, 50);
|
|
2267
|
+
}
|
|
2268
|
+
};
|
|
2269
|
+
check();
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
async waitForTimeout(ms) {
|
|
2273
|
+
await new Promise((resolve) => {
|
|
2274
|
+
const timer = setTimeout(resolve, ms);
|
|
2275
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
};
|
|
2279
|
+
|
|
2280
|
+
// src/cdp-driver/page-dom.ts
|
|
2281
|
+
var DomQueryService = class {
|
|
2282
|
+
constructor(options) {
|
|
2283
|
+
this.options = options;
|
|
2284
|
+
}
|
|
2285
|
+
options;
|
|
2286
|
+
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2287
|
+
async querySelector(selector) {
|
|
2288
|
+
if (selector.startsWith("xpath=")) {
|
|
2289
|
+
const found = await this.options.evaluate(`
|
|
2290
|
+
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2291
|
+
`).catch(() => false);
|
|
2292
|
+
if (!found) return 0;
|
|
2293
|
+
try {
|
|
2294
|
+
const search = await this.options.conn.send(
|
|
2295
|
+
"DOM.performSearch",
|
|
2296
|
+
{ query: selector.slice(6) },
|
|
2297
|
+
this.options.sessionId
|
|
2298
|
+
);
|
|
2299
|
+
if (search.nodeId) return search.nodeId;
|
|
2300
|
+
} catch {
|
|
2301
|
+
}
|
|
2302
|
+
return 1;
|
|
2303
|
+
}
|
|
2304
|
+
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2305
|
+
const doc = await withTimeout(
|
|
2306
|
+
this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
|
|
2307
|
+
8e3
|
|
2308
|
+
);
|
|
2309
|
+
if (!doc) return 0;
|
|
2310
|
+
const result = await withTimeout(
|
|
2311
|
+
this.options.conn.send(
|
|
2312
|
+
"DOM.querySelector",
|
|
2313
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2314
|
+
this.options.sessionId
|
|
2315
|
+
),
|
|
2316
|
+
8e3
|
|
2317
|
+
);
|
|
2318
|
+
if (!result) return 0;
|
|
2319
|
+
return result.nodeId;
|
|
2320
|
+
}
|
|
2321
|
+
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2322
|
+
async querySelectorAll(selector) {
|
|
2323
|
+
const doc = await this.options.conn.send(
|
|
2324
|
+
"DOM.getDocument",
|
|
2325
|
+
{ depth: 0 },
|
|
2326
|
+
this.options.sessionId
|
|
2327
|
+
);
|
|
2328
|
+
const result = await this.options.conn.send(
|
|
2329
|
+
"DOM.querySelectorAll",
|
|
2330
|
+
{ nodeId: doc.root.nodeId, selector },
|
|
2331
|
+
this.options.sessionId
|
|
2332
|
+
);
|
|
2333
|
+
return result.nodeIds ?? [];
|
|
2334
|
+
}
|
|
2335
|
+
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2336
|
+
async resolveNode(nodeId) {
|
|
2337
|
+
const result = await this.options.conn.send(
|
|
2338
|
+
"DOM.resolveNode",
|
|
2339
|
+
{ nodeId },
|
|
2340
|
+
this.options.sessionId
|
|
2341
|
+
);
|
|
2342
|
+
return result.object.objectId;
|
|
2343
|
+
}
|
|
2344
|
+
/** Get the box model for a nodeId */
|
|
2345
|
+
async getBoxModel(nodeId) {
|
|
2346
|
+
try {
|
|
2347
|
+
const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
|
|
2348
|
+
const c = result.model?.content;
|
|
2349
|
+
if (!c || c.length < 8) return null;
|
|
2350
|
+
const x1 = c[0];
|
|
2351
|
+
const y1 = c[1];
|
|
2352
|
+
const x2 = c[4];
|
|
2353
|
+
const y2 = c[5];
|
|
2354
|
+
return {
|
|
2355
|
+
x: Math.min(x1, x2),
|
|
2356
|
+
y: Math.min(y1, y2),
|
|
2357
|
+
width: Math.abs(x2 - x1),
|
|
2358
|
+
height: Math.abs(y2 - y1)
|
|
2359
|
+
};
|
|
2360
|
+
} catch {
|
|
2361
|
+
return null;
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
/** Call a function on a RemoteObject */
|
|
2365
|
+
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
2366
|
+
const result = await this.options.conn.send("Runtime.callFunctionOn", {
|
|
2367
|
+
objectId,
|
|
2368
|
+
functionDeclaration,
|
|
2369
|
+
arguments: args.map((a) => ({ value: a })),
|
|
2370
|
+
returnByValue: true
|
|
2371
|
+
}, this.options.sessionId);
|
|
2372
|
+
if (result.exceptionDetails) {
|
|
2373
|
+
throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
|
|
2374
|
+
}
|
|
2375
|
+
return result.result?.value;
|
|
2376
|
+
}
|
|
2377
|
+
/** Send a CDP command scoped to this page's session */
|
|
2378
|
+
async _cdpSend(method, params) {
|
|
2379
|
+
return this.options.conn.send(method, params, this.options.sessionId);
|
|
2380
|
+
}
|
|
2381
|
+
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2382
|
+
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2383
|
+
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2384
|
+
};
|
|
2385
|
+
|
|
2386
|
+
// src/cdp-driver/page-runtime.ts
|
|
2387
|
+
var RuntimeEvaluationService = class {
|
|
2388
|
+
constructor(options) {
|
|
2389
|
+
this.options = options;
|
|
2390
|
+
}
|
|
2391
|
+
options;
|
|
2392
|
+
async title() {
|
|
2393
|
+
let title = "";
|
|
2394
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
2395
|
+
try {
|
|
2396
|
+
title = await this.evaluate("document.title");
|
|
2397
|
+
if (title) return title;
|
|
2398
|
+
} catch {
|
|
2399
|
+
}
|
|
2400
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2401
|
+
}
|
|
2402
|
+
return title;
|
|
2403
|
+
}
|
|
2404
|
+
async content() {
|
|
2405
|
+
return this.evaluate("document.documentElement.outerHTML");
|
|
2406
|
+
}
|
|
2407
|
+
// ── Evaluation ──────────────────────────────────────────────
|
|
2408
|
+
async evaluate(fn, ...args) {
|
|
2409
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2410
|
+
this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
|
|
2411
|
+
});
|
|
2412
|
+
let expression;
|
|
2413
|
+
if (typeof fn === "string") {
|
|
2414
|
+
expression = fn;
|
|
2415
|
+
} else {
|
|
2416
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2417
|
+
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2418
|
+
}
|
|
2419
|
+
const result = await this.options.conn.send("Runtime.evaluate", {
|
|
2420
|
+
expression,
|
|
2421
|
+
returnByValue: true,
|
|
2422
|
+
awaitPromise: true
|
|
2423
|
+
}, this.options.sessionId);
|
|
2424
|
+
if (result.exceptionDetails) {
|
|
2425
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2426
|
+
throw new Error(`${detail}`);
|
|
2427
|
+
}
|
|
2428
|
+
return result.result?.value;
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2432
|
+
*
|
|
2433
|
+
* 双路径:
|
|
2434
|
+
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2435
|
+
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2436
|
+
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2437
|
+
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2438
|
+
*
|
|
2439
|
+
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2440
|
+
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2441
|
+
*/
|
|
2442
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2443
|
+
if (this.options.isClosed()) throw new Error("Page is closed");
|
|
2444
|
+
const evalIn = async (sessionId, contextId) => {
|
|
2445
|
+
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2446
|
+
if (contextId !== void 0) params.contextId = contextId;
|
|
2447
|
+
const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
|
|
2448
|
+
if (result.exceptionDetails) {
|
|
2449
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2450
|
+
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2451
|
+
}
|
|
2452
|
+
return result.result?.value;
|
|
2453
|
+
};
|
|
2454
|
+
try {
|
|
2455
|
+
const tg = await this.options.conn.send("Target.getTargets", void 0);
|
|
2456
|
+
const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2457
|
+
if (hit2) {
|
|
2458
|
+
const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
|
|
2459
|
+
return evalIn(att.sessionId);
|
|
2460
|
+
}
|
|
2461
|
+
} catch {
|
|
2462
|
+
}
|
|
2463
|
+
const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
|
|
2464
|
+
const all = [];
|
|
2465
|
+
const walk = (node) => {
|
|
2466
|
+
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2467
|
+
for (const child of node.childFrames || []) walk(child);
|
|
2468
|
+
};
|
|
2469
|
+
walk(tree.frameTree);
|
|
2470
|
+
const mainId = tree.frameTree?.frame?.id;
|
|
2471
|
+
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2472
|
+
if (target) {
|
|
2473
|
+
const contexts = [];
|
|
2474
|
+
const onCtx = (raw) => {
|
|
2475
|
+
const c = raw?.context;
|
|
2476
|
+
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2477
|
+
};
|
|
2478
|
+
this.options.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2479
|
+
try {
|
|
2480
|
+
await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
|
|
2481
|
+
});
|
|
2482
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
2483
|
+
} finally {
|
|
2484
|
+
this.options.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2485
|
+
}
|
|
2486
|
+
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2487
|
+
if (ctx) return evalIn(this.options.sessionId, ctx.id);
|
|
2488
|
+
}
|
|
2489
|
+
const attached = [];
|
|
2490
|
+
const onAttach = (raw) => {
|
|
2491
|
+
const ev = raw;
|
|
2492
|
+
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2493
|
+
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2494
|
+
}
|
|
2495
|
+
};
|
|
2496
|
+
this.options.conn.on("Target.attachedToTarget", onAttach);
|
|
2497
|
+
try {
|
|
2498
|
+
await this.options.conn.send("Target.setAutoAttach", {
|
|
2499
|
+
autoAttach: true,
|
|
2500
|
+
waitForDebuggerOnStart: false,
|
|
2501
|
+
flatten: true
|
|
2502
|
+
}, this.options.sessionId);
|
|
2503
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
2504
|
+
} finally {
|
|
2505
|
+
this.options.conn.off("Target.attachedToTarget", onAttach);
|
|
2506
|
+
this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
|
|
2507
|
+
});
|
|
2508
|
+
}
|
|
2509
|
+
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2510
|
+
if (!hit) {
|
|
2511
|
+
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`);
|
|
2512
|
+
}
|
|
2513
|
+
return evalIn(hit.sessionId);
|
|
2514
|
+
}
|
|
2515
|
+
/** evaluateHandle — evaluates fn and returns a handle for element bounding box */
|
|
2516
|
+
async evaluateHandle(fn, ...args) {
|
|
2517
|
+
let expression;
|
|
2518
|
+
if (typeof fn === "string") {
|
|
2519
|
+
expression = fn;
|
|
2520
|
+
} else {
|
|
2521
|
+
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2522
|
+
expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
|
|
2523
|
+
}
|
|
2524
|
+
const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
|
|
2525
|
+
let box = null;
|
|
2526
|
+
try {
|
|
2527
|
+
box = JSON.parse(result.result?.value);
|
|
2528
|
+
} catch {
|
|
2529
|
+
}
|
|
2530
|
+
return {
|
|
2531
|
+
asElement: () => box ? { boundingBox: async () => box } : null
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
async $eval(selector, fn, ...args) {
|
|
2535
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2536
|
+
const selJSON = JSON.stringify(selector);
|
|
2537
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2538
|
+
return this.evaluate(
|
|
2539
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2540
|
+
const el = xpathExpr
|
|
2541
|
+
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2542
|
+
: document.querySelector(sel);
|
|
2543
|
+
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2544
|
+
const fn = new Function('return ' + fnStr)();
|
|
2545
|
+
return fn(el, ...evalArgs);
|
|
2546
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2547
|
+
);
|
|
2548
|
+
}
|
|
2549
|
+
async $$eval(selector, fn, ...args) {
|
|
2550
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2551
|
+
const selJSON = JSON.stringify(selector);
|
|
2552
|
+
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2553
|
+
return this.evaluate(
|
|
2554
|
+
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2555
|
+
const els = xpathExpr
|
|
2556
|
+
? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
|
|
2557
|
+
: Array.from(document.querySelectorAll(sel));
|
|
2558
|
+
const fn = new Function('return ' + fnStr)();
|
|
2559
|
+
return fn(els, ...evalArgs);
|
|
2560
|
+
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2561
|
+
);
|
|
2562
|
+
}
|
|
2563
|
+
};
|
|
1585
2564
|
|
|
1586
2565
|
// src/cdp-driver/page.ts
|
|
1587
2566
|
var XBPageImpl = class _XBPageImpl {
|
|
@@ -1594,7 +2573,6 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1594
2573
|
_browserImpl;
|
|
1595
2574
|
_closed = false;
|
|
1596
2575
|
_url = "about:blank";
|
|
1597
|
-
_title = "";
|
|
1598
2576
|
_viewportSize = null;
|
|
1599
2577
|
_loadState = {
|
|
1600
2578
|
loadFired: true,
|
|
@@ -1603,6 +2581,13 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1603
2581
|
};
|
|
1604
2582
|
mouse;
|
|
1605
2583
|
keyboard;
|
|
2584
|
+
mediaService;
|
|
2585
|
+
fileInputService;
|
|
2586
|
+
networkWaitService;
|
|
2587
|
+
networkRouteService;
|
|
2588
|
+
navigationService;
|
|
2589
|
+
domQueryService;
|
|
2590
|
+
runtimeEvaluationService;
|
|
1606
2591
|
// Network tracking for waitForLoadState('networkidle')
|
|
1607
2592
|
inflightRequests = /* @__PURE__ */ new Set();
|
|
1608
2593
|
networkIdleResolve = null;
|
|
@@ -1616,6 +2601,60 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1616
2601
|
this._browserImpl = browser;
|
|
1617
2602
|
this.mouse = new XBMouseImpl(conn, sessionId);
|
|
1618
2603
|
this.keyboard = new XBKeyboardImpl(conn, sessionId);
|
|
2604
|
+
this.mediaService = new MediaService({
|
|
2605
|
+
conn,
|
|
2606
|
+
sessionId,
|
|
2607
|
+
viewportSize: this._viewportSize,
|
|
2608
|
+
evaluate: (script) => this.evaluate(script),
|
|
2609
|
+
onViewportSize: (size) => {
|
|
2610
|
+
this._viewportSize = size;
|
|
2611
|
+
}
|
|
2612
|
+
});
|
|
2613
|
+
this.fileInputService = new FileInputService({
|
|
2614
|
+
conn,
|
|
2615
|
+
sessionId,
|
|
2616
|
+
evaluate: (script) => this.evaluate(script),
|
|
2617
|
+
mouse: this.mouse
|
|
2618
|
+
});
|
|
2619
|
+
this.networkWaitService = new NetworkWaitService({
|
|
2620
|
+
conn,
|
|
2621
|
+
sessionId,
|
|
2622
|
+
responses: this._networkResponses,
|
|
2623
|
+
requests: this._networkRequests,
|
|
2624
|
+
on: (event, handler) => this._emitter.on(event, handler),
|
|
2625
|
+
off: (event, handler) => this._emitter.removeListener(event, handler),
|
|
2626
|
+
currentUrl: () => this.url()
|
|
2627
|
+
});
|
|
2628
|
+
this.networkRouteService = new NetworkRouteService({
|
|
2629
|
+
conn,
|
|
2630
|
+
sessionId,
|
|
2631
|
+
emit: (event, ...args) => this._emit(event, ...args)
|
|
2632
|
+
});
|
|
2633
|
+
this.navigationService = new NavigationService({
|
|
2634
|
+
conn,
|
|
2635
|
+
sessionId,
|
|
2636
|
+
state: this._loadState,
|
|
2637
|
+
stealthConfig: this._contextImpl.stealthConfig,
|
|
2638
|
+
isClosed: () => this._closed,
|
|
2639
|
+
setUrl: (url) => {
|
|
2640
|
+
this._url = url;
|
|
2641
|
+
},
|
|
2642
|
+
currentUrl: () => this.url(),
|
|
2643
|
+
waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
|
|
2644
|
+
waitForTimeout: (ms) => this.waitForTimeout(ms),
|
|
2645
|
+
evaluate: (script) => this.evaluate(script)
|
|
2646
|
+
});
|
|
2647
|
+
this.runtimeEvaluationService = new RuntimeEvaluationService({
|
|
2648
|
+
conn,
|
|
2649
|
+
sessionId,
|
|
2650
|
+
isClosed: () => this._closed,
|
|
2651
|
+
url: () => this.url()
|
|
2652
|
+
});
|
|
2653
|
+
this.domQueryService = new DomQueryService({
|
|
2654
|
+
conn,
|
|
2655
|
+
sessionId,
|
|
2656
|
+
evaluate: (script) => this.evaluate(script)
|
|
2657
|
+
});
|
|
1619
2658
|
}
|
|
1620
2659
|
_emit(event, ...args) {
|
|
1621
2660
|
this._emitter.emit(event, ...args);
|
|
@@ -1641,7 +2680,7 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1641
2680
|
});
|
|
1642
2681
|
this._subscriptions.push(
|
|
1643
2682
|
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
1644
|
-
if (this.
|
|
2683
|
+
if (this.networkRouteService.isInterceptionEnabled) return;
|
|
1645
2684
|
const p = params;
|
|
1646
2685
|
this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
|
|
1647
2686
|
});
|
|
@@ -1821,7 +2860,6 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1821
2860
|
{ targetId: this._targetId }
|
|
1822
2861
|
);
|
|
1823
2862
|
this._url = info.url;
|
|
1824
|
-
this._title = info.title;
|
|
1825
2863
|
if (info.url && info.url !== "about:blank" && info.url !== "") {
|
|
1826
2864
|
this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
|
|
1827
2865
|
}
|
|
@@ -1833,108 +2871,16 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1833
2871
|
}
|
|
1834
2872
|
// ── Navigation ──────────────────────────────────────────────
|
|
1835
2873
|
async goto(url, opts = {}) {
|
|
1836
|
-
|
|
1837
|
-
const waitUntil = opts.waitUntil ?? "load";
|
|
1838
|
-
const timeout = opts.timeout ?? 3e4;
|
|
1839
|
-
this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
|
|
1840
|
-
if (process.env.XBROWSER_STEALTH !== "off") {
|
|
1841
|
-
try {
|
|
1842
|
-
await this.conn.send(
|
|
1843
|
-
"Page.addScriptToEvaluateOnNewDocument",
|
|
1844
|
-
{ source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
|
|
1845
|
-
this.sessionId
|
|
1846
|
-
);
|
|
1847
|
-
} catch {
|
|
1848
|
-
}
|
|
1849
|
-
try {
|
|
1850
|
-
const rawUa = await this.conn.send(
|
|
1851
|
-
"Runtime.evaluate",
|
|
1852
|
-
{ expression: "navigator.userAgent", returnByValue: true },
|
|
1853
|
-
this.sessionId
|
|
1854
|
-
);
|
|
1855
|
-
const ua = rawUa?.value || "";
|
|
1856
|
-
const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
|
|
1857
|
-
if (cleaned !== ua) {
|
|
1858
|
-
await this.conn.send(
|
|
1859
|
-
"Network.setUserAgentOverride",
|
|
1860
|
-
{ userAgent: cleaned },
|
|
1861
|
-
this.sessionId
|
|
1862
|
-
);
|
|
1863
|
-
}
|
|
1864
|
-
} catch {
|
|
1865
|
-
}
|
|
1866
|
-
}
|
|
1867
|
-
const result = await this.conn.send(
|
|
1868
|
-
"Page.navigate",
|
|
1869
|
-
{ url, referrer: opts.referer },
|
|
1870
|
-
this.sessionId
|
|
1871
|
-
);
|
|
1872
|
-
if (result.errorText) {
|
|
1873
|
-
throw new Error(`Navigation failed: ${result.errorText}`);
|
|
1874
|
-
}
|
|
1875
|
-
if (waitUntil === "commit") {
|
|
1876
|
-
this._url = url;
|
|
1877
|
-
return {
|
|
1878
|
-
status: () => 0,
|
|
1879
|
-
ok: () => false,
|
|
1880
|
-
url: () => url,
|
|
1881
|
-
headers: () => ({})
|
|
1882
|
-
};
|
|
1883
|
-
}
|
|
1884
|
-
await this.waitForLoadState(waitUntil, timeout);
|
|
1885
|
-
this._url = url;
|
|
1886
|
-
const statusCode = 200;
|
|
1887
|
-
const finalUrl = url;
|
|
1888
|
-
const headers = {};
|
|
1889
|
-
return {
|
|
1890
|
-
status: () => statusCode,
|
|
1891
|
-
ok: () => statusCode >= 200 && statusCode < 300,
|
|
1892
|
-
url: () => finalUrl,
|
|
1893
|
-
headers: () => headers
|
|
1894
|
-
};
|
|
2874
|
+
return this.navigationService.goto(url, opts);
|
|
1895
2875
|
}
|
|
1896
2876
|
async goBack(opts = {}) {
|
|
1897
|
-
|
|
1898
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1899
|
-
if (navHistory.currentIndex > 0) {
|
|
1900
|
-
const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
|
|
1901
|
-
if (prevUrl && prevUrl !== "about:blank") {
|
|
1902
|
-
await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
|
|
1903
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1904
|
-
});
|
|
1905
|
-
this._url = prevUrl;
|
|
1906
|
-
return;
|
|
1907
|
-
}
|
|
1908
|
-
}
|
|
1909
|
-
} catch {
|
|
1910
|
-
}
|
|
1911
|
-
await this.evaluate("() => history.back()");
|
|
1912
|
-
await this.waitForTimeout(3e3);
|
|
1913
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
2877
|
+
return this.navigationService.goBack(opts);
|
|
1914
2878
|
}
|
|
1915
2879
|
async goForward(opts = {}) {
|
|
1916
|
-
|
|
1917
|
-
const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
|
|
1918
|
-
if (navHistory.currentIndex < navHistory.entries.length - 1) {
|
|
1919
|
-
const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
|
|
1920
|
-
if (nextUrl && nextUrl !== "about:blank") {
|
|
1921
|
-
await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
|
|
1922
|
-
await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
|
|
1923
|
-
});
|
|
1924
|
-
this._url = nextUrl;
|
|
1925
|
-
return;
|
|
1926
|
-
}
|
|
1927
|
-
}
|
|
1928
|
-
} catch {
|
|
1929
|
-
}
|
|
1930
|
-
await this.evaluate("() => history.forward()");
|
|
1931
|
-
await this.waitForTimeout(3e3);
|
|
1932
|
-
this._url = await this.evaluate("location.href").catch(() => this._url);
|
|
2880
|
+
return this.navigationService.goForward(opts);
|
|
1933
2881
|
}
|
|
1934
2882
|
async reload(opts = {}) {
|
|
1935
|
-
this.
|
|
1936
|
-
await this.conn.send("Page.reload", void 0, this.sessionId);
|
|
1937
|
-
await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
|
|
2883
|
+
return this.navigationService.reload(opts);
|
|
1938
2884
|
}
|
|
1939
2885
|
async waitForLoadState(state = "load", timeout = 3e4) {
|
|
1940
2886
|
if (this._closed) throw new Error("Page is closed");
|
|
@@ -1990,221 +2936,63 @@ var XBPageImpl = class _XBPageImpl {
|
|
|
1990
2936
|
);
|
|
1991
2937
|
if (visible) return;
|
|
1992
2938
|
}
|
|
1993
|
-
if (state === "hidden") {
|
|
1994
|
-
if (!exists) return;
|
|
1995
|
-
const visible = await this.evaluate(
|
|
1996
|
-
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
1997
|
-
);
|
|
1998
|
-
if (!visible) return;
|
|
1999
|
-
}
|
|
2000
|
-
await this.waitForTimeout(100);
|
|
2001
|
-
}
|
|
2002
|
-
throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
|
|
2003
|
-
}
|
|
2004
|
-
async waitForFunction(fn, opts = {}, ...args) {
|
|
2005
|
-
const timeout = opts.timeout ?? 3e4;
|
|
2006
|
-
const polling = opts.polling ?? 100;
|
|
2007
|
-
const deadline = Date.now() + timeout;
|
|
2008
|
-
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2009
|
-
let lastError = null;
|
|
2010
|
-
while (Date.now() < deadline) {
|
|
2011
|
-
try {
|
|
2012
|
-
const result = await this.evaluate(
|
|
2013
|
-
`(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(", ") : ""})`
|
|
2014
|
-
);
|
|
2015
|
-
if (result) return result;
|
|
2016
|
-
} catch (err) {
|
|
2017
|
-
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
2018
|
-
}
|
|
2019
|
-
const pollMs = typeof polling === "number" ? polling : 16;
|
|
2020
|
-
await this.waitForTimeout(pollMs);
|
|
2021
|
-
}
|
|
2022
|
-
const detail = lastError ? `
|
|
2023
|
-
Last error: ${lastError.message}` : "";
|
|
2024
|
-
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
2025
|
-
}
|
|
2026
|
-
url() {
|
|
2027
|
-
return this._url;
|
|
2028
|
-
}
|
|
2029
|
-
async title() {
|
|
2030
|
-
for (let i = 0; i < 20; i++) {
|
|
2031
|
-
try {
|
|
2032
|
-
this._title = await this.evaluate("document.title");
|
|
2033
|
-
if (this._title) return this._title;
|
|
2034
|
-
} catch {
|
|
2035
|
-
}
|
|
2036
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
2037
|
-
}
|
|
2038
|
-
try {
|
|
2039
|
-
const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
|
|
2040
|
-
if (info?.title) {
|
|
2041
|
-
this._title = info.title;
|
|
2042
|
-
return this._title;
|
|
2043
|
-
}
|
|
2044
|
-
} catch {
|
|
2045
|
-
}
|
|
2046
|
-
return this._title;
|
|
2047
|
-
}
|
|
2048
|
-
async content() {
|
|
2049
|
-
return this.evaluate("document.documentElement.outerHTML");
|
|
2050
|
-
}
|
|
2051
|
-
// ── Evaluation ──────────────────────────────────────────────
|
|
2052
|
-
async evaluate(fn, ...args) {
|
|
2053
|
-
if (this._closed) throw new Error("Page is closed");
|
|
2054
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
|
|
2055
|
-
});
|
|
2056
|
-
let expression;
|
|
2057
|
-
if (typeof fn === "string") {
|
|
2058
|
-
expression = fn;
|
|
2059
|
-
} else {
|
|
2060
|
-
const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
|
|
2061
|
-
expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
|
|
2062
|
-
}
|
|
2063
|
-
const result = await this.conn.send("Runtime.evaluate", {
|
|
2064
|
-
expression,
|
|
2065
|
-
returnByValue: true,
|
|
2066
|
-
awaitPromise: true
|
|
2067
|
-
}, this.sessionId);
|
|
2068
|
-
if (result.exceptionDetails) {
|
|
2069
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2070
|
-
throw new Error(`${detail}`);
|
|
2071
|
-
}
|
|
2072
|
-
return result.result?.value;
|
|
2073
|
-
}
|
|
2074
|
-
/**
|
|
2075
|
-
* 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
|
|
2076
|
-
*
|
|
2077
|
-
* 双路径:
|
|
2078
|
-
* 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
|
|
2079
|
-
* 找到目标 frameId 的 contextId,用 contextId 定向执行;
|
|
2080
|
-
* 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
|
|
2081
|
-
* attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
|
|
2082
|
-
*
|
|
2083
|
-
* 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
|
|
2084
|
-
* 支付窗/验证码/第三方嵌入内容的读写都靠它。
|
|
2085
|
-
*/
|
|
2086
|
-
async evaluateInFrame(urlIncludes, expression) {
|
|
2087
|
-
if (this._closed) throw new Error("Page is closed");
|
|
2088
|
-
const evalIn = async (sessionId, contextId) => {
|
|
2089
|
-
const params = { expression, returnByValue: true, awaitPromise: true };
|
|
2090
|
-
if (contextId !== void 0) params.contextId = contextId;
|
|
2091
|
-
const result = await this.conn.send("Runtime.evaluate", params, sessionId);
|
|
2092
|
-
if (result.exceptionDetails) {
|
|
2093
|
-
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
|
|
2094
|
-
throw new Error(`[frame ${urlIncludes}] ${detail}`);
|
|
2095
|
-
}
|
|
2096
|
-
return result.result?.value;
|
|
2097
|
-
};
|
|
2098
|
-
try {
|
|
2099
|
-
const tg = await this.conn.send("Target.getTargets", void 0);
|
|
2100
|
-
const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
|
|
2101
|
-
if (hit2) {
|
|
2102
|
-
const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
|
|
2103
|
-
return evalIn(att.sessionId);
|
|
2104
|
-
}
|
|
2105
|
-
} catch {
|
|
2106
|
-
}
|
|
2107
|
-
const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
|
|
2108
|
-
const all = [];
|
|
2109
|
-
const walk = (node) => {
|
|
2110
|
-
all.push({ id: node.frame.id, url: node.frame.url });
|
|
2111
|
-
for (const child of node.childFrames || []) walk(child);
|
|
2112
|
-
};
|
|
2113
|
-
walk(tree.frameTree);
|
|
2114
|
-
const mainId = tree.frameTree?.frame?.id;
|
|
2115
|
-
const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
|
|
2116
|
-
if (target) {
|
|
2117
|
-
const contexts = [];
|
|
2118
|
-
const onCtx = (raw) => {
|
|
2119
|
-
const c = raw?.context;
|
|
2120
|
-
if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
|
|
2121
|
-
};
|
|
2122
|
-
this.conn.on("Runtime.executionContextCreated", onCtx);
|
|
2123
|
-
try {
|
|
2124
|
-
await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
|
|
2125
|
-
});
|
|
2126
|
-
await new Promise((r) => setTimeout(r, 400));
|
|
2127
|
-
} finally {
|
|
2128
|
-
this.conn.off("Runtime.executionContextCreated", onCtx);
|
|
2129
|
-
}
|
|
2130
|
-
const ctx = contexts.find((c) => c.frameId === target.id);
|
|
2131
|
-
if (ctx) return evalIn(this.sessionId, ctx.id);
|
|
2132
|
-
}
|
|
2133
|
-
const attached = [];
|
|
2134
|
-
const onAttach = (raw) => {
|
|
2135
|
-
const ev = raw;
|
|
2136
|
-
if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
|
|
2137
|
-
attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
|
|
2138
|
-
}
|
|
2139
|
-
};
|
|
2140
|
-
this.conn.on("Target.attachedToTarget", onAttach);
|
|
2141
|
-
try {
|
|
2142
|
-
await this.conn.send("Target.setAutoAttach", {
|
|
2143
|
-
autoAttach: true,
|
|
2144
|
-
waitForDebuggerOnStart: false,
|
|
2145
|
-
flatten: true
|
|
2146
|
-
}, this.sessionId);
|
|
2147
|
-
await new Promise((r) => setTimeout(r, 600));
|
|
2148
|
-
} finally {
|
|
2149
|
-
this.conn.off("Target.attachedToTarget", onAttach);
|
|
2150
|
-
this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
|
|
2151
|
-
});
|
|
2152
|
-
}
|
|
2153
|
-
const hit = attached.find((a) => a.url.includes(urlIncludes));
|
|
2154
|
-
if (!hit) {
|
|
2155
|
-
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`);
|
|
2939
|
+
if (state === "hidden") {
|
|
2940
|
+
if (!exists) return;
|
|
2941
|
+
const visible = await this.evaluate(
|
|
2942
|
+
`(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
|
|
2943
|
+
);
|
|
2944
|
+
if (!visible) return;
|
|
2945
|
+
}
|
|
2946
|
+
await this.waitForTimeout(100);
|
|
2156
2947
|
}
|
|
2157
|
-
|
|
2948
|
+
throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
|
|
2158
2949
|
}
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2950
|
+
async waitForFunction(fn, opts = {}, ...args) {
|
|
2951
|
+
const timeout = opts.timeout ?? 3e4;
|
|
2952
|
+
const polling = opts.polling ?? 100;
|
|
2953
|
+
const deadline = Date.now() + timeout;
|
|
2954
|
+
const fnBody = typeof fn === "function" ? fn.toString() : fn;
|
|
2955
|
+
let lastError = null;
|
|
2956
|
+
while (Date.now() < deadline) {
|
|
2957
|
+
try {
|
|
2958
|
+
const result = await this.evaluate(
|
|
2959
|
+
`(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(", ") : ""})`
|
|
2960
|
+
);
|
|
2961
|
+
if (result) return result;
|
|
2962
|
+
} catch (err) {
|
|
2963
|
+
lastError = err instanceof Error ? err : new Error(errMsg(err));
|
|
2964
|
+
}
|
|
2965
|
+
const pollMs = typeof polling === "number" ? polling : 16;
|
|
2966
|
+
await this.waitForTimeout(pollMs);
|
|
2173
2967
|
}
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
};
|
|
2968
|
+
const detail = lastError ? `
|
|
2969
|
+
Last error: ${lastError.message}` : "";
|
|
2970
|
+
throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
|
|
2971
|
+
}
|
|
2972
|
+
url() {
|
|
2973
|
+
return this._url;
|
|
2974
|
+
}
|
|
2975
|
+
async title() {
|
|
2976
|
+
return this.runtimeEvaluationService.title();
|
|
2977
|
+
}
|
|
2978
|
+
async content() {
|
|
2979
|
+
return this.runtimeEvaluationService.content();
|
|
2980
|
+
}
|
|
2981
|
+
async evaluate(fn, ...args) {
|
|
2982
|
+
return this.runtimeEvaluationService.evaluate(fn, ...args);
|
|
2983
|
+
}
|
|
2984
|
+
async evaluateInFrame(urlIncludes, expression) {
|
|
2985
|
+
return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
|
|
2986
|
+
}
|
|
2987
|
+
async evaluateHandle(script, ...args) {
|
|
2988
|
+
return this.runtimeEvaluationService.evaluateHandle(script, ...args);
|
|
2177
2989
|
}
|
|
2178
2990
|
async $eval(selector, fn, ...args) {
|
|
2179
|
-
|
|
2180
|
-
const selJSON = JSON.stringify(selector);
|
|
2181
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2182
|
-
return this.evaluate(
|
|
2183
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2184
|
-
const el = xpathExpr
|
|
2185
|
-
? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
|
|
2186
|
-
: document.querySelector(sel);
|
|
2187
|
-
if (!el) throw new Error('No element found for selector: ' + sel);
|
|
2188
|
-
const fn = new Function('return ' + fnStr)();
|
|
2189
|
-
return fn(el, ...evalArgs);
|
|
2190
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2191
|
-
);
|
|
2991
|
+
return this.runtimeEvaluationService.$eval(selector, fn, ...args);
|
|
2192
2992
|
}
|
|
2193
2993
|
async $$eval(selector, fn, ...args) {
|
|
2194
|
-
|
|
2195
|
-
const selJSON = JSON.stringify(selector);
|
|
2196
|
-
const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
|
|
2197
|
-
return this.evaluate(
|
|
2198
|
-
`(function(sel, xpathExpr, fnStr, ...evalArgs) {
|
|
2199
|
-
const els = xpathExpr
|
|
2200
|
-
? (() => { 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; })()
|
|
2201
|
-
: Array.from(document.querySelectorAll(sel));
|
|
2202
|
-
const fn = new Function('return ' + fnStr)();
|
|
2203
|
-
return fn(els, ...evalArgs);
|
|
2204
|
-
})(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
|
|
2205
|
-
);
|
|
2994
|
+
return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
|
|
2206
2995
|
}
|
|
2207
|
-
// ── Locator ─────────────────────────────────────────────────
|
|
2208
2996
|
locator(selector) {
|
|
2209
2997
|
return new XBLocatorImpl(this, selector);
|
|
2210
2998
|
}
|
|
@@ -2325,88 +3113,20 @@ Last error: ${lastError.message}` : "";
|
|
|
2325
3113
|
}
|
|
2326
3114
|
// ── Screen ──────────────────────────────────────────────────
|
|
2327
3115
|
async screenshot(opts = {}) {
|
|
2328
|
-
|
|
2329
|
-
format: opts.type ?? "png"
|
|
2330
|
-
};
|
|
2331
|
-
if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
|
|
2332
|
-
params.quality = opts.quality;
|
|
2333
|
-
}
|
|
2334
|
-
if (opts.fullPage) {
|
|
2335
|
-
params.captureBeyondViewport = true;
|
|
2336
|
-
}
|
|
2337
|
-
if (opts.clip) {
|
|
2338
|
-
const clip = {
|
|
2339
|
-
x: Math.round(opts.clip.x),
|
|
2340
|
-
y: Math.round(opts.clip.y),
|
|
2341
|
-
width: Math.round(Math.max(1, opts.clip.width)),
|
|
2342
|
-
height: Math.round(Math.max(1, opts.clip.height)),
|
|
2343
|
-
scale: 1
|
|
2344
|
-
};
|
|
2345
|
-
params.clip = clip;
|
|
2346
|
-
}
|
|
2347
|
-
if (opts.omitBackground) {
|
|
2348
|
-
params.omitBackground = true;
|
|
2349
|
-
}
|
|
2350
|
-
const result = await this.conn.send(
|
|
2351
|
-
"Page.captureScreenshot",
|
|
2352
|
-
params,
|
|
2353
|
-
this.sessionId
|
|
2354
|
-
);
|
|
2355
|
-
return Buffer.from(result.data, "base64");
|
|
3116
|
+
return this.mediaService.screenshot(opts);
|
|
2356
3117
|
}
|
|
2357
3118
|
async pdf(opts = {}) {
|
|
2358
|
-
|
|
2359
|
-
if (opts.landscape !== void 0) params.landscape = opts.landscape;
|
|
2360
|
-
if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
|
|
2361
|
-
if (opts.scale !== void 0) params.scale = opts.scale;
|
|
2362
|
-
if (opts.format) params.paperFormat = opts.format;
|
|
2363
|
-
if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
|
|
2364
|
-
if (opts.margin) {
|
|
2365
|
-
if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
|
|
2366
|
-
if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
|
|
2367
|
-
if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
|
|
2368
|
-
if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
|
|
2369
|
-
}
|
|
2370
|
-
const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
|
|
2371
|
-
return Buffer.from(result.data, "base64");
|
|
3119
|
+
return this.mediaService.pdf(opts);
|
|
2372
3120
|
}
|
|
2373
3121
|
viewportSize() {
|
|
2374
|
-
return this._viewportSize
|
|
3122
|
+
return this._viewportSize;
|
|
2375
3123
|
}
|
|
2376
3124
|
async setViewportSize(size) {
|
|
2377
|
-
|
|
2378
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2379
|
-
{
|
|
2380
|
-
width: size.width,
|
|
2381
|
-
height: size.height,
|
|
2382
|
-
deviceScaleFactor: 1,
|
|
2383
|
-
mobile: false
|
|
2384
|
-
},
|
|
2385
|
-
this.sessionId
|
|
2386
|
-
);
|
|
2387
|
-
this._viewportSize = size;
|
|
3125
|
+
return this.mediaService.setViewportSize(size);
|
|
2388
3126
|
}
|
|
2389
|
-
/**
|
|
2390
|
-
* env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
|
|
2391
|
-
* 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
|
|
2392
|
-
*/
|
|
2393
3127
|
async setDeviceScaleFactor(dsf) {
|
|
2394
|
-
|
|
2395
|
-
"({ width: window.innerWidth, height: window.innerHeight })"
|
|
2396
|
-
);
|
|
2397
|
-
await this.conn.send(
|
|
2398
|
-
"Emulation.setDeviceMetricsOverride",
|
|
2399
|
-
{
|
|
2400
|
-
width: size.width,
|
|
2401
|
-
height: size.height,
|
|
2402
|
-
deviceScaleFactor: dsf,
|
|
2403
|
-
mobile: false
|
|
2404
|
-
},
|
|
2405
|
-
this.sessionId
|
|
2406
|
-
);
|
|
2407
|
-
this._viewportSize = size;
|
|
3128
|
+
return this.mediaService.setDeviceScaleFactor(dsf);
|
|
2408
3129
|
}
|
|
2409
|
-
// ── Scripts ─────────────────────────────────────────────────
|
|
2410
3130
|
async addInitScript(script) {
|
|
2411
3131
|
await this.conn.send(
|
|
2412
3132
|
"Page.addScriptToEvaluateOnNewDocument",
|
|
@@ -2534,83 +3254,17 @@ Last error: ${lastError.message}` : "";
|
|
|
2534
3254
|
}
|
|
2535
3255
|
}
|
|
2536
3256
|
// ── CDP helpers exposed for locator/element ─────────────────
|
|
2537
|
-
/** Query a single element, returns CDP nodeId or 0 if not found */
|
|
2538
3257
|
async querySelector(selector) {
|
|
2539
|
-
|
|
2540
|
-
const found = await this.evaluate(`
|
|
2541
|
-
(() => { const el = ${queryJS(selector)}; return !!el; })()
|
|
2542
|
-
`).catch(() => false);
|
|
2543
|
-
if (!found) return 0;
|
|
2544
|
-
try {
|
|
2545
|
-
const search = await this.conn.send(
|
|
2546
|
-
"DOM.performSearch",
|
|
2547
|
-
{ query: selector.slice(6) },
|
|
2548
|
-
this.sessionId
|
|
2549
|
-
);
|
|
2550
|
-
if (search.nodeId) return search.nodeId;
|
|
2551
|
-
} catch {
|
|
2552
|
-
}
|
|
2553
|
-
return 1;
|
|
2554
|
-
}
|
|
2555
|
-
const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
|
|
2556
|
-
const doc = await withTimeout(
|
|
2557
|
-
this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
|
|
2558
|
-
8e3
|
|
2559
|
-
);
|
|
2560
|
-
if (!doc) return 0;
|
|
2561
|
-
const result = await withTimeout(
|
|
2562
|
-
this.conn.send(
|
|
2563
|
-
"DOM.querySelector",
|
|
2564
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2565
|
-
this.sessionId
|
|
2566
|
-
),
|
|
2567
|
-
8e3
|
|
2568
|
-
);
|
|
2569
|
-
if (!result) return 0;
|
|
2570
|
-
return result.nodeId;
|
|
3258
|
+
return this.domQueryService.querySelector(selector);
|
|
2571
3259
|
}
|
|
2572
|
-
/** Query all matching elements, returns array of CDP nodeIds */
|
|
2573
3260
|
async querySelectorAll(selector) {
|
|
2574
|
-
|
|
2575
|
-
"DOM.getDocument",
|
|
2576
|
-
{ depth: 0 },
|
|
2577
|
-
this.sessionId
|
|
2578
|
-
);
|
|
2579
|
-
const result = await this.conn.send(
|
|
2580
|
-
"DOM.querySelectorAll",
|
|
2581
|
-
{ nodeId: doc.root.nodeId, selector },
|
|
2582
|
-
this.sessionId
|
|
2583
|
-
);
|
|
2584
|
-
return result.nodeIds ?? [];
|
|
3261
|
+
return this.domQueryService.querySelectorAll(selector);
|
|
2585
3262
|
}
|
|
2586
|
-
/** Resolve a CDP nodeId to a RemoteObject for evaluate */
|
|
2587
3263
|
async resolveNode(nodeId) {
|
|
2588
|
-
|
|
2589
|
-
"DOM.resolveNode",
|
|
2590
|
-
{ nodeId },
|
|
2591
|
-
this.sessionId
|
|
2592
|
-
);
|
|
2593
|
-
return result.object.objectId;
|
|
3264
|
+
return this.domQueryService.resolveNode(nodeId);
|
|
2594
3265
|
}
|
|
2595
|
-
/** Get the box model for a nodeId */
|
|
2596
3266
|
async getBoxModel(nodeId) {
|
|
2597
|
-
|
|
2598
|
-
const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
|
|
2599
|
-
const c = result.model?.content;
|
|
2600
|
-
if (!c || c.length < 8) return null;
|
|
2601
|
-
const x1 = c[0];
|
|
2602
|
-
const y1 = c[1];
|
|
2603
|
-
const x2 = c[4];
|
|
2604
|
-
const y2 = c[5];
|
|
2605
|
-
return {
|
|
2606
|
-
x: Math.min(x1, x2),
|
|
2607
|
-
y: Math.min(y1, y2),
|
|
2608
|
-
width: Math.abs(x2 - x1),
|
|
2609
|
-
height: Math.abs(y2 - y1)
|
|
2610
|
-
};
|
|
2611
|
-
} catch {
|
|
2612
|
-
return null;
|
|
2613
|
-
}
|
|
3267
|
+
return this.domQueryService.getBoxModel(nodeId);
|
|
2614
3268
|
}
|
|
2615
3269
|
/** Call a function on a RemoteObject */
|
|
2616
3270
|
async callFunctionOn(objectId, functionDeclaration, args = []) {
|
|
@@ -2629,9 +3283,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2629
3283
|
async _cdpSend(method, params) {
|
|
2630
3284
|
return this.conn.send(method, params, this.sessionId);
|
|
2631
3285
|
}
|
|
2632
|
-
/** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
|
|
2633
|
-
* 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
|
|
2634
|
-
* accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
|
|
2635
3286
|
setBeforeUnloadBehavior(mode) {
|
|
2636
3287
|
this._beforeUnloadAccept = mode === "accept";
|
|
2637
3288
|
}
|
|
@@ -2648,149 +3299,43 @@ Last error: ${lastError.message}` : "";
|
|
|
2648
3299
|
async setFileDialogInterception(enabled) {
|
|
2649
3300
|
await this.conn.send("Page.setInterceptFileChooserDialog", { enabled }, this.sessionId).catch((e) => console.error("[XBPage] setInterceptFileChooserDialog failed:", errMsg(e)));
|
|
2650
3301
|
}
|
|
2651
|
-
/** Subscribe to a CDP event on this page's session. Returns unsubscribe function. */
|
|
2652
|
-
_subscribe(event, handler) {
|
|
2653
|
-
return this.conn.subscribe(event, this.sessionId, handler);
|
|
2654
|
-
}
|
|
2655
|
-
// ── Private: Event Setup ────────────────────────────────────
|
|
2656
|
-
setupPageEvents() {
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
this.
|
|
2664
|
-
}
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
this._loadState.loadFired = true;
|
|
2669
|
-
}
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
);
|
|
2676
|
-
|
|
2677
|
-
this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
|
|
2678
|
-
const p = params;
|
|
2679
|
-
const dialog = {
|
|
2680
|
-
type: p.type,
|
|
2681
|
-
message: () => p.message,
|
|
2682
|
-
defaultValue: () => p.defaultValue,
|
|
2683
|
-
accept: async (text) => {
|
|
2684
|
-
await this.conn.send("Page.handleJavaScriptDialog", {
|
|
2685
|
-
accept: true,
|
|
2686
|
-
promptText: text
|
|
2687
|
-
}, this.sessionId);
|
|
2688
|
-
},
|
|
2689
|
-
dismiss: async () => {
|
|
2690
|
-
await this.conn.send("Page.handleJavaScriptDialog", {
|
|
2691
|
-
accept: false
|
|
2692
|
-
}, this.sessionId);
|
|
2693
|
-
}
|
|
2694
|
-
};
|
|
2695
|
-
this._emit("dialog", dialog);
|
|
2696
|
-
const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
|
|
2697
|
-
setTimeout(() => {
|
|
2698
|
-
this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
|
|
2699
|
-
});
|
|
2700
|
-
}, 0);
|
|
2701
|
-
})
|
|
2702
|
-
);
|
|
2703
|
-
this._subscriptions.push(
|
|
2704
|
-
this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
|
|
2705
|
-
const p = params;
|
|
2706
|
-
let selector = "";
|
|
2707
|
-
try {
|
|
2708
|
-
const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2709
|
-
const attrs = result.node?.attributes || [];
|
|
2710
|
-
const idIdx = attrs.indexOf("id");
|
|
2711
|
-
if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
|
|
2712
|
-
} catch {
|
|
2713
|
-
}
|
|
2714
|
-
if (!selector) {
|
|
2715
|
-
try {
|
|
2716
|
-
const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
|
|
2717
|
-
const evalResult = await this.conn.send("Runtime.callFunctionOn", {
|
|
2718
|
-
objectId: result.objectId,
|
|
2719
|
-
functionDeclaration: 'function() { return this.id || this.name || "" }',
|
|
2720
|
-
returnByValue: true
|
|
2721
|
-
}, this.sessionId);
|
|
2722
|
-
if (evalResult.result?.value) selector = "#" + evalResult.result.value;
|
|
2723
|
-
} catch {
|
|
2724
|
-
}
|
|
2725
|
-
}
|
|
2726
|
-
const fileChooser = {
|
|
2727
|
-
selector,
|
|
2728
|
-
isMultiple: p.mode === "selectMultiple",
|
|
2729
|
-
setFiles: async (files) => {
|
|
2730
|
-
const fileArray = Array.isArray(files) ? files : [files];
|
|
2731
|
-
await this.setInputFiles(selector || 'input[type="file"]', fileArray);
|
|
2732
|
-
}
|
|
2733
|
-
};
|
|
2734
|
-
this._emit("filechooser", fileChooser);
|
|
2735
|
-
})
|
|
2736
|
-
);
|
|
2737
|
-
}
|
|
3302
|
+
/** Subscribe to a CDP event on this page's session. Returns unsubscribe function. */
|
|
3303
|
+
_subscribe(event, handler) {
|
|
3304
|
+
return this.conn.subscribe(event, this.sessionId, handler);
|
|
3305
|
+
}
|
|
3306
|
+
// ── Private: Event Setup ────────────────────────────────────
|
|
3307
|
+
setupPageEvents() {
|
|
3308
|
+
setupPageEvents({
|
|
3309
|
+
conn: this.conn,
|
|
3310
|
+
sessionId: this.sessionId,
|
|
3311
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
|
|
3312
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3313
|
+
setUrl: (url) => {
|
|
3314
|
+
this._url = url;
|
|
3315
|
+
},
|
|
3316
|
+
currentUrl: () => this.url(),
|
|
3317
|
+
mainFrame: () => this.mainFrame(),
|
|
3318
|
+
markLoadFired: () => {
|
|
3319
|
+
this._loadState.loadFired = true;
|
|
3320
|
+
},
|
|
3321
|
+
markDomContentFired: () => {
|
|
3322
|
+
this._loadState.domContentFired = true;
|
|
3323
|
+
},
|
|
3324
|
+
getBeforeUnloadAccept: () => this._beforeUnloadAccept,
|
|
3325
|
+
setInputFiles: (selector, files) => this.setInputFiles(selector, files)
|
|
3326
|
+
});
|
|
3327
|
+
}
|
|
2738
3328
|
setupNetworkEvents() {
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
});
|
|
2750
|
-
this._emit("request", createXBRequest(
|
|
2751
|
-
null,
|
|
2752
|
-
{
|
|
2753
|
-
requestId: p.requestId,
|
|
2754
|
-
url: p.request.url,
|
|
2755
|
-
method: p.request.method,
|
|
2756
|
-
headers: p.request.headers,
|
|
2757
|
-
postData: p.request.postData ?? null,
|
|
2758
|
-
resourceType: p.type
|
|
2759
|
-
}
|
|
2760
|
-
));
|
|
2761
|
-
this.checkNetworkIdle();
|
|
2762
|
-
})
|
|
2763
|
-
);
|
|
2764
|
-
this._subscriptions.push(
|
|
2765
|
-
this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
|
|
2766
|
-
const p = params;
|
|
2767
|
-
this._storeNetworkResponse(p.requestId, {
|
|
2768
|
-
status: p.response.status,
|
|
2769
|
-
url: p.response.url,
|
|
2770
|
-
headers: p.response.headers
|
|
2771
|
-
});
|
|
2772
|
-
this._emit("response", createXBResponse(
|
|
2773
|
-
{ requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
|
|
2774
|
-
this.conn,
|
|
2775
|
-
this.sessionId
|
|
2776
|
-
));
|
|
2777
|
-
})
|
|
2778
|
-
);
|
|
2779
|
-
this._subscriptions.push(
|
|
2780
|
-
this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
|
|
2781
|
-
const p = params;
|
|
2782
|
-
this.inflightRequests.delete(p.requestId);
|
|
2783
|
-
this._emit("requestfinished", p);
|
|
2784
|
-
this.checkNetworkIdle();
|
|
2785
|
-
})
|
|
2786
|
-
);
|
|
2787
|
-
this._subscriptions.push(
|
|
2788
|
-
this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
|
|
2789
|
-
const p = params;
|
|
2790
|
-
this.inflightRequests.delete(p.requestId);
|
|
2791
|
-
this.checkNetworkIdle();
|
|
2792
|
-
})
|
|
2793
|
-
);
|
|
3329
|
+
setupNetworkEvents({
|
|
3330
|
+
conn: this.conn,
|
|
3331
|
+
sessionId: this.sessionId,
|
|
3332
|
+
state: { inflightRequests: this.inflightRequests },
|
|
3333
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
3334
|
+
storeRequest: (id, data) => this._storeNetworkRequest(id, data),
|
|
3335
|
+
storeResponse: (id, data) => this._storeNetworkResponse(id, data),
|
|
3336
|
+
checkNetworkIdle: () => this.checkNetworkIdle(),
|
|
3337
|
+
addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
|
|
3338
|
+
});
|
|
2794
3339
|
}
|
|
2795
3340
|
setupConsoleEvents() {
|
|
2796
3341
|
this._subscriptions.push(
|
|
@@ -2836,8 +3381,6 @@ Last error: ${lastError.message}` : "";
|
|
|
2836
3381
|
// ── Network Data Store (for waitForResponse/waitForRequest) ──
|
|
2837
3382
|
_networkResponses = /* @__PURE__ */ new Map();
|
|
2838
3383
|
_networkRequests = /* @__PURE__ */ new Map();
|
|
2839
|
-
_routeHandlers = [];
|
|
2840
|
-
_interceptionEnabled = false;
|
|
2841
3384
|
_beforeUnloadAccept = true;
|
|
2842
3385
|
/** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
|
|
2843
3386
|
_storeNetworkRequest(requestId, data) {
|
|
@@ -2846,284 +3389,30 @@ Last error: ${lastError.message}` : "";
|
|
|
2846
3389
|
_storeNetworkResponse(requestId, data) {
|
|
2847
3390
|
this._networkResponses.set(requestId, { requestId, ...data });
|
|
2848
3391
|
}
|
|
2849
|
-
// ── waitForResponse ─────────────────────────────────────────
|
|
2850
3392
|
async waitForResponse(urlOrPredicate, opts = {}) {
|
|
2851
|
-
|
|
2852
|
-
const predicate = createResponsePredicate(urlOrPredicate);
|
|
2853
|
-
for (const [, data] of this._networkResponses) {
|
|
2854
|
-
const response = createXBResponse(data, this.conn, this.sessionId);
|
|
2855
|
-
if (predicate(response)) return response;
|
|
2856
|
-
}
|
|
2857
|
-
return new Promise((resolve, reject) => {
|
|
2858
|
-
const timer = setTimeout(() => {
|
|
2859
|
-
this._emitter.removeListener("response", handler);
|
|
2860
|
-
reject(new Error(`waitForResponse timed out after ${timeout}ms`));
|
|
2861
|
-
}, timeout);
|
|
2862
|
-
const handler = (params) => {
|
|
2863
|
-
let response;
|
|
2864
|
-
const respObj = params;
|
|
2865
|
-
if (respObj.response) {
|
|
2866
|
-
const data = {
|
|
2867
|
-
requestId: respObj.requestId || "",
|
|
2868
|
-
status: respObj.response.status || 0,
|
|
2869
|
-
url: respObj.response.url || "",
|
|
2870
|
-
headers: respObj.response.headers || {}
|
|
2871
|
-
};
|
|
2872
|
-
response = createXBResponse(data, this.conn, this.sessionId);
|
|
2873
|
-
} else if (typeof params.status === "function") {
|
|
2874
|
-
response = params;
|
|
2875
|
-
} else {
|
|
2876
|
-
return;
|
|
2877
|
-
}
|
|
2878
|
-
if (predicate(response)) {
|
|
2879
|
-
clearTimeout(timer);
|
|
2880
|
-
this._emitter.removeListener("response", handler);
|
|
2881
|
-
resolve(response);
|
|
2882
|
-
}
|
|
2883
|
-
};
|
|
2884
|
-
this._emitter.on("response", handler);
|
|
2885
|
-
});
|
|
3393
|
+
return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
|
|
2886
3394
|
}
|
|
2887
|
-
// ── waitForRequest ──────────────────────────────────────────
|
|
2888
3395
|
async waitForRequest(urlOrPredicate, opts = {}) {
|
|
2889
|
-
|
|
2890
|
-
const predicate = createRequestPredicate(urlOrPredicate);
|
|
2891
|
-
for (const [, data] of this._networkRequests) {
|
|
2892
|
-
const request = createXBRequest(this, data);
|
|
2893
|
-
if (predicate(request)) return request;
|
|
2894
|
-
}
|
|
2895
|
-
return new Promise((resolve, reject) => {
|
|
2896
|
-
const timer = setTimeout(() => {
|
|
2897
|
-
this._emitter.removeListener("request", handler);
|
|
2898
|
-
reject(new Error(`waitForRequest timed out after ${timeout}ms`));
|
|
2899
|
-
}, timeout);
|
|
2900
|
-
const handler = (params) => {
|
|
2901
|
-
let request;
|
|
2902
|
-
const reqObj = params;
|
|
2903
|
-
if (reqObj.request) {
|
|
2904
|
-
request = createXBRequest(this, {
|
|
2905
|
-
requestId: reqObj.requestId || "",
|
|
2906
|
-
url: reqObj.request.url || "",
|
|
2907
|
-
method: reqObj.request.method || "",
|
|
2908
|
-
headers: reqObj.request.headers || {},
|
|
2909
|
-
postData: reqObj.request.postData ?? null,
|
|
2910
|
-
resourceType: reqObj.type || ""
|
|
2911
|
-
});
|
|
2912
|
-
} else if (typeof params.url === "function") {
|
|
2913
|
-
request = params;
|
|
2914
|
-
} else {
|
|
2915
|
-
return;
|
|
2916
|
-
}
|
|
2917
|
-
if (predicate(request)) {
|
|
2918
|
-
clearTimeout(timer);
|
|
2919
|
-
this._emitter.removeListener("request", handler);
|
|
2920
|
-
resolve(request);
|
|
2921
|
-
}
|
|
2922
|
-
};
|
|
2923
|
-
this._emitter.on("request", handler);
|
|
2924
|
-
});
|
|
3396
|
+
return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
|
|
2925
3397
|
}
|
|
2926
|
-
// ── waitForURL ──────────────────────────────────────────────
|
|
2927
3398
|
async waitForURL(url, opts = {}) {
|
|
2928
|
-
|
|
2929
|
-
const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
|
|
2930
|
-
if (checkFn(this._url)) return;
|
|
2931
|
-
return new Promise((resolve, reject) => {
|
|
2932
|
-
const timer = setTimeout(() => {
|
|
2933
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2934
|
-
reject(new Error(`waitForURL timed out after ${timeout}ms`));
|
|
2935
|
-
}, timeout);
|
|
2936
|
-
const handler = () => {
|
|
2937
|
-
if (checkFn(this._url)) {
|
|
2938
|
-
clearTimeout(timer);
|
|
2939
|
-
this._emitter.removeListener("framenavigated", handler);
|
|
2940
|
-
resolve();
|
|
2941
|
-
}
|
|
2942
|
-
};
|
|
2943
|
-
this._emitter.on("framenavigated", handler);
|
|
2944
|
-
});
|
|
2945
|
-
}
|
|
2946
|
-
// ── route / unroute ─────────────────────────────────────────
|
|
2947
|
-
async route(url, handler) {
|
|
2948
|
-
const regex = typeof url === "string" ? globToRegex(url) : url;
|
|
2949
|
-
this._routeHandlers.push({ pattern: String(url), regex, handler });
|
|
2950
|
-
if (!this._interceptionEnabled) {
|
|
2951
|
-
this._interceptionEnabled = true;
|
|
2952
|
-
await this.conn.send("Fetch.enable", {
|
|
2953
|
-
patterns: [{ urlPattern: "*", requestStage: "Request" }],
|
|
2954
|
-
// sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
|
|
2955
|
-
// 会顶掉 _init 的 auth 配置)
|
|
2956
|
-
handleAuthRequests: true
|
|
2957
|
-
}, this.sessionId);
|
|
2958
|
-
this._subscriptions.push(
|
|
2959
|
-
this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
|
|
2960
|
-
this._handleRequestPaused(params);
|
|
2961
|
-
})
|
|
2962
|
-
);
|
|
2963
|
-
}
|
|
3399
|
+
return this.networkWaitService.waitForURL(url, opts);
|
|
2964
3400
|
}
|
|
2965
|
-
async
|
|
2966
|
-
|
|
2967
|
-
this._routeHandlers = this._routeHandlers.filter(
|
|
2968
|
-
(h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
|
|
2969
|
-
);
|
|
2970
|
-
if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
|
|
2971
|
-
this._interceptionEnabled = false;
|
|
2972
|
-
await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
|
|
2973
|
-
});
|
|
2974
|
-
}
|
|
3401
|
+
async route(pattern, handler) {
|
|
3402
|
+
return this.networkRouteService.route(pattern, handler);
|
|
2975
3403
|
}
|
|
2976
|
-
async
|
|
2977
|
-
|
|
2978
|
-
for (const { regex, handler } of this._routeHandlers) {
|
|
2979
|
-
if (regex.test(requestUrl)) {
|
|
2980
|
-
this._emit("request", createXBRequest(
|
|
2981
|
-
null,
|
|
2982
|
-
{
|
|
2983
|
-
requestId: params.requestId,
|
|
2984
|
-
url: params.request.url,
|
|
2985
|
-
method: params.request.method,
|
|
2986
|
-
headers: params.request.headers,
|
|
2987
|
-
postData: params.request.postData ?? null,
|
|
2988
|
-
resourceType: params.resourceType
|
|
2989
|
-
}
|
|
2990
|
-
));
|
|
2991
|
-
const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
|
|
2992
|
-
try {
|
|
2993
|
-
await handler(route);
|
|
2994
|
-
} catch {
|
|
2995
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
2996
|
-
requestId: params.requestId
|
|
2997
|
-
}, this.sessionId).catch(() => {
|
|
2998
|
-
});
|
|
2999
|
-
}
|
|
3000
|
-
return;
|
|
3001
|
-
}
|
|
3002
|
-
}
|
|
3003
|
-
await this.conn.send("Fetch.continueRequest", {
|
|
3004
|
-
requestId: params.requestId
|
|
3005
|
-
}, this.sessionId).catch(() => {
|
|
3006
|
-
});
|
|
3404
|
+
async unroute(pattern) {
|
|
3405
|
+
return this.networkRouteService.unroute(pattern);
|
|
3007
3406
|
}
|
|
3008
|
-
// ── setInputFiles ───────────────────────────────────────────
|
|
3009
|
-
/**
|
|
3010
|
-
* sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
|
|
3011
|
-
* dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
|
|
3012
|
-
* 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
|
|
3013
|
-
* 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
|
|
3014
|
-
* 中心)。
|
|
3015
|
-
*/
|
|
3016
3407
|
async dropFiles(selector, payload) {
|
|
3017
|
-
|
|
3018
|
-
(function() {
|
|
3019
|
-
var el = ${queryJS(selector)};
|
|
3020
|
-
if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
|
|
3021
|
-
var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
|
|
3022
|
-
var bin = atob(b64);
|
|
3023
|
-
var buf = new Uint8Array(bin.length);
|
|
3024
|
-
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
|
3025
|
-
var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
|
|
3026
|
-
var dt = new DataTransfer();
|
|
3027
|
-
dt.items.add(file);
|
|
3028
|
-
var rect = el.getBoundingClientRect();
|
|
3029
|
-
var opts = {
|
|
3030
|
-
bubbles: true, cancelable: true,
|
|
3031
|
-
clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
|
|
3032
|
-
};
|
|
3033
|
-
el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
|
|
3034
|
-
el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
|
|
3035
|
-
el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
|
|
3036
|
-
})()
|
|
3037
|
-
`);
|
|
3408
|
+
return this.fileInputService.dropFiles(selector, payload);
|
|
3038
3409
|
}
|
|
3039
3410
|
async setInputFiles(selector, files) {
|
|
3040
|
-
|
|
3041
|
-
const fileList = fileArr.map((f) => ({
|
|
3042
|
-
name: f.name,
|
|
3043
|
-
type: f.mimeType,
|
|
3044
|
-
dataBase64: f.buffer.toString("base64")
|
|
3045
|
-
}));
|
|
3046
|
-
await this.evaluate(`
|
|
3047
|
-
(function() {
|
|
3048
|
-
var selector = ${JSON.stringify(selector)};
|
|
3049
|
-
var input = ${queryJS(selector)};
|
|
3050
|
-
if (!input) throw new Error('Element not found: ' + selector);
|
|
3051
|
-
|
|
3052
|
-
var fileList = ${JSON.stringify(fileList)};
|
|
3053
|
-
var dt = new DataTransfer();
|
|
3054
|
-
|
|
3055
|
-
fileList.forEach(function(f) {
|
|
3056
|
-
var binary = atob(f.dataBase64);
|
|
3057
|
-
var bytes = new Uint8Array(binary.length);
|
|
3058
|
-
for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
3059
|
-
var blob = new Blob([bytes], { type: f.type });
|
|
3060
|
-
var file = new File([blob], f.name, { type: f.type });
|
|
3061
|
-
dt.items.add(file);
|
|
3062
|
-
});
|
|
3063
|
-
|
|
3064
|
-
input.files = dt.files;
|
|
3065
|
-
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
3066
|
-
input.dispatchEvent(new Event('change', { bubbles: true }));
|
|
3067
|
-
})()
|
|
3068
|
-
`);
|
|
3411
|
+
return this.fileInputService.setInputFiles(selector, files);
|
|
3069
3412
|
}
|
|
3070
|
-
// ── dragAndDrop ─────────────────────────────────────────────
|
|
3071
3413
|
async dragAndDrop(source, target) {
|
|
3072
|
-
|
|
3073
|
-
(function() {
|
|
3074
|
-
const el = ${queryJS(source)};
|
|
3075
|
-
if (!el) throw new Error('Source not found: ${source}');
|
|
3076
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
3077
|
-
const r = el.getBoundingClientRect();
|
|
3078
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
3079
|
-
})()
|
|
3080
|
-
`);
|
|
3081
|
-
const targetRect = await this.evaluate(`
|
|
3082
|
-
(function() {
|
|
3083
|
-
const el = ${queryJS(target)};
|
|
3084
|
-
if (!el) throw new Error('Target not found: ${target}');
|
|
3085
|
-
el.scrollIntoView({ behavior: 'instant', block: 'center' });
|
|
3086
|
-
const r = el.getBoundingClientRect();
|
|
3087
|
-
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
3088
|
-
})()
|
|
3089
|
-
`);
|
|
3090
|
-
const sx = sourceRect.x + sourceRect.width / 2;
|
|
3091
|
-
const sy = sourceRect.y + sourceRect.height / 2;
|
|
3092
|
-
const tx = targetRect.x + targetRect.width / 2;
|
|
3093
|
-
const ty = targetRect.y + targetRect.height / 2;
|
|
3094
|
-
try {
|
|
3095
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3096
|
-
type: "dragStart",
|
|
3097
|
-
x: sx,
|
|
3098
|
-
y: sy,
|
|
3099
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3100
|
-
}, this.sessionId);
|
|
3101
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3102
|
-
type: "dragOver",
|
|
3103
|
-
x: tx,
|
|
3104
|
-
y: ty,
|
|
3105
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3106
|
-
}, this.sessionId);
|
|
3107
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3108
|
-
type: "drop",
|
|
3109
|
-
x: tx,
|
|
3110
|
-
y: ty,
|
|
3111
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3112
|
-
}, this.sessionId);
|
|
3113
|
-
await this.conn.send("Input.dispatchDragEvent", {
|
|
3114
|
-
type: "dragCancel",
|
|
3115
|
-
x: sx,
|
|
3116
|
-
y: sy,
|
|
3117
|
-
data: { items: [], dragOperations: ["copy", "move", "link"] }
|
|
3118
|
-
}, this.sessionId);
|
|
3119
|
-
} catch {
|
|
3120
|
-
await this.mouse.move(sx, sy);
|
|
3121
|
-
await this.mouse.down();
|
|
3122
|
-
await this.mouse.move(tx, ty, { steps: 10 });
|
|
3123
|
-
await this.mouse.up();
|
|
3124
|
-
}
|
|
3414
|
+
return this.fileInputService.dragAndDrop(source, target);
|
|
3125
3415
|
}
|
|
3126
|
-
// ── setOfflineMode ──────────────────────────────────────────
|
|
3127
3416
|
async setOfflineMode(offline) {
|
|
3128
3417
|
await this.conn.send("Network.emulateNetworkConditions", {
|
|
3129
3418
|
offline,
|
|
@@ -3419,7 +3708,7 @@ var XBBrowserImpl = class {
|
|
|
3419
3708
|
this._exitHandler = null;
|
|
3420
3709
|
}
|
|
3421
3710
|
if (this.childProcess) {
|
|
3422
|
-
const { killChrome: killChrome2 } = await import("./launcher-
|
|
3711
|
+
const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3423
3712
|
await killChrome2(this.childProcess, this.tmpDir);
|
|
3424
3713
|
}
|
|
3425
3714
|
await this.conn.close();
|
|
@@ -3589,7 +3878,7 @@ var XBBrowserImpl = class {
|
|
|
3589
3878
|
if (pageTargets.length === 0 && httpFallbackUrl) {
|
|
3590
3879
|
console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
|
|
3591
3880
|
try {
|
|
3592
|
-
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-
|
|
3881
|
+
const { getCDPTargets: getCDPTargets2 } = await import("./launcher-ZYB32LSZ.js");
|
|
3593
3882
|
const httpPages = await getCDPTargets2(httpFallbackUrl);
|
|
3594
3883
|
console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
|
|
3595
3884
|
for (const p of httpPages) {
|
|
@@ -3776,6 +4065,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
|
|
|
3776
4065
|
if (decision && decision.action === "block") {
|
|
3777
4066
|
throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
|
|
3778
4067
|
}
|
|
4068
|
+
if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
|
|
4069
|
+
const sequence = decision.transformedParams.__sequence;
|
|
4070
|
+
let last;
|
|
4071
|
+
for (const step of sequence) {
|
|
4072
|
+
if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
|
|
4073
|
+
last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
|
|
4074
|
+
}
|
|
4075
|
+
return last;
|
|
4076
|
+
}
|
|
3779
4077
|
}
|
|
3780
4078
|
if (this.closed) {
|
|
3781
4079
|
throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
|
|
@@ -4018,7 +4316,7 @@ async function launch(options = {}) {
|
|
|
4018
4316
|
const bv = await conn.send("Browser.getVersion");
|
|
4019
4317
|
const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
|
|
4020
4318
|
if (m && !options.stealthConfig?.uaChProfile) {
|
|
4021
|
-
const { deriveUaChProfileForBinary } = await import("./stealth-
|
|
4319
|
+
const { deriveUaChProfileForBinary } = await import("./stealth-MCKFKPZ6.js");
|
|
4022
4320
|
stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
|
|
4023
4321
|
}
|
|
4024
4322
|
} catch {
|