-
Notifications
You must be signed in to change notification settings - Fork 9k
/
FrameManager.ts
1540 lines (1440 loc) · 43.7 KB
/
FrameManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Protocol} from 'devtools-protocol';
import {assert} from './assert.js';
import {CDPSession} from './Connection.js';
import {IsolatedWorld, WaitForSelectorOptions} from './IsolatedWorld.js';
import {ElementHandle} from './ElementHandle.js';
import {EventEmitter} from './EventEmitter.js';
import {EVALUATION_SCRIPT_URL, ExecutionContext} from './ExecutionContext.js';
import {HTTPResponse} from './HTTPResponse.js';
import {MouseButton} from './Input.js';
import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
import {NetworkManager} from './NetworkManager.js';
import {Page} from './Page.js';
import {Target} from './Target.js';
import {TimeoutSettings} from './TimeoutSettings.js';
import {EvaluateFunc, HandleFor, NodeFor} from './types.js';
import {
createDeferredPromiseWithTimer,
debugError,
DeferredPromise,
isErrorLike,
} from './util.js';
const UTILITY_WORLD_NAME = '__puppeteer_utility_world__';
/**
* We use symbols to prevent external parties listening to these events.
* They are internal to Puppeteer.
*
* @internal
*/
export const FrameManagerEmittedEvents = {
FrameAttached: Symbol('FrameManager.FrameAttached'),
FrameNavigated: Symbol('FrameManager.FrameNavigated'),
FrameDetached: Symbol('FrameManager.FrameDetached'),
FrameSwapped: Symbol('FrameManager.FrameSwapped'),
LifecycleEvent: Symbol('FrameManager.LifecycleEvent'),
FrameNavigatedWithinDocument: Symbol(
'FrameManager.FrameNavigatedWithinDocument'
),
ExecutionContextCreated: Symbol('FrameManager.ExecutionContextCreated'),
ExecutionContextDestroyed: Symbol('FrameManager.ExecutionContextDestroyed'),
};
/**
* @internal
*/
export class FrameManager extends EventEmitter {
#page: Page;
#networkManager: NetworkManager;
#timeoutSettings: TimeoutSettings;
#frames = new Map<string, Frame>();
#contextIdToContext = new Map<string, ExecutionContext>();
#isolatedWorlds = new Set<string>();
#mainFrame?: Frame;
#client: CDPSession;
/**
* Keeps track of OOPIF targets/frames (target ID == frame ID for OOPIFs)
* that are being initialized.
*/
#framesPendingTargetInit = new Map<string, DeferredPromise<void>>();
/**
* Keeps track of frames that are in the process of being attached in #onFrameAttached.
*/
#framesPendingAttachment = new Map<string, DeferredPromise<void>>();
/**
* @internal
*/
get _timeoutSettings(): TimeoutSettings {
return this.#timeoutSettings;
}
/**
* @internal
*/
get _client(): CDPSession {
return this.#client;
}
constructor(
client: CDPSession,
page: Page,
ignoreHTTPSErrors: boolean,
timeoutSettings: TimeoutSettings
) {
super();
this.#client = client;
this.#page = page;
this.#networkManager = new NetworkManager(client, ignoreHTTPSErrors, this);
this.#timeoutSettings = timeoutSettings;
this.setupEventListeners(this.#client);
}
private setupEventListeners(session: CDPSession) {
session.on('Page.frameAttached', event => {
this.#onFrameAttached(session, event.frameId, event.parentFrameId);
});
session.on('Page.frameNavigated', event => {
this.#onFrameNavigated(event.frame);
});
session.on('Page.navigatedWithinDocument', event => {
this.#onFrameNavigatedWithinDocument(event.frameId, event.url);
});
session.on(
'Page.frameDetached',
(event: Protocol.Page.FrameDetachedEvent) => {
this.#onFrameDetached(
event.frameId,
event.reason as Protocol.Page.FrameDetachedEventReason
);
}
);
session.on('Page.frameStartedLoading', event => {
this.#onFrameStartedLoading(event.frameId);
});
session.on('Page.frameStoppedLoading', event => {
this.#onFrameStoppedLoading(event.frameId);
});
session.on('Runtime.executionContextCreated', event => {
this.#onExecutionContextCreated(event.context, session);
});
session.on('Runtime.executionContextDestroyed', event => {
this.#onExecutionContextDestroyed(event.executionContextId, session);
});
session.on('Runtime.executionContextsCleared', () => {
this.#onExecutionContextsCleared(session);
});
session.on('Page.lifecycleEvent', event => {
this.#onLifecycleEvent(event);
});
}
async initialize(
targetId: string,
client: CDPSession = this.#client
): Promise<void> {
try {
if (!this.#framesPendingTargetInit.has(targetId)) {
this.#framesPendingTargetInit.set(
targetId,
createDeferredPromiseWithTimer(
`Waiting for target frame ${targetId} failed`
)
);
}
const result = await Promise.all([
client.send('Page.enable'),
client.send('Page.getFrameTree'),
]);
const {frameTree} = result[1];
this.#handleFrameTree(client, frameTree);
await Promise.all([
client.send('Page.setLifecycleEventsEnabled', {enabled: true}),
client.send('Runtime.enable').then(() => {
return this._ensureIsolatedWorld(client, UTILITY_WORLD_NAME);
}),
// TODO: Network manager is not aware of OOP iframes yet.
client === this.#client
? this.#networkManager.initialize()
: Promise.resolve(),
]);
} catch (error) {
// The target might have been closed before the initialization finished.
if (
isErrorLike(error) &&
(error.message.includes('Target closed') ||
error.message.includes('Session closed'))
) {
return;
}
throw error;
} finally {
this.#framesPendingTargetInit.get(targetId)?.resolve();
this.#framesPendingTargetInit.delete(targetId);
}
}
networkManager(): NetworkManager {
return this.#networkManager;
}
async navigateFrame(
frame: Frame,
url: string,
options: {
referer?: string;
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
} = {}
): Promise<HTTPResponse | null> {
assertNoLegacyNavigationOptions(options);
const {
referer = this.#networkManager.extraHTTPHeaders()['referer'],
waitUntil = ['load'],
timeout = this.#timeoutSettings.navigationTimeout(),
} = options;
let ensureNewDocumentNavigation = false;
const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);
let error = await Promise.race([
navigate(this.#client, url, referer, frame._id),
watcher.timeoutOrTerminationPromise(),
]);
if (!error) {
error = await Promise.race([
watcher.timeoutOrTerminationPromise(),
ensureNewDocumentNavigation
? watcher.newDocumentNavigationPromise()
: watcher.sameDocumentNavigationPromise(),
]);
}
try {
if (error) {
throw error;
}
return await watcher.navigationResponse();
} finally {
watcher.dispose();
}
async function navigate(
client: CDPSession,
url: string,
referrer: string | undefined,
frameId: string
): Promise<Error | null> {
try {
const response = await client.send('Page.navigate', {
url,
referrer,
frameId,
});
ensureNewDocumentNavigation = !!response.loaderId;
return response.errorText
? new Error(`${response.errorText} at ${url}`)
: null;
} catch (error) {
if (isErrorLike(error)) {
return error;
}
throw error;
}
}
}
async waitForFrameNavigation(
frame: Frame,
options: {
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
} = {}
): Promise<HTTPResponse | null> {
assertNoLegacyNavigationOptions(options);
const {
waitUntil = ['load'],
timeout = this.#timeoutSettings.navigationTimeout(),
} = options;
const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);
const error = await Promise.race([
watcher.timeoutOrTerminationPromise(),
watcher.sameDocumentNavigationPromise(),
watcher.newDocumentNavigationPromise(),
]);
try {
if (error) {
throw error;
}
return await watcher.navigationResponse();
} finally {
watcher.dispose();
}
}
async onAttachedToTarget(target: Target): Promise<void> {
if (target._getTargetInfo().type !== 'iframe') {
return;
}
const frame = this.#frames.get(target._getTargetInfo().targetId);
if (frame) {
frame._updateClient(target._session()!);
}
this.setupEventListeners(target._session()!);
this.initialize(target._getTargetInfo().targetId, target._session());
}
async onDetachedFromTarget(target: Target): Promise<void> {
const frame = this.#frames.get(target._targetId);
if (frame && frame.isOOPFrame()) {
// When an OOP iframe is removed from the page, it
// will only get a Target.detachedFromTarget event.
this.#removeFramesRecursively(frame);
}
}
#onLifecycleEvent(event: Protocol.Page.LifecycleEventEvent): void {
const frame = this.#frames.get(event.frameId);
if (!frame) {
return;
}
frame._onLifecycleEvent(event.loaderId, event.name);
this.emit(FrameManagerEmittedEvents.LifecycleEvent, frame);
}
#onFrameStartedLoading(frameId: string): void {
const frame = this.#frames.get(frameId);
if (!frame) {
return;
}
frame._onLoadingStarted();
}
#onFrameStoppedLoading(frameId: string): void {
const frame = this.#frames.get(frameId);
if (!frame) {
return;
}
frame._onLoadingStopped();
this.emit(FrameManagerEmittedEvents.LifecycleEvent, frame);
}
#handleFrameTree(
session: CDPSession,
frameTree: Protocol.Page.FrameTree
): void {
if (frameTree.frame.parentId) {
this.#onFrameAttached(
session,
frameTree.frame.id,
frameTree.frame.parentId
);
}
this.#onFrameNavigated(frameTree.frame);
if (!frameTree.childFrames) {
return;
}
for (const child of frameTree.childFrames) {
this.#handleFrameTree(session, child);
}
}
page(): Page {
return this.#page;
}
mainFrame(): Frame {
assert(this.#mainFrame, 'Requesting main frame too early!');
return this.#mainFrame;
}
frames(): Frame[] {
return Array.from(this.#frames.values());
}
frame(frameId: string): Frame | null {
return this.#frames.get(frameId) || null;
}
#onFrameAttached(
session: CDPSession,
frameId: string,
parentFrameId: string
): void {
if (this.#frames.has(frameId)) {
const frame = this.#frames.get(frameId)!;
if (session && frame.isOOPFrame()) {
// If an OOP iframes becomes a normal iframe again
// it is first attached to the parent page before
// the target is removed.
frame._updateClient(session);
}
return;
}
const parentFrame = this.#frames.get(parentFrameId);
const complete = (parentFrame: Frame) => {
assert(parentFrame, `Parent frame ${parentFrameId} not found`);
const frame = new Frame(this, parentFrame, frameId, session);
this.#frames.set(frame._id, frame);
this.emit(FrameManagerEmittedEvents.FrameAttached, frame);
};
if (parentFrame) {
return complete(parentFrame);
}
const frame = this.#framesPendingTargetInit.get(parentFrameId);
if (frame) {
if (!this.#framesPendingAttachment.has(frameId)) {
this.#framesPendingAttachment.set(
frameId,
createDeferredPromiseWithTimer(
`Waiting for frame ${frameId} to attach failed`
)
);
}
frame.then(() => {
complete(this.#frames.get(parentFrameId)!);
this.#framesPendingAttachment.get(frameId)?.resolve();
this.#framesPendingAttachment.delete(frameId);
});
return;
}
throw new Error(`Parent frame ${parentFrameId} not found`);
}
#onFrameNavigated(framePayload: Protocol.Page.Frame): void {
const frameId = framePayload.id;
const isMainFrame = !framePayload.parentId;
const frame = isMainFrame ? this.#mainFrame : this.#frames.get(frameId);
const complete = (frame?: Frame) => {
assert(
isMainFrame || frame,
`Missing frame isMainFrame=${isMainFrame}, frameId=${frameId}`
);
// Detach all child frames first.
if (frame) {
for (const child of frame.childFrames()) {
this.#removeFramesRecursively(child);
}
}
// Update or create main frame.
if (isMainFrame) {
if (frame) {
// Update frame id to retain frame identity on cross-process navigation.
this.#frames.delete(frame._id);
frame._id = frameId;
} else {
// Initial main frame navigation.
frame = new Frame(this, null, frameId, this.#client);
}
this.#frames.set(frameId, frame);
this.#mainFrame = frame;
}
// Update frame payload.
assert(frame);
frame._navigated(framePayload);
this.emit(FrameManagerEmittedEvents.FrameNavigated, frame);
};
const pendingFrame = this.#framesPendingAttachment.get(frameId);
if (pendingFrame) {
pendingFrame.then(() => {
complete(isMainFrame ? this.#mainFrame : this.#frames.get(frameId));
});
} else {
complete(frame);
}
}
async _ensureIsolatedWorld(session: CDPSession, name: string): Promise<void> {
const key = `${session.id()}:${name}`;
if (this.#isolatedWorlds.has(key)) {
return;
}
this.#isolatedWorlds.add(key);
await session.send('Page.addScriptToEvaluateOnNewDocument', {
source: `//# sourceURL=${EVALUATION_SCRIPT_URL}`,
worldName: name,
});
// Frames might be removed before we send this.
await Promise.all(
this.frames()
.filter(frame => {
return frame._client() === session;
})
.map(frame => {
return session
.send('Page.createIsolatedWorld', {
frameId: frame._id,
worldName: name,
grantUniveralAccess: true,
})
.catch(debugError);
})
);
}
#onFrameNavigatedWithinDocument(frameId: string, url: string): void {
const frame = this.#frames.get(frameId);
if (!frame) {
return;
}
frame._navigatedWithinDocument(url);
this.emit(FrameManagerEmittedEvents.FrameNavigatedWithinDocument, frame);
this.emit(FrameManagerEmittedEvents.FrameNavigated, frame);
}
#onFrameDetached(
frameId: string,
reason: Protocol.Page.FrameDetachedEventReason
): void {
const frame = this.#frames.get(frameId);
if (reason === 'remove') {
// Only remove the frame if the reason for the detached event is
// an actual removement of the frame.
// For frames that become OOP iframes, the reason would be 'swap'.
if (frame) {
this.#removeFramesRecursively(frame);
}
} else if (reason === 'swap') {
this.emit(FrameManagerEmittedEvents.FrameSwapped, frame);
}
}
#onExecutionContextCreated(
contextPayload: Protocol.Runtime.ExecutionContextDescription,
session: CDPSession
): void {
const auxData = contextPayload.auxData as {frameId?: string} | undefined;
const frameId = auxData && auxData.frameId;
const frame =
typeof frameId === 'string' ? this.#frames.get(frameId) : undefined;
let world: IsolatedWorld | undefined;
if (frame) {
// Only care about execution contexts created for the current session.
if (frame._client() !== session) {
return;
}
if (contextPayload.auxData && !!contextPayload.auxData['isDefault']) {
world = frame._mainWorld;
} else if (
contextPayload.name === UTILITY_WORLD_NAME &&
!frame._secondaryWorld.hasContext()
) {
// In case of multiple sessions to the same target, there's a race between
// connections so we might end up creating multiple isolated worlds.
// We can use either.
world = frame._secondaryWorld;
}
}
const context = new ExecutionContext(
frame?._client() || this.#client,
contextPayload,
world
);
if (world) {
world.setContext(context);
}
const key = `${session.id()}:${contextPayload.id}`;
this.#contextIdToContext.set(key, context);
}
#onExecutionContextDestroyed(
executionContextId: number,
session: CDPSession
): void {
const key = `${session.id()}:${executionContextId}`;
const context = this.#contextIdToContext.get(key);
if (!context) {
return;
}
this.#contextIdToContext.delete(key);
if (context._world) {
context._world.clearContext();
}
}
#onExecutionContextsCleared(session: CDPSession): void {
for (const [key, context] of this.#contextIdToContext.entries()) {
// Make sure to only clear execution contexts that belong
// to the current session.
if (context._client !== session) {
continue;
}
if (context._world) {
context._world.clearContext();
}
this.#contextIdToContext.delete(key);
}
}
executionContextById(
contextId: number,
session: CDPSession = this.#client
): ExecutionContext {
const key = `${session.id()}:${contextId}`;
const context = this.#contextIdToContext.get(key);
assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId);
return context;
}
#removeFramesRecursively(frame: Frame): void {
for (const child of frame.childFrames()) {
this.#removeFramesRecursively(child);
}
frame._detach();
this.#frames.delete(frame._id);
this.emit(FrameManagerEmittedEvents.FrameDetached, frame);
}
}
/**
* @public
*/
export interface FrameWaitForFunctionOptions {
/**
* An interval at which the `pageFunction` is executed, defaults to `raf`. If
* `polling` is a number, then it is treated as an interval in milliseconds at
* which the function would be executed. If `polling` is a string, then it can
* be one of the following values:
*
* - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame`
* callback. This is the tightest polling mode which is suitable to observe
* styling changes.
*
* - `mutation` - to execute `pageFunction` on every DOM mutation.
*/
polling?: string | number;
/**
* Maximum time to wait in milliseconds. Defaults to `30000` (30 seconds).
* Pass `0` to disable the timeout. Puppeteer's default timeout can be changed
* using {@link Page.setDefaultTimeout}.
*/
timeout?: number;
}
/**
* @public
*/
export interface FrameAddScriptTagOptions {
/**
* the URL of the script to be added.
*/
url?: string;
/**
* The path to a JavaScript file to be injected into the frame.
* @remarks
* If `path` is a relative path, it is resolved relative to the current
* working directory (`process.cwd()` in Node.js).
*/
path?: string;
/**
* Raw JavaScript content to be injected into the frame.
*/
content?: string;
/**
* Set the script's `type`. Use `module` in order to load an ES2015 module.
*/
type?: string;
}
/**
* @public
*/
export interface FrameAddStyleTagOptions {
/**
* the URL of the CSS file to be added.
*/
url?: string;
/**
* The path to a CSS file to be injected into the frame.
* @remarks
* If `path` is a relative path, it is resolved relative to the current
* working directory (`process.cwd()` in Node.js).
*/
path?: string;
/**
* Raw CSS content to be injected into the frame.
*/
content?: string;
}
/**
* At every point of time, page exposes its current frame tree via the
* {@link Page.mainFrame | page.mainFrame} and
* {@link Frame.childFrames | frame.childFrames} methods.
*
* @remarks
*
* `Frame` object lifecycles are controlled by three events that are all
* dispatched on the page object:
*
* - {@link PageEmittedEvents.FrameAttached}
*
* - {@link PageEmittedEvents.FrameNavigated}
*
* - {@link PageEmittedEvents.FrameDetached}
*
* @Example
* An example of dumping frame tree:
*
* ```ts
* const puppeteer = require('puppeteer');
*
* (async () => {
* const browser = await puppeteer.launch();
* const page = await browser.newPage();
* await page.goto('https://www.google.com/chrome/browser/canary.html');
* dumpFrameTree(page.mainFrame(), '');
* await browser.close();
*
* function dumpFrameTree(frame, indent) {
* console.log(indent + frame.url());
* for (const child of frame.childFrames()) {
* dumpFrameTree(child, indent + ' ');
* }
* }
* })();
* ```
*
* @Example
* An example of getting text from an iframe element:
*
* ```ts
* const frame = page.frames().find(frame => frame.name() === 'myframe');
* const text = await frame.$eval('.selector', element => element.textContent);
* console.log(text);
* ```
*
* @public
*/
export class Frame {
#parentFrame: Frame | null;
#url = '';
#detached = false;
#client!: CDPSession;
/**
* @internal
*/
_frameManager: FrameManager;
/**
* @internal
*/
_id: string;
/**
* @internal
*/
_loaderId = '';
/**
* @internal
*/
_name?: string;
/**
* @internal
*/
_hasStartedLoading = false;
/**
* @internal
*/
_lifecycleEvents = new Set<string>();
/**
* @internal
*/
_mainWorld!: IsolatedWorld;
/**
* @internal
*/
_secondaryWorld!: IsolatedWorld;
/**
* @internal
*/
_childFrames: Set<Frame>;
/**
* @internal
*/
constructor(
frameManager: FrameManager,
parentFrame: Frame | null,
frameId: string,
client: CDPSession
) {
this._frameManager = frameManager;
this.#parentFrame = parentFrame ?? null;
this.#url = '';
this._id = frameId;
this.#detached = false;
this._loaderId = '';
this._childFrames = new Set();
if (this.#parentFrame) {
this.#parentFrame._childFrames.add(this);
}
this._updateClient(client);
}
/**
* @internal
*/
_updateClient(client: CDPSession): void {
this.#client = client;
this._mainWorld = new IsolatedWorld(
this.#client,
this._frameManager,
this,
this._frameManager._timeoutSettings
);
this._secondaryWorld = new IsolatedWorld(
this.#client,
this._frameManager,
this,
this._frameManager._timeoutSettings
);
}
/**
* @returns a page associated with the frame.
*/
page(): Page {
return this._frameManager.page();
}
/**
* @remarks
*
* @returns `true` if the frame is an OOP frame, or `false` otherwise.
*/
isOOPFrame(): boolean {
return this.#client !== this._frameManager._client;
}
/**
* @remarks
*
* `frame.goto` will throw an error if:
* - there's an SSL error (e.g. in case of self-signed certificates).
*
* - target URL is invalid.
*
* - the `timeout` is exceeded during navigation.
*
* - the remote server does not respond or is unreachable.
*
* - the main resource failed to load.
*
* `frame.goto` will not throw an error when any valid HTTP status code is
* returned by the remote server, including 404 "Not Found" and 500 "Internal
* Server Error". The status code for such responses can be retrieved by
* calling {@link HTTPResponse.status}.
*
* NOTE: `frame.goto` either throws an error or returns a main resource
* response. The only exceptions are navigation to `about:blank` or
* navigation to the same URL with a different hash, which would succeed and
* return `null`.
*
* NOTE: Headless mode doesn't support navigation to a PDF document. See
* the {@link https://bugs.chromium.org/p/chromium/issues/detail?id=761295 | upstream
* issue}.
*
* @param url - the URL to navigate the frame to. This should include the
* scheme, e.g. `https://`.
* @param options - navigation options. `waitUntil` is useful to define when
* the navigation should be considered successful - see the docs for
* {@link PuppeteerLifeCycleEvent} for more details.
*
* @returns A promise which resolves to the main resource response. In case of
* multiple redirects, the navigation will resolve with the response of the
* last redirect.
*/
async goto(
url: string,
options: {
referer?: string;
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
} = {}
): Promise<HTTPResponse | null> {
return await this._frameManager.navigateFrame(this, url, options);
}
/**
* @remarks
*
* This resolves when the frame navigates to a new URL. It is useful for when
* you run code which will indirectly cause the frame to navigate. Consider
* this example:
*
* ```ts
* const [response] = await Promise.all([
* // The navigation promise resolves after navigation has finished
* frame.waitForNavigation(),
* // Clicking the link will indirectly cause a navigation
* frame.click('a.my-link'),
* ]);
* ```
*
* Usage of the {@link https://developer.mozilla.org/en-US/docs/Web/API/History_API | History API} to change the URL is considered a navigation.
*
* @param options - options to configure when the navigation is consided finished.
* @returns a promise that resolves when the frame navigates to a new URL.
*/
async waitForNavigation(
options: {
timeout?: number;
waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
} = {}
): Promise<HTTPResponse | null> {
return await this._frameManager.waitForFrameNavigation(this, options);
}
/**
* @internal
*/
_client(): CDPSession {
return this.#client;
}
/**
* @returns a promise that resolves to the frame's default execution context.
*/
executionContext(): Promise<ExecutionContext> {
return this._mainWorld.executionContext();
}
/**
* @remarks
*
* The only difference between {@link Frame.evaluate} and
* `frame.evaluateHandle` is that `evaluateHandle` will return the value
* wrapped in an in-page object.
*
* This method behaves identically to {@link Page.evaluateHandle} except it's
* run within the context of the `frame`, rather than the entire page.
*
* @param pageFunction - a function that is run within the frame
* @param args - arguments to be passed to the pageFunction
*/
async evaluateHandle<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
...args: Params
): Promise<HandleFor<Awaited<ReturnType<Func>>>> {
return this._mainWorld.evaluateHandle(pageFunction, ...args);
}
/**
* @remarks
*
* This method behaves identically to {@link Page.evaluate} except it's run
* within the context of the `frame`, rather than the entire page.
*
* @param pageFunction - a function that is run within the frame
* @param args - arguments to be passed to the pageFunction
*/
async evaluate<
Params extends unknown[],
Func extends EvaluateFunc<Params> = EvaluateFunc<Params>
>(
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>> {
return this._mainWorld.evaluate(pageFunction, ...args);
}
/**
* This method queries the frame for the given selector.
*
* @param selector - a selector to query for.
* @returns A promise which resolves to an `ElementHandle` pointing at the
* element, or `null` if it was not found.
*/
async $<Selector extends string>(
selector: Selector
): Promise<ElementHandle<NodeFor<Selector>> | null> {
return this._mainWorld.$(selector);
}
/**
* This runs `document.querySelectorAll` in the frame and returns the result.
*
* @param selector - a selector to search for
* @returns An array of element handles pointing to the found frame elements.
*/
async $$<Selector extends string>(
selector: Selector
): Promise<Array<ElementHandle<NodeFor<Selector>>>> {
return this._mainWorld.$$(selector);