mcp-browser-dev-tools 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -15
- package/package.json +9 -2
- package/src/action-changes.mjs +340 -0
- package/src/browser-adapter.mjs +40 -4
- package/src/cdp-client.mjs +1006 -50
- package/src/config.mjs +9 -0
- package/src/firefox-bidi-client.mjs +834 -51
- package/src/input-delivery.mjs +82 -0
- package/src/json-schema.mjs +14 -1
- package/src/mcp-server.mjs +59 -8
- package/src/network-control.mjs +156 -0
- package/src/page-context.mjs +315 -3
- package/src/page-script.mjs +1317 -14
- package/src/run-steps.mjs +75 -23
- package/src/run-tabs.mjs +11 -16
- package/src/screenshot-output.mjs +92 -1
- package/src/session-events.mjs +57 -0
- package/src/tool-schemas.mjs +88 -83
- package/src/tool-sets.mjs +73 -0
- package/src/tools/action-tools.mjs +217 -77
- package/src/tools/browser-tools.mjs +12 -19
- package/src/tools/inspection-tools.mjs +88 -54
- package/src/tools/more-tools.mjs +108 -0
- package/src/tools/performance-tools.mjs +116 -0
- package/src/tools/state-tools.mjs +62 -16
- package/src/upload-files.mjs +57 -0
package/src/cdp-client.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
exportHarLikeSummary,
|
|
3
3
|
filterConsoleMessages,
|
|
4
|
+
InFlightRequests,
|
|
4
5
|
summarizeNetworkRequests,
|
|
5
6
|
} from "./session-events.mjs";
|
|
6
7
|
import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
|
|
@@ -8,9 +9,66 @@ import { waitForPageCondition } from "./wait-for.mjs";
|
|
|
8
9
|
import {
|
|
9
10
|
assertEnabled,
|
|
10
11
|
assertPointerTarget,
|
|
12
|
+
buildInputRecorderExpression,
|
|
11
13
|
buildPageContextExpression,
|
|
12
14
|
} from "./page-context.mjs";
|
|
13
15
|
import { buildCdpKeyEvents } from "./keyboard.mjs";
|
|
16
|
+
import { sendCheckedInput } from "./input-delivery.mjs";
|
|
17
|
+
import {
|
|
18
|
+
applyNetworkOptions,
|
|
19
|
+
describeNetworkState,
|
|
20
|
+
inNetworkTurn,
|
|
21
|
+
mockHeaders,
|
|
22
|
+
takeMatchingRule,
|
|
23
|
+
} from "./network-control.mjs";
|
|
24
|
+
import {
|
|
25
|
+
FrameKeys,
|
|
26
|
+
probeScope,
|
|
27
|
+
restoreFrameSelector,
|
|
28
|
+
addFrameSnapshots,
|
|
29
|
+
frameElementSnapshot,
|
|
30
|
+
parseFrameRef,
|
|
31
|
+
shiftFramePoints,
|
|
32
|
+
unknownFrame,
|
|
33
|
+
takeFileTarget,
|
|
34
|
+
assertFileInput,
|
|
35
|
+
uploadResult,
|
|
36
|
+
describePointer,
|
|
37
|
+
dragEnd,
|
|
38
|
+
wheelScroll,
|
|
39
|
+
dragPath,
|
|
40
|
+
pointerFields,
|
|
41
|
+
takeNextRef,
|
|
42
|
+
} from "./page-context.mjs";
|
|
43
|
+
|
|
44
|
+
// How long a drag waits after its first move for the page to start an HTML5
|
|
45
|
+
// drag, and the longest a drag's interception stays open.
|
|
46
|
+
const DRAG_START_MS = 100;
|
|
47
|
+
// The categories DevTools' Performance panel records, so a trace opens there
|
|
48
|
+
// with its timeline, call stacks, and CPU profile.
|
|
49
|
+
const TRACE_CATEGORIES = [
|
|
50
|
+
"-*",
|
|
51
|
+
"devtools.timeline",
|
|
52
|
+
"disabled-by-default-devtools.timeline",
|
|
53
|
+
"disabled-by-default-devtools.timeline.frame",
|
|
54
|
+
"disabled-by-default-devtools.timeline.stack",
|
|
55
|
+
"v8.execute",
|
|
56
|
+
"disabled-by-default-v8.cpu_profiler",
|
|
57
|
+
"blink.console",
|
|
58
|
+
"blink.user_timing",
|
|
59
|
+
"latencyInfo",
|
|
60
|
+
"loading",
|
|
61
|
+
];
|
|
62
|
+
const TRACE_COMPLETE_MS = 60_000;
|
|
63
|
+
// How long a click may take to open a file chooser.
|
|
64
|
+
const FILE_CHOOSER_MS = 2000;
|
|
65
|
+
const DRAG_SESSION_MS = 30_000;
|
|
66
|
+
|
|
67
|
+
function sleep(ms) {
|
|
68
|
+
return new Promise((resolve) => {
|
|
69
|
+
setTimeout(resolve, ms);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
14
72
|
|
|
15
73
|
function toErrorMessage(error) {
|
|
16
74
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -383,6 +441,7 @@ export class CdpSession {
|
|
|
383
441
|
this.eventBufferSize = options.eventBufferSize ?? 200;
|
|
384
442
|
this.onClosed = options.onClosed ?? null;
|
|
385
443
|
this.bufferedEvents = [];
|
|
444
|
+
this.inFlight = new InFlightRequests();
|
|
386
445
|
this.pending = new Map();
|
|
387
446
|
this.nextMessageId = 1;
|
|
388
447
|
this.connectedAt = new Date().toISOString();
|
|
@@ -392,6 +451,12 @@ export class CdpSession {
|
|
|
392
451
|
this.lastNavigationAt = null;
|
|
393
452
|
this.lastReloadAt = null;
|
|
394
453
|
this.viewportOverride = null;
|
|
454
|
+
// Frames: child sessions of cross-site iframes (attached in flatten
|
|
455
|
+
// mode, by session id), the default execution context of each frame,
|
|
456
|
+
// keyed by session and frame id, and the frame keys refs use.
|
|
457
|
+
this.frameSessions = new Map();
|
|
458
|
+
this.frameContexts = new Map();
|
|
459
|
+
this.frameKeys = new FrameKeys();
|
|
395
460
|
}
|
|
396
461
|
|
|
397
462
|
markClosed() {
|
|
@@ -465,7 +530,16 @@ export class CdpSession {
|
|
|
465
530
|
this.send("Log.enable"),
|
|
466
531
|
this.send("Network.enable"),
|
|
467
532
|
]);
|
|
468
|
-
|
|
533
|
+
// Chrome's performance counters count from here, so get_performance's
|
|
534
|
+
// layout, style, and script times cover the whole session.
|
|
535
|
+
await this.send("Performance.enable")
|
|
536
|
+
.then(() => {
|
|
537
|
+
this.performanceEnabled = true;
|
|
538
|
+
})
|
|
539
|
+
.catch(() => {});
|
|
540
|
+
await this.autoAttachFrames(null);
|
|
541
|
+
|
|
542
|
+
await this.installInputRecorder();
|
|
469
543
|
await this.seedBufferedState();
|
|
470
544
|
|
|
471
545
|
return this.getSummary();
|
|
@@ -497,9 +571,247 @@ export class CdpSession {
|
|
|
497
571
|
return;
|
|
498
572
|
}
|
|
499
573
|
|
|
574
|
+
// Events of a cross-site iframe's session only keep the frame records,
|
|
575
|
+
// except a file chooser opened there, which an upload waits for.
|
|
576
|
+
if (message.sessionId) {
|
|
577
|
+
if (message.method === "Page.fileChooserOpened") {
|
|
578
|
+
this.resolveEventWaiters(message.method, {
|
|
579
|
+
...message.params,
|
|
580
|
+
sessionId: message.sessionId,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
this.trackFrameEvent(
|
|
584
|
+
message.method,
|
|
585
|
+
message.params ?? {},
|
|
586
|
+
message.sessionId,
|
|
587
|
+
);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
this.trackFrameEvent(message.method, message.params ?? {}, null);
|
|
500
592
|
this.bufferEvent(message.method, message.params ?? {});
|
|
501
593
|
}
|
|
502
594
|
|
|
595
|
+
// Cross-site iframes run in their own targets; attaching to them in
|
|
596
|
+
// flatten mode gives a session on this connection for each, and doing
|
|
597
|
+
// the same in each such session reaches iframes nested in them.
|
|
598
|
+
async autoAttachFrames(sessionId) {
|
|
599
|
+
await this.send(
|
|
600
|
+
"Target.setAutoAttach",
|
|
601
|
+
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
|
|
602
|
+
sessionId,
|
|
603
|
+
).catch(() => {});
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
trackFrameEvent(method, params, sessionId) {
|
|
607
|
+
const scope = sessionId ?? "";
|
|
608
|
+
if (method === "Runtime.executionContextCreated") {
|
|
609
|
+
const { id, auxData } = params.context ?? {};
|
|
610
|
+
if (auxData?.isDefault && auxData.frameId) {
|
|
611
|
+
this.frameContexts.set(`${scope}:${auxData.frameId}`, id);
|
|
612
|
+
// A frame document that was already loaded gets the recorder late
|
|
613
|
+
// (a new one has it from its start, which this leaves alone).
|
|
614
|
+
this.send(
|
|
615
|
+
"Runtime.evaluate",
|
|
616
|
+
{
|
|
617
|
+
expression: buildInputRecorderExpression(false),
|
|
618
|
+
contextId: id,
|
|
619
|
+
awaitPromise: false,
|
|
620
|
+
returnByValue: true,
|
|
621
|
+
},
|
|
622
|
+
sessionId,
|
|
623
|
+
).catch(() => {});
|
|
624
|
+
}
|
|
625
|
+
} else if (method === "Runtime.executionContextDestroyed") {
|
|
626
|
+
for (const [key, id] of this.frameContexts) {
|
|
627
|
+
if (key.startsWith(`${scope}:`) && id === params.executionContextId) {
|
|
628
|
+
this.frameContexts.delete(key);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
} else if (method === "Runtime.executionContextsCleared") {
|
|
632
|
+
for (const key of Array.from(this.frameContexts.keys())) {
|
|
633
|
+
if (key.startsWith(`${scope}:`)) {
|
|
634
|
+
this.frameContexts.delete(key);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
} else if (
|
|
638
|
+
method === "Target.attachedToTarget" &&
|
|
639
|
+
params.targetInfo?.type === "iframe"
|
|
640
|
+
) {
|
|
641
|
+
const child = params.sessionId;
|
|
642
|
+
this.frameSessions.set(child, {
|
|
643
|
+
sessionId: child,
|
|
644
|
+
frameId: params.targetInfo.targetId,
|
|
645
|
+
parentSessionId: sessionId,
|
|
646
|
+
});
|
|
647
|
+
for (const enable of ["Runtime.enable", "DOM.enable", "Page.enable"]) {
|
|
648
|
+
this.send(enable, {}, child).catch(() => {});
|
|
649
|
+
}
|
|
650
|
+
void this.installInputRecorder(child);
|
|
651
|
+
void this.autoAttachFrames(child);
|
|
652
|
+
} else if (method === "Target.detachedFromTarget") {
|
|
653
|
+
this.frameSessions.delete(params.sessionId);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// The tab's iframes, outermost first: the top target's own frames, then
|
|
658
|
+
// each cross-site iframe's target and its own frames.
|
|
659
|
+
async listFrames() {
|
|
660
|
+
const frames = [];
|
|
661
|
+
const walk = (node, sessionId) => {
|
|
662
|
+
for (const child of node.childFrames ?? []) {
|
|
663
|
+
frames.push({
|
|
664
|
+
id: child.frame.id,
|
|
665
|
+
url: child.frame.url,
|
|
666
|
+
sessionId,
|
|
667
|
+
root: false,
|
|
668
|
+
});
|
|
669
|
+
walk(child, sessionId);
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
const top = await this.send("Page.getFrameTree");
|
|
673
|
+
walk(top.frameTree, null);
|
|
674
|
+
for (const child of this.frameSessions.values()) {
|
|
675
|
+
const tree = await this.send(
|
|
676
|
+
"Page.getFrameTree",
|
|
677
|
+
{},
|
|
678
|
+
child.sessionId,
|
|
679
|
+
).catch(() => null);
|
|
680
|
+
frames.push({
|
|
681
|
+
id: child.frameId,
|
|
682
|
+
url: tree?.frameTree.frame.url ?? "",
|
|
683
|
+
sessionId: child.sessionId,
|
|
684
|
+
root: true,
|
|
685
|
+
});
|
|
686
|
+
if (tree) {
|
|
687
|
+
walk(tree.frameTree, child.sessionId);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return frames;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// The frame's owner element, found in whichever session holds it, and
|
|
694
|
+
// the top-left of its content box in that session's viewport.
|
|
695
|
+
async frameOwner(frameId) {
|
|
696
|
+
for (const sessionId of [null, ...this.frameSessions.keys()]) {
|
|
697
|
+
try {
|
|
698
|
+
const { backendNodeId } = await this.send(
|
|
699
|
+
"DOM.getFrameOwner",
|
|
700
|
+
{ frameId },
|
|
701
|
+
sessionId,
|
|
702
|
+
);
|
|
703
|
+
const { model } = await this.send(
|
|
704
|
+
"DOM.getBoxModel",
|
|
705
|
+
{ backendNodeId },
|
|
706
|
+
sessionId,
|
|
707
|
+
);
|
|
708
|
+
return {
|
|
709
|
+
sessionId,
|
|
710
|
+
backendNodeId,
|
|
711
|
+
x: model.content[0],
|
|
712
|
+
y: model.content[1],
|
|
713
|
+
};
|
|
714
|
+
} catch {
|
|
715
|
+
// Not in this session.
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return null;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// Where the frame's viewport starts in the top page's viewport, adding up
|
|
722
|
+
// the owners of the cross-site frames it is nested in; null when the
|
|
723
|
+
// frame has no box (hidden) or is gone. With scroll, each owner is
|
|
724
|
+
// scrolled into view first, outermost first.
|
|
725
|
+
async frameOffset(frameId, scroll = false) {
|
|
726
|
+
const owner = await this.frameOwner(frameId);
|
|
727
|
+
if (!owner) {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
const parent = owner.sessionId
|
|
731
|
+
? this.frameSessions.get(owner.sessionId)
|
|
732
|
+
: null;
|
|
733
|
+
if (scroll) {
|
|
734
|
+
if (parent) {
|
|
735
|
+
await this.frameOffset(parent.frameId, true);
|
|
736
|
+
}
|
|
737
|
+
await this.send(
|
|
738
|
+
"DOM.scrollIntoViewIfNeeded",
|
|
739
|
+
{ backendNodeId: owner.backendNodeId },
|
|
740
|
+
owner.sessionId,
|
|
741
|
+
).catch(() => {});
|
|
742
|
+
return this.frameOffset(frameId, false);
|
|
743
|
+
}
|
|
744
|
+
const base = parent
|
|
745
|
+
? await this.frameOffset(parent.frameId)
|
|
746
|
+
: { x: 0, y: 0 };
|
|
747
|
+
return base ? { x: base.x + owner.x, y: base.y + owner.y } : null;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Runs a page action in a frame: in its target's session for a cross-site
|
|
751
|
+
// frame's own document, else in the frame's default execution context.
|
|
752
|
+
async runInFrame(frameKey, payload, options = {}) {
|
|
753
|
+
const frame = this.frameKeys.get(frameKey);
|
|
754
|
+
if (!frame) {
|
|
755
|
+
return unknownFrame(frameKey, payload.selector);
|
|
756
|
+
}
|
|
757
|
+
// Change tracking needs no position, and works in a hidden frame.
|
|
758
|
+
const positioned = options.offset !== false;
|
|
759
|
+
// A drop target is read without scrolling, so the drag's source stays
|
|
760
|
+
// where it was measured.
|
|
761
|
+
const before = positioned
|
|
762
|
+
? await this.frameOffset(
|
|
763
|
+
frame.id,
|
|
764
|
+
options.scroll ?? payload.scrollIntoView !== false,
|
|
765
|
+
)
|
|
766
|
+
: { x: 0, y: 0 };
|
|
767
|
+
const contextId = frame.root
|
|
768
|
+
? undefined
|
|
769
|
+
: this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`);
|
|
770
|
+
if (!before || (!frame.root && contextId === undefined)) {
|
|
771
|
+
return unknownFrame(frameKey, payload.selector);
|
|
772
|
+
}
|
|
773
|
+
const response = await this.send(
|
|
774
|
+
"Runtime.evaluate",
|
|
775
|
+
{
|
|
776
|
+
expression: buildPageContextExpression(
|
|
777
|
+
{ browserFamily: cdpBrowserFamily(this.config), ...payload },
|
|
778
|
+
{ serialize: true },
|
|
779
|
+
),
|
|
780
|
+
awaitPromise: true,
|
|
781
|
+
returnByValue: true,
|
|
782
|
+
userGesture: options.userGesture ?? false,
|
|
783
|
+
...(contextId !== undefined ? { contextId } : {}),
|
|
784
|
+
},
|
|
785
|
+
frame.sessionId,
|
|
786
|
+
);
|
|
787
|
+
if (response.exceptionDetails) {
|
|
788
|
+
throw new Error(pageExceptionMessage(response.exceptionDetails));
|
|
789
|
+
}
|
|
790
|
+
const value = response.result?.value;
|
|
791
|
+
const result = typeof value === "string" ? JSON.parse(value) : value;
|
|
792
|
+
// The action may have scrolled the frame's ancestors, moving the frame.
|
|
793
|
+
const offset = positioned
|
|
794
|
+
? ((await this.frameOffset(frame.id)) ?? before)
|
|
795
|
+
: before;
|
|
796
|
+
return shiftFramePoints(result, offset);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// Where a frame ref's own document runs, for protocol calls that must
|
|
800
|
+
// reach it: the session and execution context.
|
|
801
|
+
frameScope(selector) {
|
|
802
|
+
const route = parseFrameRef(selector);
|
|
803
|
+
const frame = route ? this.frameKeys.get(route.frameKey) : null;
|
|
804
|
+
if (!frame) {
|
|
805
|
+
return { sessionId: null, contextId: undefined };
|
|
806
|
+
}
|
|
807
|
+
return {
|
|
808
|
+
sessionId: frame.sessionId,
|
|
809
|
+
contextId: frame.root
|
|
810
|
+
? undefined
|
|
811
|
+
: this.frameContexts.get(`${frame.sessionId ?? ""}:${frame.id}`),
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
|
|
503
815
|
bufferEvent(method, params) {
|
|
504
816
|
const capturedAt = new Date().toISOString();
|
|
505
817
|
if (
|
|
@@ -524,6 +836,10 @@ export class CdpSession {
|
|
|
524
836
|
this.autoDismissDialog(params);
|
|
525
837
|
}
|
|
526
838
|
|
|
839
|
+
if (method === "Fetch.requestPaused") {
|
|
840
|
+
void this.handleRequestPaused(params);
|
|
841
|
+
}
|
|
842
|
+
|
|
527
843
|
this.pushEvent({
|
|
528
844
|
method,
|
|
529
845
|
capturedAt,
|
|
@@ -532,12 +848,89 @@ export class CdpSession {
|
|
|
532
848
|
this.resolveEventWaiters(method, params);
|
|
533
849
|
}
|
|
534
850
|
|
|
851
|
+
// Fetch pauses only requests whose URL matches a rule's pattern, so other
|
|
852
|
+
// requests are not slowed by a round trip to the server.
|
|
853
|
+
// One call at a time per tab, so a reset cannot be undone by a call that
|
|
854
|
+
// started before it.
|
|
855
|
+
async setNetwork(options) {
|
|
856
|
+
return inNetworkTurn(this, () => this.applyNetwork(options));
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async applyNetwork(options) {
|
|
860
|
+
const before = this.network;
|
|
861
|
+
const state = applyNetworkOptions(before, options);
|
|
862
|
+
// Requests paused once the new patterns apply see the new rules.
|
|
863
|
+
this.network = state;
|
|
864
|
+
if (state.rules.length > 0) {
|
|
865
|
+
await this.send("Fetch.enable", {
|
|
866
|
+
patterns: state.rules.map((rule) => ({
|
|
867
|
+
urlPattern: rule.url,
|
|
868
|
+
requestStage: "Request",
|
|
869
|
+
})),
|
|
870
|
+
});
|
|
871
|
+
} else if (before?.rules.length > 0) {
|
|
872
|
+
await this.send("Fetch.disable");
|
|
873
|
+
}
|
|
874
|
+
if (options.headers !== undefined || options.reset) {
|
|
875
|
+
await this.send("Network.setExtraHTTPHeaders", {
|
|
876
|
+
headers: state.headers,
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
const conditions = [
|
|
880
|
+
"offline",
|
|
881
|
+
"latencyMs",
|
|
882
|
+
"downloadKbps",
|
|
883
|
+
"uploadKbps",
|
|
884
|
+
"reset",
|
|
885
|
+
];
|
|
886
|
+
if (conditions.some((key) => options[key] !== undefined)) {
|
|
887
|
+
const throughput = (kbps) => (kbps ? (kbps * 1024) / 8 : -1);
|
|
888
|
+
await this.send("Network.emulateNetworkConditions", {
|
|
889
|
+
offline: state.offline,
|
|
890
|
+
latency: state.latencyMs ?? 0,
|
|
891
|
+
downloadThroughput: throughput(state.downloadKbps),
|
|
892
|
+
uploadThroughput: throughput(state.uploadKbps),
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
return {
|
|
896
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
897
|
+
...describeNetworkState(state),
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
async handleRequestPaused(params) {
|
|
902
|
+
const { requestId } = params;
|
|
903
|
+
const rule = takeMatchingRule(this.network, params.request?.url ?? "");
|
|
904
|
+
try {
|
|
905
|
+
if (!rule) {
|
|
906
|
+
await this.send("Fetch.continueRequest", { requestId });
|
|
907
|
+
} else if (rule.action === "block") {
|
|
908
|
+
await this.send("Fetch.failRequest", {
|
|
909
|
+
requestId,
|
|
910
|
+
errorReason: "BlockedByClient",
|
|
911
|
+
});
|
|
912
|
+
} else {
|
|
913
|
+
await this.send("Fetch.fulfillRequest", {
|
|
914
|
+
requestId,
|
|
915
|
+
responseCode: rule.status,
|
|
916
|
+
responseHeaders: mockHeaders(rule),
|
|
917
|
+
body: Buffer.from(rule.body).toString("base64"),
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
} catch {
|
|
921
|
+
// Release the request if it is still paused; it may also have gone
|
|
922
|
+
// away, for example because the page navigated.
|
|
923
|
+
await this.send("Fetch.continueRequest", { requestId }).catch(() => {});
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
535
927
|
autoDismissDialog(params) {
|
|
536
928
|
const accept = params.type !== "prompt";
|
|
537
929
|
this.send("Page.handleJavaScriptDialog", { accept }).catch(() => {});
|
|
538
930
|
}
|
|
539
931
|
|
|
540
932
|
pushEvent(event) {
|
|
933
|
+
this.inFlight.observe(event);
|
|
541
934
|
this.bufferedEvents.push(event);
|
|
542
935
|
if (this.bufferedEvents.length > this.eventBufferSize) {
|
|
543
936
|
this.bufferedEvents.shift();
|
|
@@ -611,13 +1004,18 @@ export class CdpSession {
|
|
|
611
1004
|
this.pending.clear();
|
|
612
1005
|
}
|
|
613
1006
|
|
|
614
|
-
send(method, params = {}) {
|
|
1007
|
+
send(method, params = {}, sessionId = null) {
|
|
615
1008
|
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
|
616
1009
|
throw new Error(`CDP session ${this.id} is not connected`);
|
|
617
1010
|
}
|
|
618
1011
|
|
|
619
1012
|
const id = this.nextMessageId++;
|
|
620
|
-
const payload = JSON.stringify({
|
|
1013
|
+
const payload = JSON.stringify({
|
|
1014
|
+
id,
|
|
1015
|
+
method,
|
|
1016
|
+
params,
|
|
1017
|
+
...(sessionId ? { sessionId } : {}),
|
|
1018
|
+
});
|
|
621
1019
|
|
|
622
1020
|
return new Promise((resolve, reject) => {
|
|
623
1021
|
this.pending.set(id, { resolve, reject });
|
|
@@ -711,6 +1109,15 @@ export class CdpSession {
|
|
|
711
1109
|
}
|
|
712
1110
|
|
|
713
1111
|
async runPageAction(payload, options = {}) {
|
|
1112
|
+
const route = parseFrameRef(payload.selector);
|
|
1113
|
+
if (route) {
|
|
1114
|
+
const result = await this.runInFrame(
|
|
1115
|
+
route.frameKey,
|
|
1116
|
+
{ ...payload, selector: route.selector },
|
|
1117
|
+
options,
|
|
1118
|
+
);
|
|
1119
|
+
return restoreFrameSelector(result, route, payload.selector);
|
|
1120
|
+
}
|
|
714
1121
|
const result = await this.evaluateRuntime(
|
|
715
1122
|
buildPageContextExpression(
|
|
716
1123
|
{
|
|
@@ -878,8 +1285,71 @@ export class CdpSession {
|
|
|
878
1285
|
};
|
|
879
1286
|
}
|
|
880
1287
|
|
|
1288
|
+
// Refs number on from the last snapshot, across navigations, so an old
|
|
1289
|
+
// ref never names an element on a later page.
|
|
1290
|
+
async runSnapshotAction(payload) {
|
|
1291
|
+
const result = await this.runPageAction({
|
|
1292
|
+
...payload,
|
|
1293
|
+
refStart: this.refStart ?? 1,
|
|
1294
|
+
});
|
|
1295
|
+
return takeNextRef(this, result);
|
|
1296
|
+
}
|
|
1297
|
+
|
|
881
1298
|
async snapshotControls() {
|
|
882
|
-
return this.
|
|
1299
|
+
return this.runSnapshotAction({ action: "controls_snapshot" });
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
// The top page's headings and controls, then each iframe's.
|
|
1303
|
+
async snapshotPage(options = {}) {
|
|
1304
|
+
const runInFrame = (key, payload, runOptions) =>
|
|
1305
|
+
this.runInFrame(key, payload, runOptions);
|
|
1306
|
+
const route = parseFrameRef(options.selector);
|
|
1307
|
+
if (route) {
|
|
1308
|
+
return frameElementSnapshot({
|
|
1309
|
+
route,
|
|
1310
|
+
frameKeys: this.frameKeys,
|
|
1311
|
+
runInFrame,
|
|
1312
|
+
options,
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
const result = await this.runSnapshotAction({
|
|
1316
|
+
action: "snapshot",
|
|
1317
|
+
...options,
|
|
1318
|
+
});
|
|
1319
|
+
if (options.selector) {
|
|
1320
|
+
return result;
|
|
1321
|
+
}
|
|
1322
|
+
return addFrameSnapshots({
|
|
1323
|
+
result,
|
|
1324
|
+
frames: await this.listFrames().catch(() => []),
|
|
1325
|
+
frameKeys: this.frameKeys,
|
|
1326
|
+
runInFrame,
|
|
1327
|
+
options,
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
async trackChanges(phase, options = {}) {
|
|
1332
|
+
const { frameKey, ...rest } = options;
|
|
1333
|
+
if (!frameKey) {
|
|
1334
|
+
return this.runSnapshotAction({ action: `change_${phase}`, ...rest });
|
|
1335
|
+
}
|
|
1336
|
+
// In a frame, refs number on from the frame's own last snapshot. A frame
|
|
1337
|
+
// that is gone ends tracking as a lost baseline does.
|
|
1338
|
+
const entry = this.frameKeys.get(frameKey);
|
|
1339
|
+
const result = entry
|
|
1340
|
+
? await this.runInFrame(
|
|
1341
|
+
frameKey,
|
|
1342
|
+
{ action: `change_${phase}`, ...rest, refStart: entry.refStart ?? 1 },
|
|
1343
|
+
{ offset: false },
|
|
1344
|
+
)
|
|
1345
|
+
: null;
|
|
1346
|
+
if (!result || result.error?.startsWith("Unknown frame")) {
|
|
1347
|
+
if (phase === "baseline") {
|
|
1348
|
+
throw new Error(`Unknown frame ${frameKey}`);
|
|
1349
|
+
}
|
|
1350
|
+
return { document: "same", lost: true };
|
|
1351
|
+
}
|
|
1352
|
+
return takeNextRef(entry, result);
|
|
883
1353
|
}
|
|
884
1354
|
|
|
885
1355
|
async readText(options = {}) {
|
|
@@ -894,15 +1364,61 @@ export class CdpSession {
|
|
|
894
1364
|
});
|
|
895
1365
|
}
|
|
896
1366
|
|
|
897
|
-
async resolvePointerTarget(selector) {
|
|
1367
|
+
async resolvePointerTarget(selector, options = {}) {
|
|
898
1368
|
const target = await this.runPageAction({
|
|
899
1369
|
action: "pointer_target",
|
|
900
1370
|
selector,
|
|
1371
|
+
...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
|
|
1372
|
+
...(options.scrollIntoView === false ? { scrollIntoView: false } : {}),
|
|
901
1373
|
});
|
|
902
1374
|
assertPointerTarget(target);
|
|
903
1375
|
return target;
|
|
904
1376
|
}
|
|
905
1377
|
|
|
1378
|
+
// A locator, scrolled into view unless scrollIntoView is false, or
|
|
1379
|
+
// viewport coordinates, which never scroll.
|
|
1380
|
+
async resolvePointer(target, options = {}) {
|
|
1381
|
+
if (typeof target === "string") {
|
|
1382
|
+
return this.resolvePointerTarget(target, options);
|
|
1383
|
+
}
|
|
1384
|
+
return this.runSnapshotAction({
|
|
1385
|
+
action: "point_target",
|
|
1386
|
+
x: target.x,
|
|
1387
|
+
y: target.y,
|
|
1388
|
+
...(options.inputProbe ? { inputProbe: options.inputProbe } : {}),
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
async readInputProbe(token, disarm, target = null) {
|
|
1393
|
+
try {
|
|
1394
|
+
const probe = await this.runPageAction({
|
|
1395
|
+
action: "input_probe",
|
|
1396
|
+
token,
|
|
1397
|
+
disarm,
|
|
1398
|
+
...probeScope(target),
|
|
1399
|
+
});
|
|
1400
|
+
return probe.armed ? probe : null;
|
|
1401
|
+
} catch {
|
|
1402
|
+
return null;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
// A double click is two presses, the second with clickCount 2, as the
|
|
1407
|
+
// browser reports them.
|
|
1408
|
+
async dispatchClick(point, options = {}) {
|
|
1409
|
+
const button = options.button ?? "left";
|
|
1410
|
+
const buttons = { left: 1, right: 2, middle: 4 }[button] ?? 1;
|
|
1411
|
+
await this.dispatchMouse("mouseMoved", point);
|
|
1412
|
+
for (let count = 1; count <= (options.clickCount ?? 1); count += 1) {
|
|
1413
|
+
const press = { button, clickCount: count };
|
|
1414
|
+
await this.dispatchMouse("mousePressed", point, { ...press, buttons });
|
|
1415
|
+
await this.dispatchMouse("mouseReleased", point, {
|
|
1416
|
+
...press,
|
|
1417
|
+
buttons: 0,
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
|
|
906
1422
|
async dispatchMouse(type, point, extra = {}) {
|
|
907
1423
|
await this.send("Input.dispatchMouseEvent", {
|
|
908
1424
|
type,
|
|
@@ -918,59 +1434,173 @@ export class CdpSession {
|
|
|
918
1434
|
}
|
|
919
1435
|
}
|
|
920
1436
|
|
|
921
|
-
async click(
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
1437
|
+
async click(target, options = {}) {
|
|
1438
|
+
const token = crypto.randomUUID();
|
|
1439
|
+
const resolved = await this.resolvePointer(target, { inputProbe: token });
|
|
1440
|
+
if (!resolved.found) {
|
|
1441
|
+
return resolved;
|
|
1442
|
+
}
|
|
1443
|
+
if (typeof target === "string") {
|
|
1444
|
+
assertEnabled(resolved);
|
|
925
1445
|
}
|
|
926
|
-
assertEnabled(target);
|
|
927
1446
|
|
|
928
|
-
const
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
});
|
|
934
|
-
await this.dispatchMouse("mouseReleased", target.point, {
|
|
935
|
-
...press,
|
|
936
|
-
buttons: 0,
|
|
1447
|
+
const delivery = await sendCheckedInput({
|
|
1448
|
+
send: () => this.dispatchClick(resolved.point, options),
|
|
1449
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, target),
|
|
1450
|
+
recover: () => this.bringToFront(),
|
|
1451
|
+
describe: `The click on ${describePointer(target)}`,
|
|
937
1452
|
});
|
|
938
1453
|
|
|
939
1454
|
return {
|
|
940
1455
|
browserFamily: cdpBrowserFamily(this.config),
|
|
941
|
-
selector,
|
|
942
1456
|
found: true,
|
|
943
1457
|
clicked: true,
|
|
944
|
-
|
|
945
|
-
node
|
|
1458
|
+
...(delivery.resent ? { resent: true } : {}),
|
|
1459
|
+
...pointerFields(target, resolved, delivery.node ?? resolved.node),
|
|
946
1460
|
};
|
|
947
1461
|
}
|
|
948
1462
|
|
|
949
|
-
|
|
950
|
-
|
|
1463
|
+
// Bringing the tab to the front makes Chrome render it again, which is
|
|
1464
|
+
// the one recovery tried before resending input the page never received.
|
|
1465
|
+
async bringToFront() {
|
|
1466
|
+
await this.send("Page.bringToFront").catch(() => {});
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
async hover(target) {
|
|
1470
|
+
const resolved = await this.resolvePointer(target);
|
|
1471
|
+
if (!resolved.found) {
|
|
1472
|
+
return resolved;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
await this.dispatchMouse("mouseMoved", resolved.point);
|
|
1476
|
+
|
|
1477
|
+
return {
|
|
1478
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
1479
|
+
found: true,
|
|
1480
|
+
hovered: true,
|
|
1481
|
+
...pointerFields(target, resolved),
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// Presses at from, moves through dragPath, and releases at to. Chrome
|
|
1486
|
+
// does not run an HTML5 drag (draggable elements, dataTransfer) from CDP
|
|
1487
|
+
// mouse input, so drags are intercepted: when the page starts one, Chrome
|
|
1488
|
+
// hands over its data and the drag finishes with drag events instead.
|
|
1489
|
+
async drag(from, to, options = {}) {
|
|
1490
|
+
const token = crypto.randomUUID();
|
|
1491
|
+
const source = await this.resolvePointer(from, { inputProbe: token });
|
|
1492
|
+
if (!source.found) {
|
|
1493
|
+
await this.readInputProbe(token, true, from);
|
|
1494
|
+
return source;
|
|
1495
|
+
}
|
|
1496
|
+
// The drop point is read without scrolling, so the source stays put.
|
|
1497
|
+
const target = await this.resolvePointer(to, { scrollIntoView: false });
|
|
951
1498
|
if (!target.found) {
|
|
1499
|
+
await this.readInputProbe(token, true, from);
|
|
952
1500
|
return target;
|
|
953
1501
|
}
|
|
954
1502
|
|
|
955
|
-
await this.
|
|
1503
|
+
await this.send("Input.setInterceptDrags", { enabled: true });
|
|
1504
|
+
let dragData = null;
|
|
1505
|
+
const intercepted = this.createEventWaiter(
|
|
1506
|
+
"Input.dragIntercepted",
|
|
1507
|
+
() => true,
|
|
1508
|
+
DRAG_SESSION_MS,
|
|
1509
|
+
);
|
|
1510
|
+
intercepted.promise.then(
|
|
1511
|
+
(params) => {
|
|
1512
|
+
dragData = params.data;
|
|
1513
|
+
},
|
|
1514
|
+
() => {},
|
|
1515
|
+
);
|
|
1516
|
+
const held = { button: "left", buttons: 1 };
|
|
1517
|
+
const release = { button: "left", buttons: 0, clickCount: 1 };
|
|
1518
|
+
let delivery;
|
|
1519
|
+
let released = false;
|
|
1520
|
+
try {
|
|
1521
|
+
delivery = await sendCheckedInput({
|
|
1522
|
+
send: async () => {
|
|
1523
|
+
await this.dispatchMouse("mouseMoved", source.point);
|
|
1524
|
+
await this.dispatchMouse("mousePressed", source.point, {
|
|
1525
|
+
...held,
|
|
1526
|
+
clickCount: 1,
|
|
1527
|
+
});
|
|
1528
|
+
},
|
|
1529
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, from),
|
|
1530
|
+
recover: () => this.bringToFront(),
|
|
1531
|
+
describe: `The press to drag ${describePointer(from)}`,
|
|
1532
|
+
});
|
|
1533
|
+
|
|
1534
|
+
const path = dragPath(source.point, target.point, options.steps);
|
|
1535
|
+
let index = 0;
|
|
1536
|
+
for (; index < path.length && !dragData; index += 1) {
|
|
1537
|
+
await this.dispatchMouse("mouseMoved", path[index], held);
|
|
1538
|
+
if (index === 0) {
|
|
1539
|
+
// A page starts an HTML5 drag on the first move past a few pixels.
|
|
1540
|
+
await Promise.race([intercepted.promise, sleep(DRAG_START_MS)]).catch(
|
|
1541
|
+
() => {},
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
if (dragData) {
|
|
1546
|
+
const rest = path.slice(index);
|
|
1547
|
+
const enter = rest[0] ?? target.point;
|
|
1548
|
+
await this.dispatchDrag("dragEnter", enter, dragData);
|
|
1549
|
+
for (const point of rest) {
|
|
1550
|
+
await this.dispatchDrag("dragOver", point, dragData);
|
|
1551
|
+
}
|
|
1552
|
+
await this.dispatchDrag("drop", target.point, dragData);
|
|
1553
|
+
}
|
|
1554
|
+
await this.dispatchMouse("mouseReleased", target.point, release);
|
|
1555
|
+
released = true;
|
|
1556
|
+
} finally {
|
|
1557
|
+
// A drag that failed partway must not leave the button down for the
|
|
1558
|
+
// next action.
|
|
1559
|
+
if (!released) {
|
|
1560
|
+
if (dragData) {
|
|
1561
|
+
await this.dispatchDrag("dragCancel", target.point, dragData).catch(
|
|
1562
|
+
() => {},
|
|
1563
|
+
);
|
|
1564
|
+
}
|
|
1565
|
+
await this.dispatchMouse("mouseReleased", target.point, release).catch(
|
|
1566
|
+
() => {},
|
|
1567
|
+
);
|
|
1568
|
+
}
|
|
1569
|
+
intercepted.cancel();
|
|
1570
|
+
await this.send("Input.setInterceptDrags", { enabled: false }).catch(
|
|
1571
|
+
() => {},
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
956
1574
|
|
|
957
1575
|
return {
|
|
958
1576
|
browserFamily: cdpBrowserFamily(this.config),
|
|
959
|
-
selector,
|
|
960
1577
|
found: true,
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1578
|
+
dragged: true,
|
|
1579
|
+
html5: Boolean(dragData),
|
|
1580
|
+
...(delivery.resent ? { resent: true } : {}),
|
|
1581
|
+
from: dragEnd(from, source),
|
|
1582
|
+
to: dragEnd(to, target),
|
|
964
1583
|
};
|
|
965
1584
|
}
|
|
966
1585
|
|
|
1586
|
+
async dispatchDrag(type, point, data) {
|
|
1587
|
+
await this.send("Input.dispatchDragEvent", {
|
|
1588
|
+
type,
|
|
1589
|
+
x: point.x,
|
|
1590
|
+
y: point.y,
|
|
1591
|
+
data,
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
|
|
967
1595
|
async type(selector, text, options = {}) {
|
|
1596
|
+
const token = crypto.randomUUID();
|
|
968
1597
|
const prepared = await this.runPageAction(
|
|
969
1598
|
{
|
|
970
1599
|
action: "prepare_type",
|
|
971
1600
|
selector,
|
|
972
1601
|
text,
|
|
973
1602
|
clear: options.clear,
|
|
1603
|
+
inputProbe: token,
|
|
974
1604
|
},
|
|
975
1605
|
{ userGesture: true },
|
|
976
1606
|
);
|
|
@@ -982,35 +1612,266 @@ export class CdpSession {
|
|
|
982
1612
|
// see trusted beforeinput/input events and the real value change.
|
|
983
1613
|
// Newlines become Enter presses, matching the Firefox path: a line break
|
|
984
1614
|
// in a textarea, implicit submission in a single-line input.
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1615
|
+
const sendText = async () => {
|
|
1616
|
+
if (text) {
|
|
1617
|
+
const lines = text.replace(/\r\n?/g, "\n").split("\n");
|
|
1618
|
+
for (const [index, line] of lines.entries()) {
|
|
1619
|
+
if (index > 0) {
|
|
1620
|
+
await this.dispatchKeyEvents(buildCdpKeyEvents("Enter"));
|
|
1621
|
+
}
|
|
1622
|
+
if (line) {
|
|
1623
|
+
await this.send("Input.insertText", { text: line });
|
|
1624
|
+
}
|
|
993
1625
|
}
|
|
1626
|
+
} else if (options.clear !== false) {
|
|
1627
|
+
await this.dispatchKeyEvents(buildCdpKeyEvents("Delete"));
|
|
994
1628
|
}
|
|
995
|
-
}
|
|
996
|
-
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
let delivery = { node: null, resent: false };
|
|
1632
|
+
if (text || options.clear !== false) {
|
|
1633
|
+
delivery = await sendCheckedInput({
|
|
1634
|
+
send: sendText,
|
|
1635
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
|
|
1636
|
+
recover: () => this.bringToFront(),
|
|
1637
|
+
describe: `The text for "${selector}"`,
|
|
1638
|
+
});
|
|
1639
|
+
} else {
|
|
1640
|
+
await this.readInputProbe(token, true, selector);
|
|
997
1641
|
}
|
|
998
1642
|
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1643
|
+
let node = delivery.node;
|
|
1644
|
+
if (!node) {
|
|
1645
|
+
const typed = await this.runPageAction({
|
|
1646
|
+
action: "inspect",
|
|
1647
|
+
selector,
|
|
1648
|
+
scrollIntoView: false,
|
|
1649
|
+
});
|
|
1650
|
+
node = typed.found ? typed.node : prepared.node;
|
|
1651
|
+
}
|
|
1004
1652
|
|
|
1005
1653
|
return {
|
|
1006
1654
|
browserFamily: cdpBrowserFamily(this.config),
|
|
1007
1655
|
selector,
|
|
1008
1656
|
found: true,
|
|
1009
1657
|
typedText: text,
|
|
1010
|
-
|
|
1658
|
+
...(delivery.resent ? { resent: true } : {}),
|
|
1659
|
+
node,
|
|
1011
1660
|
};
|
|
1012
1661
|
}
|
|
1013
1662
|
|
|
1663
|
+
// Sets files on a file input, or, for a button that opens a file chooser
|
|
1664
|
+
// from script, intercepts the chooser its click opens.
|
|
1665
|
+
async uploadFiles(selector, files) {
|
|
1666
|
+
const token = crypto.randomUUID();
|
|
1667
|
+
const target = await this.runPageAction({
|
|
1668
|
+
action: "file_input",
|
|
1669
|
+
selector,
|
|
1670
|
+
token,
|
|
1671
|
+
clear: files.length === 0,
|
|
1672
|
+
});
|
|
1673
|
+
if (!target.found) {
|
|
1674
|
+
return target;
|
|
1675
|
+
}
|
|
1676
|
+
const family = cdpBrowserFamily(this.config);
|
|
1677
|
+
if (target.cleared) {
|
|
1678
|
+
return uploadResult(family, selector, files);
|
|
1679
|
+
}
|
|
1680
|
+
if (target.fileInput) {
|
|
1681
|
+
// The input's handle and the files go to the session of the
|
|
1682
|
+
// document it is in, a frame's for a frame ref.
|
|
1683
|
+
const scope = this.frameScope(selector);
|
|
1684
|
+
const handle = await this.send(
|
|
1685
|
+
"Runtime.evaluate",
|
|
1686
|
+
{
|
|
1687
|
+
expression: takeFileTarget(token),
|
|
1688
|
+
returnByValue: false,
|
|
1689
|
+
...(scope.contextId !== undefined
|
|
1690
|
+
? { contextId: scope.contextId }
|
|
1691
|
+
: {}),
|
|
1692
|
+
},
|
|
1693
|
+
scope.sessionId,
|
|
1694
|
+
);
|
|
1695
|
+
const objectId = handle.result?.objectId;
|
|
1696
|
+
try {
|
|
1697
|
+
assertFileInput(target, files);
|
|
1698
|
+
await this.send(
|
|
1699
|
+
"DOM.setFileInputFiles",
|
|
1700
|
+
{ files, objectId },
|
|
1701
|
+
scope.sessionId,
|
|
1702
|
+
);
|
|
1703
|
+
} finally {
|
|
1704
|
+
this.send("Runtime.releaseObject", { objectId }, scope.sessionId).catch(
|
|
1705
|
+
() => {},
|
|
1706
|
+
);
|
|
1707
|
+
}
|
|
1708
|
+
return uploadResult(family, selector, files, {
|
|
1709
|
+
multiple: target.multiple,
|
|
1710
|
+
accept: target.accept,
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// One chooser at a time per tab, so a chooser goes to the upload whose
|
|
1715
|
+
// click opened it.
|
|
1716
|
+
const previous = this.chooserTurn ?? Promise.resolve();
|
|
1717
|
+
let finished;
|
|
1718
|
+
this.chooserTurn = new Promise((resolve) => {
|
|
1719
|
+
finished = resolve;
|
|
1720
|
+
});
|
|
1721
|
+
await previous;
|
|
1722
|
+
try {
|
|
1723
|
+
return await this.uploadThroughChooser(selector, files, family);
|
|
1724
|
+
} finally {
|
|
1725
|
+
finished();
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
// The chooser opens in the session of the document whose script opens it,
|
|
1730
|
+
// the button's frame or the top page, so both intercept it.
|
|
1731
|
+
async uploadThroughChooser(selector, files, family) {
|
|
1732
|
+
const sessions = Array.from(
|
|
1733
|
+
new Set([null, this.frameScope(selector).sessionId]),
|
|
1734
|
+
);
|
|
1735
|
+
for (const sessionId of sessions) {
|
|
1736
|
+
await this.send(
|
|
1737
|
+
"Page.setInterceptFileChooserDialog",
|
|
1738
|
+
{ enabled: true },
|
|
1739
|
+
sessionId,
|
|
1740
|
+
).catch(() => {});
|
|
1741
|
+
}
|
|
1742
|
+
const chooser = this.createEventWaiter(
|
|
1743
|
+
"Page.fileChooserOpened",
|
|
1744
|
+
() => true,
|
|
1745
|
+
FILE_CHOOSER_MS,
|
|
1746
|
+
);
|
|
1747
|
+
try {
|
|
1748
|
+
await this.click(selector);
|
|
1749
|
+
let opened;
|
|
1750
|
+
try {
|
|
1751
|
+
opened = await chooser.promise;
|
|
1752
|
+
} catch {
|
|
1753
|
+
throw new Error(
|
|
1754
|
+
`"${selector}" is not a file input, and clicking it opened no file chooser; pass the <input type="file">, which may be hidden`,
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
if (files.length > 1 && opened.mode !== "selectMultiple") {
|
|
1758
|
+
throw new Error(
|
|
1759
|
+
`The file chooser "${selector}" opened takes one file, not ${files.length}`,
|
|
1760
|
+
);
|
|
1761
|
+
}
|
|
1762
|
+
await this.send(
|
|
1763
|
+
"DOM.setFileInputFiles",
|
|
1764
|
+
{ files, backendNodeId: opened.backendNodeId },
|
|
1765
|
+
opened.sessionId ?? null,
|
|
1766
|
+
);
|
|
1767
|
+
} finally {
|
|
1768
|
+
chooser.cancel();
|
|
1769
|
+
for (const sessionId of sessions) {
|
|
1770
|
+
await this.send(
|
|
1771
|
+
"Page.setInterceptFileChooserDialog",
|
|
1772
|
+
{ enabled: false },
|
|
1773
|
+
sessionId,
|
|
1774
|
+
).catch(() => {});
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
return uploadResult(family, selector, files, { chooser: true });
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
// The page's report, with Chromium's own counters: heap, DOM nodes,
|
|
1781
|
+
// listeners, layouts and style recalculations, and script and task time.
|
|
1782
|
+
async getPerformance() {
|
|
1783
|
+
const report = await this.runPageAction({ action: "performance" });
|
|
1784
|
+
let metrics = null;
|
|
1785
|
+
try {
|
|
1786
|
+
if (!this.performanceEnabled) {
|
|
1787
|
+
await this.send("Performance.enable");
|
|
1788
|
+
this.performanceEnabled = true;
|
|
1789
|
+
}
|
|
1790
|
+
const values = Object.fromEntries(
|
|
1791
|
+
(await this.send("Performance.getMetrics")).metrics.map(
|
|
1792
|
+
({ name, value }) => [name, value],
|
|
1793
|
+
),
|
|
1794
|
+
);
|
|
1795
|
+
const ms = (seconds) =>
|
|
1796
|
+
seconds === undefined ? null : Math.round(seconds * 1000);
|
|
1797
|
+
metrics = {
|
|
1798
|
+
jsHeapUsedBytes: Math.round(values.JSHeapUsedSize ?? 0),
|
|
1799
|
+
jsHeapTotalBytes: Math.round(values.JSHeapTotalSize ?? 0),
|
|
1800
|
+
domNodes: values.Nodes ?? null,
|
|
1801
|
+
eventListeners: values.JSEventListeners ?? null,
|
|
1802
|
+
layouts: values.LayoutCount ?? null,
|
|
1803
|
+
styleRecalcs: values.RecalcStyleCount ?? null,
|
|
1804
|
+
layoutMs: ms(values.LayoutDuration),
|
|
1805
|
+
styleRecalcMs: ms(values.RecalcStyleDuration),
|
|
1806
|
+
scriptMs: ms(values.ScriptDuration),
|
|
1807
|
+
taskMs: ms(values.TaskDuration),
|
|
1808
|
+
};
|
|
1809
|
+
} catch {
|
|
1810
|
+
// The counters are extra; the page's report stands without them.
|
|
1811
|
+
}
|
|
1812
|
+
return { ...report, metrics };
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
async startTrace(options = {}) {
|
|
1816
|
+
if (this.tracing) {
|
|
1817
|
+
throw new Error("A trace is already recording; stop it first");
|
|
1818
|
+
}
|
|
1819
|
+
await this.send("Tracing.start", {
|
|
1820
|
+
transferMode: "ReturnAsStream",
|
|
1821
|
+
traceConfig: {
|
|
1822
|
+
recordMode: "recordUntilFull",
|
|
1823
|
+
includedCategories: [
|
|
1824
|
+
...TRACE_CATEGORIES,
|
|
1825
|
+
...(options.screenshots
|
|
1826
|
+
? ["disabled-by-default-devtools.screenshot"]
|
|
1827
|
+
: []),
|
|
1828
|
+
],
|
|
1829
|
+
},
|
|
1830
|
+
});
|
|
1831
|
+
this.tracing = { startedAt: Date.now() };
|
|
1832
|
+
return { browserFamily: cdpBrowserFamily(this.config), recording: true };
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
// Ends the trace and reads it from the stream Chrome hands back.
|
|
1836
|
+
async stopTrace() {
|
|
1837
|
+
if (!this.tracing) {
|
|
1838
|
+
throw new Error("No trace is recording; start one first");
|
|
1839
|
+
}
|
|
1840
|
+
const { startedAt } = this.tracing;
|
|
1841
|
+
const complete = this.createEventWaiter(
|
|
1842
|
+
"Tracing.tracingComplete",
|
|
1843
|
+
() => true,
|
|
1844
|
+
TRACE_COMPLETE_MS,
|
|
1845
|
+
);
|
|
1846
|
+
try {
|
|
1847
|
+
await this.send("Tracing.end");
|
|
1848
|
+
} catch (error) {
|
|
1849
|
+
// Chrome is still recording; a later stop can end it.
|
|
1850
|
+
complete.cancel();
|
|
1851
|
+
throw error;
|
|
1852
|
+
}
|
|
1853
|
+
this.tracing = null;
|
|
1854
|
+
const { stream } = await complete.promise;
|
|
1855
|
+
const chunks = [];
|
|
1856
|
+
try {
|
|
1857
|
+
while (true) {
|
|
1858
|
+
const chunk = await this.send("IO.read", {
|
|
1859
|
+
handle: stream,
|
|
1860
|
+
size: 1 << 20,
|
|
1861
|
+
});
|
|
1862
|
+
chunks.push(
|
|
1863
|
+
Buffer.from(chunk.data, chunk.base64Encoded ? "base64" : "utf8"),
|
|
1864
|
+
);
|
|
1865
|
+
if (chunk.eof) {
|
|
1866
|
+
break;
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
} finally {
|
|
1870
|
+
await this.send("IO.close", { handle: stream }).catch(() => {});
|
|
1871
|
+
}
|
|
1872
|
+
return { data: Buffer.concat(chunks), durationMs: Date.now() - startedAt };
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1014
1875
|
async select(selector, options = {}) {
|
|
1015
1876
|
return this.runPageAction(
|
|
1016
1877
|
{
|
|
@@ -1025,10 +1886,12 @@ export class CdpSession {
|
|
|
1025
1886
|
|
|
1026
1887
|
async pressKey(key, selector = null) {
|
|
1027
1888
|
const events = buildCdpKeyEvents(key);
|
|
1889
|
+
const token = crypto.randomUUID();
|
|
1028
1890
|
const focused = await this.runPageAction(
|
|
1029
1891
|
{
|
|
1030
1892
|
action: "focus",
|
|
1031
1893
|
selector,
|
|
1894
|
+
inputProbe: token,
|
|
1032
1895
|
},
|
|
1033
1896
|
{ userGesture: true },
|
|
1034
1897
|
);
|
|
@@ -1036,17 +1899,45 @@ export class CdpSession {
|
|
|
1036
1899
|
return focused;
|
|
1037
1900
|
}
|
|
1038
1901
|
|
|
1039
|
-
await
|
|
1902
|
+
const delivery = await sendCheckedInput({
|
|
1903
|
+
send: () => this.dispatchKeyEvents(events),
|
|
1904
|
+
readProbe: (disarm) => this.readInputProbe(token, disarm, selector),
|
|
1905
|
+
recover: () => this.bringToFront(),
|
|
1906
|
+
describe: `The key press "${key}"`,
|
|
1907
|
+
});
|
|
1040
1908
|
|
|
1041
1909
|
return {
|
|
1042
1910
|
browserFamily: cdpBrowserFamily(this.config),
|
|
1043
1911
|
key,
|
|
1044
1912
|
dispatched: true,
|
|
1913
|
+
...(delivery.resent ? { resent: true } : {}),
|
|
1045
1914
|
target: focused.target,
|
|
1046
1915
|
};
|
|
1047
1916
|
}
|
|
1048
1917
|
|
|
1918
|
+
// A selector alone scrolls its element into view and deltas alone scroll
|
|
1919
|
+
// the page. Coordinates, or a selector with deltas, send a real mouse
|
|
1920
|
+
// wheel there, which scrolls whatever is under the pointer, such as a list
|
|
1921
|
+
// inside the page.
|
|
1049
1922
|
async scroll(options = {}) {
|
|
1923
|
+
if (wheelScroll(options)) {
|
|
1924
|
+
const target = options.selector ?? { x: options.x, y: options.y };
|
|
1925
|
+
const resolved = await this.resolvePointer(target);
|
|
1926
|
+
if (!resolved.found) {
|
|
1927
|
+
return resolved;
|
|
1928
|
+
}
|
|
1929
|
+
await this.dispatchMouse("mouseWheel", resolved.point, {
|
|
1930
|
+
deltaX: options.deltaX ?? 0,
|
|
1931
|
+
deltaY: options.deltaY ?? 0,
|
|
1932
|
+
});
|
|
1933
|
+
return {
|
|
1934
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
1935
|
+
found: true,
|
|
1936
|
+
scrolled: true,
|
|
1937
|
+
wheel: { deltaX: options.deltaX ?? 0, deltaY: options.deltaY ?? 0 },
|
|
1938
|
+
...pointerFields(target, resolved),
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1050
1941
|
return this.runPageAction(
|
|
1051
1942
|
{
|
|
1052
1943
|
action: "scroll",
|
|
@@ -1153,6 +2044,31 @@ export class CdpSession {
|
|
|
1153
2044
|
};
|
|
1154
2045
|
}
|
|
1155
2046
|
|
|
2047
|
+
// Counts trusted input from the start of every later document, and from
|
|
2048
|
+
// now on in the current one, so input actions can check that their input
|
|
2049
|
+
// arrived. Without it they are reported as sent, unchecked.
|
|
2050
|
+
// A cross-site iframe's target gets the recorder too, by its session.
|
|
2051
|
+
async installInputRecorder(sessionId = null) {
|
|
2052
|
+
try {
|
|
2053
|
+
await this.send(
|
|
2054
|
+
"Page.addScriptToEvaluateOnNewDocument",
|
|
2055
|
+
{ source: buildInputRecorderExpression(true) },
|
|
2056
|
+
sessionId,
|
|
2057
|
+
);
|
|
2058
|
+
await this.send(
|
|
2059
|
+
"Runtime.evaluate",
|
|
2060
|
+
{
|
|
2061
|
+
expression: buildInputRecorderExpression(false),
|
|
2062
|
+
awaitPromise: false,
|
|
2063
|
+
returnByValue: true,
|
|
2064
|
+
},
|
|
2065
|
+
sessionId,
|
|
2066
|
+
);
|
|
2067
|
+
} catch {
|
|
2068
|
+
// Ignore recorder failures so attach still succeeds.
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
|
|
1156
2072
|
async seedBufferedState() {
|
|
1157
2073
|
try {
|
|
1158
2074
|
const snapshot = await this.runPageAction({
|
|
@@ -1183,6 +2099,10 @@ export class CdpSession {
|
|
|
1183
2099
|
return this.bufferedEvents.slice(-safeLimit);
|
|
1184
2100
|
}
|
|
1185
2101
|
|
|
2102
|
+
pendingRequests() {
|
|
2103
|
+
return this.inFlight.list();
|
|
2104
|
+
}
|
|
2105
|
+
|
|
1186
2106
|
getSummary() {
|
|
1187
2107
|
return {
|
|
1188
2108
|
sessionId: this.id,
|
|
@@ -1583,12 +2503,36 @@ export class CdpSessionManager {
|
|
|
1583
2503
|
return this.getSession(sessionId).reload(options);
|
|
1584
2504
|
}
|
|
1585
2505
|
|
|
1586
|
-
async click(sessionId,
|
|
1587
|
-
return this.getSession(sessionId).click(
|
|
2506
|
+
async click(sessionId, target, options) {
|
|
2507
|
+
return this.getSession(sessionId).click(target, options);
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
async hover(sessionId, target) {
|
|
2511
|
+
return this.getSession(sessionId).hover(target);
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
async drag(sessionId, from, to, options) {
|
|
2515
|
+
return this.getSession(sessionId).drag(from, to, options);
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
async uploadFiles(sessionId, selector, files) {
|
|
2519
|
+
return this.getSession(sessionId).uploadFiles(selector, files);
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
async setNetwork(sessionId, options) {
|
|
2523
|
+
return this.getSession(sessionId).setNetwork(options);
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
async getPerformance(sessionId) {
|
|
2527
|
+
return this.getSession(sessionId).getPerformance();
|
|
1588
2528
|
}
|
|
1589
2529
|
|
|
1590
|
-
async
|
|
1591
|
-
return this.getSession(sessionId).
|
|
2530
|
+
async startTrace(sessionId, options) {
|
|
2531
|
+
return this.getSession(sessionId).startTrace(options);
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
async stopTrace(sessionId) {
|
|
2535
|
+
return this.getSession(sessionId).stopTrace();
|
|
1592
2536
|
}
|
|
1593
2537
|
|
|
1594
2538
|
async type(sessionId, selector, text, options) {
|
|
@@ -1655,10 +2599,22 @@ export class CdpSessionManager {
|
|
|
1655
2599
|
return this.getSession(sessionId).snapshotControls();
|
|
1656
2600
|
}
|
|
1657
2601
|
|
|
2602
|
+
async snapshotPage(sessionId, options) {
|
|
2603
|
+
return this.getSession(sessionId).snapshotPage(options);
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
async trackChanges(sessionId, phase, options) {
|
|
2607
|
+
return this.getSession(sessionId).trackChanges(phase, options);
|
|
2608
|
+
}
|
|
2609
|
+
|
|
1658
2610
|
async inspectElement(sessionId, selector, options) {
|
|
1659
2611
|
return this.getSession(sessionId).inspectElement(selector, options);
|
|
1660
2612
|
}
|
|
1661
2613
|
|
|
2614
|
+
pendingRequests(sessionId) {
|
|
2615
|
+
return this.getSession(sessionId).pendingRequests();
|
|
2616
|
+
}
|
|
2617
|
+
|
|
1662
2618
|
getEvents(sessionId, limit) {
|
|
1663
2619
|
return this.getSession(sessionId).getEvents(limit);
|
|
1664
2620
|
}
|