/
frames.ts
1227 lines (1087 loc) · 48.3 KB
/
frames.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.
* Modifications copyright (c) Microsoft Corporation.
*
* 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 { ConsoleMessage } from './console';
import * as dom from './dom';
import { helper, RegisteredListener } from './helper';
import * as js from './javascript';
import * as network from './network';
import { Page } from './page';
import * as types from './types';
import { BrowserContext } from './browserContext';
import { Progress, ProgressController, runAbortableTask } from './progress';
import { EventEmitter } from 'events';
import { assert, makeWaitForNextTask } from '../utils/utils';
import { debugLogger } from '../utils/debugLogger';
type ContextData = {
contextPromise: Promise<dom.FrameExecutionContext>;
contextResolveCallback: (c: dom.FrameExecutionContext) => void;
context: dom.FrameExecutionContext | null;
rerunnableTasks: Set<RerunnableTask>;
};
type DocumentInfo = {
// Unfortunately, we don't have documentId when we find out about
// a pending navigation from things like frameScheduledNavigaiton.
documentId: string | undefined,
request: network.Request | undefined,
};
export type GotoResult = {
newDocumentId?: string,
};
type ConsoleTagHandler = () => void;
export type FunctionWithSource = (source: { context: BrowserContext, page: Page, frame: Frame}, ...args: any) => any;
export type NavigationEvent = {
// New frame url after navigation.
url: string,
// New frame name after navigation.
name: string,
// Information about the new document for cross-document navigations.
// Undefined for same-document navigations.
newDocument?: DocumentInfo,
// Error for cross-document navigations if any. When error is present,
// the navigation did not commit.
error?: Error,
};
export class FrameManager {
private _page: Page;
private _frames = new Map<string, Frame>();
private _mainFrame: Frame;
readonly _consoleMessageTags = new Map<string, ConsoleTagHandler>();
readonly _signalBarriers = new Set<SignalBarrier>();
private _webSockets = new Map<string, network.WebSocket>();
constructor(page: Page) {
this._page = page;
this._mainFrame = undefined as any as Frame;
}
dispose() {
for (const frame of this._frames.values())
frame._stopNetworkIdleTimer();
}
mainFrame(): Frame {
return this._mainFrame;
}
frames() {
const frames: Frame[] = [];
collect(this._mainFrame);
return frames;
function collect(frame: Frame) {
frames.push(frame);
for (const subframe of frame.childFrames())
collect(subframe);
}
}
frame(frameId: string): Frame | null {
return this._frames.get(frameId) || null;
}
frameAttached(frameId: string, parentFrameId: string | null | undefined): Frame {
const parentFrame = parentFrameId ? this._frames.get(parentFrameId)! : null;
if (!parentFrame) {
if (this._mainFrame) {
// Update frame id to retain frame identity on cross-process navigation.
this._frames.delete(this._mainFrame._id);
this._mainFrame._id = frameId;
} else {
assert(!this._frames.has(frameId));
this._mainFrame = new Frame(this._page, frameId, parentFrame);
}
this._frames.set(frameId, this._mainFrame);
return this._mainFrame;
} else {
assert(!this._frames.has(frameId));
const frame = new Frame(this._page, frameId, parentFrame);
this._frames.set(frameId, frame);
this._page.emit(Page.Events.FrameAttached, frame);
return frame;
}
}
async waitForSignalsCreatedBy<T>(progress: Progress | null, noWaitAfter: boolean | undefined, action: () => Promise<T>, source?: 'input'): Promise<T> {
if (noWaitAfter)
return action();
const barrier = new SignalBarrier(progress);
this._signalBarriers.add(barrier);
if (progress)
progress.cleanupWhenAborted(() => this._signalBarriers.delete(barrier));
const result = await action();
if (source === 'input')
await this._page._delegate.inputActionEpilogue();
await barrier.waitFor();
this._signalBarriers.delete(barrier);
// Resolve in the next task, after all waitForNavigations.
await new Promise(makeWaitForNextTask());
return result;
}
frameWillPotentiallyRequestNavigation() {
for (const barrier of this._signalBarriers)
barrier.retain();
}
frameDidPotentiallyRequestNavigation() {
for (const barrier of this._signalBarriers)
barrier.release();
}
frameRequestedNavigation(frameId: string, documentId?: string) {
const frame = this._frames.get(frameId);
if (!frame)
return;
for (const barrier of this._signalBarriers)
barrier.addFrameNavigation(frame);
if (frame._pendingDocument && frame._pendingDocument.documentId === documentId) {
// Do not override request with undefined.
return;
}
frame._pendingDocument = { documentId, request: undefined };
}
frameCommittedNewDocumentNavigation(frameId: string, url: string, name: string, documentId: string, initial: boolean) {
const frame = this._frames.get(frameId)!;
this.removeChildFramesRecursively(frame);
this.clearWebSockets(frame);
frame._url = url;
frame._name = name;
let keepPending: DocumentInfo | undefined;
if (frame._pendingDocument) {
if (frame._pendingDocument.documentId === undefined) {
// Pending with unknown documentId - assume it is the one being committed.
frame._pendingDocument.documentId = documentId;
}
if (frame._pendingDocument.documentId === documentId) {
// Committing a pending document.
frame._currentDocument = frame._pendingDocument;
} else {
// Sometimes, we already have a new pending when the old one commits.
// An example would be Chromium error page followed by a new navigation request,
// where the error page commit arrives after Network.requestWillBeSent for the
// new navigation.
// We commit, but keep the pending request since it's not done yet.
keepPending = frame._pendingDocument;
frame._currentDocument = { documentId, request: undefined };
}
frame._pendingDocument = undefined;
} else {
// No pending - just commit a new document.
frame._currentDocument = { documentId, request: undefined };
}
frame._onClearLifecycle();
const navigationEvent: NavigationEvent = { url, name, newDocument: frame._currentDocument };
frame.emit(Frame.Events.Navigation, navigationEvent);
if (!initial) {
debugLogger.log('api', ` navigated to "${url}"`);
this._page.frameNavigated(frame);
}
// Restore pending if any - see comments above about keepPending.
frame._pendingDocument = keepPending;
}
frameCommittedSameDocumentNavigation(frameId: string, url: string) {
const frame = this._frames.get(frameId);
if (!frame)
return;
frame._url = url;
const navigationEvent: NavigationEvent = { url, name: frame._name };
frame.emit(Frame.Events.Navigation, navigationEvent);
debugLogger.log('api', ` navigated to "${url}"`);
this._page.frameNavigated(frame);
}
frameAbortedNavigation(frameId: string, errorText: string, documentId?: string) {
const frame = this._frames.get(frameId);
if (!frame || !frame._pendingDocument)
return;
if (documentId !== undefined && frame._pendingDocument.documentId !== documentId)
return;
const navigationEvent: NavigationEvent = {
url: frame._url,
name: frame._name,
newDocument: frame._pendingDocument,
error: new Error(errorText),
};
frame._pendingDocument = undefined;
frame.emit(Frame.Events.Navigation, navigationEvent);
}
frameDetached(frameId: string) {
const frame = this._frames.get(frameId);
if (frame)
this._removeFramesRecursively(frame);
}
frameStoppedLoading(frameId: string) {
this.frameLifecycleEvent(frameId, 'domcontentloaded');
this.frameLifecycleEvent(frameId, 'load');
}
frameLifecycleEvent(frameId: string, event: types.LifecycleEvent) {
const frame = this._frames.get(frameId);
if (frame)
frame._onLifecycleEvent(event);
}
requestStarted(request: network.Request) {
const frame = request.frame();
this._inflightRequestStarted(request);
if (request._documentId)
frame._pendingDocument = { documentId: request._documentId, request };
if (request._isFavicon) {
const route = request._route();
if (route)
route.continue();
return;
}
this._page._requestStarted(request);
}
requestReceivedResponse(response: network.Response) {
if (!response.request()._isFavicon)
this._page.emit(Page.Events.Response, response);
}
requestFinished(request: network.Request) {
this._inflightRequestFinished(request);
if (!request._isFavicon)
this._page.emit(Page.Events.RequestFinished, request);
}
requestFailed(request: network.Request, canceled: boolean) {
const frame = request.frame();
this._inflightRequestFinished(request);
if (frame._pendingDocument && frame._pendingDocument.request === request) {
let errorText = request.failure()!.errorText;
if (canceled)
errorText += '; maybe frame was detached?';
this.frameAbortedNavigation(frame._id, errorText, frame._pendingDocument.documentId);
}
if (!request._isFavicon)
this._page.emit(Page.Events.RequestFailed, request);
}
removeChildFramesRecursively(frame: Frame) {
for (const child of frame.childFrames())
this._removeFramesRecursively(child);
}
private _removeFramesRecursively(frame: Frame) {
this.removeChildFramesRecursively(frame);
frame._onDetached();
this._frames.delete(frame._id);
if (!this._page.isClosed())
this._page.emit(Page.Events.FrameDetached, frame);
}
private _inflightRequestFinished(request: network.Request) {
const frame = request.frame();
if (request._isFavicon)
return;
if (!frame._inflightRequests.has(request))
return;
frame._inflightRequests.delete(request);
if (frame._inflightRequests.size === 0)
frame._startNetworkIdleTimer();
}
private _inflightRequestStarted(request: network.Request) {
const frame = request.frame();
if (request._isFavicon)
return;
frame._inflightRequests.add(request);
if (frame._inflightRequests.size === 1)
frame._stopNetworkIdleTimer();
}
interceptConsoleMessage(message: ConsoleMessage): boolean {
if (message.type() !== 'debug')
return false;
const tag = message.text();
const handler = this._consoleMessageTags.get(tag);
if (!handler)
return false;
this._consoleMessageTags.delete(tag);
handler();
return true;
}
clearWebSockets(frame: Frame) {
// TODO: attribute sockets to frames.
if (frame.parentFrame())
return;
this._webSockets.clear();
}
onWebSocketCreated(requestId: string, url: string) {
const ws = new network.WebSocket(url);
this._webSockets.set(requestId, ws);
}
onWebSocketRequest(requestId: string) {
const ws = this._webSockets.get(requestId);
if (ws)
this._page.emit(Page.Events.WebSocket, ws);
}
onWebSocketResponse(requestId: string, status: number, statusText: string) {
const ws = this._webSockets.get(requestId);
if (status < 400)
return;
if (ws)
ws.error(`${statusText}: ${status}`);
}
onWebSocketFrameSent(requestId: string, opcode: number, data: string) {
const ws = this._webSockets.get(requestId);
if (ws)
ws.frameSent(opcode, data);
}
webSocketFrameReceived(requestId: string, opcode: number, data: string) {
const ws = this._webSockets.get(requestId);
if (ws)
ws.frameReceived(opcode, data);
}
webSocketClosed(requestId: string) {
const ws = this._webSockets.get(requestId);
if (ws)
ws.closed();
this._webSockets.delete(requestId);
}
webSocketError(requestId: string, errorMessage: string): void {
const ws = this._webSockets.get(requestId);
if (ws)
ws.error(errorMessage);
}
}
export class Frame extends EventEmitter {
static Events = {
Navigation: 'navigation',
AddLifecycle: 'addlifecycle',
RemoveLifecycle: 'removelifecycle',
};
_id: string;
private _firedLifecycleEvents = new Set<types.LifecycleEvent>();
_subtreeLifecycleEvents = new Set<types.LifecycleEvent>();
_currentDocument: DocumentInfo;
_pendingDocument?: DocumentInfo;
readonly _page: Page;
private _parentFrame: Frame | null;
_url = '';
private _detached = false;
private _contextData = new Map<types.World, ContextData>();
private _childFrames = new Set<Frame>();
_name = '';
_inflightRequests = new Set<network.Request>();
private _networkIdleTimer: NodeJS.Timer | undefined;
private _setContentCounter = 0;
readonly _detachedPromise: Promise<void>;
private _detachedCallback = () => {};
constructor(page: Page, id: string, parentFrame: Frame | null) {
super();
this.setMaxListeners(0);
this._id = id;
this._page = page;
this._parentFrame = parentFrame;
this._currentDocument = { documentId: undefined, request: undefined };
this._detachedPromise = new Promise<void>(x => this._detachedCallback = x);
this._contextData.set('main', { contextPromise: new Promise(() => {}), contextResolveCallback: () => {}, context: null, rerunnableTasks: new Set() });
this._contextData.set('utility', { contextPromise: new Promise(() => {}), contextResolveCallback: () => {}, context: null, rerunnableTasks: new Set() });
this._setContext('main', null);
this._setContext('utility', null);
if (this._parentFrame)
this._parentFrame._childFrames.add(this);
}
_onLifecycleEvent(event: types.LifecycleEvent) {
if (this._firedLifecycleEvents.has(event))
return;
this._firedLifecycleEvents.add(event);
// Recalculate subtree lifecycle for the whole tree - it should not be that big.
this._page.mainFrame()._recalculateLifecycle();
}
_onClearLifecycle() {
this._firedLifecycleEvents.clear();
// Recalculate subtree lifecycle for the whole tree - it should not be that big.
this._page.mainFrame()._recalculateLifecycle();
// Keep the current navigation request if any.
this._inflightRequests = new Set(Array.from(this._inflightRequests).filter(request => request === this._currentDocument.request));
this._stopNetworkIdleTimer();
if (this._inflightRequests.size === 0)
this._startNetworkIdleTimer();
}
private _recalculateLifecycle() {
const events = new Set<types.LifecycleEvent>(this._firedLifecycleEvents);
for (const child of this._childFrames) {
child._recalculateLifecycle();
// We require a particular lifecycle event to be fired in the whole
// frame subtree, and then consider it done.
for (const event of events) {
if (!child._subtreeLifecycleEvents.has(event))
events.delete(event);
}
}
const mainFrame = this._page.mainFrame();
for (const event of events) {
// Checking whether we have already notified about this event.
if (!this._subtreeLifecycleEvents.has(event)) {
this.emit(Frame.Events.AddLifecycle, event);
if (this === mainFrame && this._url !== 'about:blank')
debugLogger.log('api', ` "${event}" event fired`);
if (this === mainFrame && event === 'load')
this._page.emit(Page.Events.Load);
if (this === mainFrame && event === 'domcontentloaded')
this._page.emit(Page.Events.DOMContentLoaded);
}
}
for (const event of this._subtreeLifecycleEvents) {
if (!events.has(event))
this.emit(Frame.Events.RemoveLifecycle, event);
}
this._subtreeLifecycleEvents = events;
}
setupNavigationProgressController(controller: ProgressController) {
this._page._disconnectedPromise.then(() => controller.abort(new Error('Navigation failed because page was closed!')));
this._page._crashedPromise.then(() => controller.abort(new Error('Navigation failed because page crashed!')));
this._detachedPromise.then(() => controller.abort(new Error('Navigating frame was detached!')));
}
async goto(controller: ProgressController, url: string, options: types.GotoOptions = {}): Promise<network.Response | null> {
this.setupNavigationProgressController(controller);
return controller.run(async progress => {
const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
progress.log(`navigating to "${url}", waiting until "${waitUntil}"`);
const headers = this._page._state.extraHTTPHeaders || [];
const refererHeader = headers.find(h => h.name.toLowerCase() === 'referer');
let referer = refererHeader ? refererHeader.value : undefined;
if (options.referer !== undefined) {
if (referer !== undefined && referer !== options.referer)
throw new Error('"referer" is already specified as extra HTTP header');
referer = options.referer;
}
url = helper.completeUserURL(url);
const sameDocument = helper.waitForEvent(progress, this, Frame.Events.Navigation, (e: NavigationEvent) => !e.newDocument);
const navigateResult = await this._page._delegate.navigateFrame(this, url, referer);
let event: NavigationEvent;
if (navigateResult.newDocumentId) {
sameDocument.dispose();
event = await helper.waitForEvent(progress, this, Frame.Events.Navigation, (event: NavigationEvent) => {
// We are interested either in this specific document, or any other document that
// did commit and replaced the expected document.
return event.newDocument && (event.newDocument.documentId === navigateResult.newDocumentId || !event.error);
}).promise;
if (event.newDocument!.documentId !== navigateResult.newDocumentId) {
// This is just a sanity check. In practice, new navigation should
// cancel the previous one and report "request cancelled"-like error.
throw new Error('Navigation interrupted by another one');
}
if (event.error)
throw event.error;
} else {
event = await sameDocument.promise;
}
if (!this._subtreeLifecycleEvents.has(waitUntil))
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
const request = event.newDocument ? event.newDocument.request : undefined;
const response = request ? request._finalRequest().response() : null;
await this._page._doSlowMo();
return response;
}, this._page._timeoutSettings.navigationTimeout(options));
}
async _waitForNavigation(progress: Progress, options: types.NavigateOptions): Promise<network.Response | null> {
const waitUntil = verifyLifecycle('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
progress.log(`waiting for navigation until "${waitUntil}"`);
const navigationEvent: NavigationEvent = await helper.waitForEvent(progress, this, Frame.Events.Navigation, (event: NavigationEvent) => {
// Any failed navigation results in a rejection.
if (event.error)
return true;
progress.log(` navigated to "${this._url}"`);
return true;
}).promise;
if (navigationEvent.error)
throw navigationEvent.error;
if (!this._subtreeLifecycleEvents.has(waitUntil))
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
const request = navigationEvent.newDocument ? navigationEvent.newDocument.request : undefined;
return request ? request._finalRequest().response() : null;
}
async _waitForLoadState(progress: Progress, state: types.LifecycleEvent): Promise<void> {
const waitUntil = verifyLifecycle('state', state);
if (!this._subtreeLifecycleEvents.has(waitUntil))
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
}
async frameElement(): Promise<dom.ElementHandle> {
return this._page._delegate.getFrameElement(this);
}
_context(world: types.World): Promise<dom.FrameExecutionContext> {
if (this._detached)
throw new Error(`Execution Context is not available in detached frame "${this.url()}" (are you trying to evaluate?)`);
return this._contextData.get(world)!.contextPromise;
}
_mainContext(): Promise<dom.FrameExecutionContext> {
return this._context('main');
}
_utilityContext(): Promise<dom.FrameExecutionContext> {
return this._context('utility');
}
async _evaluateExpressionHandle(expression: string, isFunction: boolean, arg: any, world: types.World = 'main'): Promise<any> {
const context = await this._context(world);
const handle = await context.evaluateExpressionHandleInternal(expression, isFunction, arg);
if (world === 'main')
await this._page._doSlowMo();
return handle;
}
async _evaluateExpression(expression: string, isFunction: boolean, arg: any, world: types.World = 'main'): Promise<any> {
const context = await this._context(world);
const value = await context.evaluateExpressionInternal(expression, isFunction, arg);
if (world === 'main')
await this._page._doSlowMo();
return value;
}
async $(selector: string): Promise<dom.ElementHandle<Element> | null> {
return this._page.selectors._query(this, selector);
}
async waitForSelector(selector: string, options: types.WaitForElementOptions = {}): Promise<dom.ElementHandle<Element> | null> {
if ((options as any).visibility)
throw new Error('options.visibility is not supported, did you mean options.state?');
if ((options as any).waitFor && (options as any).waitFor !== 'visible')
throw new Error('options.waitFor is not supported, did you mean options.state?');
const { state = 'visible' } = options;
if (!['attached', 'detached', 'visible', 'hidden'].includes(state))
throw new Error(`state: expected one of (attached|detached|visible|hidden)`);
const info = this._page.selectors._parseSelector(selector);
const task = dom.waitForSelectorTask(info, state);
return runAbortableTask(async progress => {
progress.log(`waiting for selector "${selector}"${state === 'attached' ? '' : ' to be ' + state}`);
const result = await this._scheduleRerunnableHandleTask(progress, info.world, task);
if (!result.asElement()) {
result.dispose();
return null;
}
const handle = result.asElement() as dom.ElementHandle<Element>;
return handle._adoptTo(await this._mainContext());
}, this._page._timeoutSettings.timeout(options));
}
async dispatchEvent(selector: string, type: string, eventInit?: Object, options: types.TimeoutOptions = {}): Promise<void> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.dispatchEventTask(info, type, eventInit || {});
await runAbortableTask(async progress => {
progress.log(`Dispatching "${type}" event on selector "${selector}"...`);
// Note: we always dispatch events in the main world.
await this._scheduleRerunnableTask(progress, 'main', task);
}, this._page._timeoutSettings.timeout(options));
await this._page._doSlowMo();
}
async _$evalExpression(selector: string, expression: string, isFunction: boolean, arg: any): Promise<any> {
const handle = await this.$(selector);
if (!handle)
throw new Error(`Error: failed to find element matching selector "${selector}"`);
const result = await handle._evaluateExpression(expression, isFunction, true, arg);
handle.dispose();
return result;
}
async _$$evalExpression(selector: string, expression: string, isFunction: boolean, arg: any): Promise<any> {
const arrayHandle = await this._page.selectors._queryArray(this, selector);
const result = await arrayHandle._evaluateExpression(expression, isFunction, true, arg);
arrayHandle.dispose();
return result;
}
async $$(selector: string): Promise<dom.ElementHandle<Element>[]> {
return this._page.selectors._queryAll(this, selector, undefined, true /* adoptToMain */);
}
async content(): Promise<string> {
const context = await this._utilityContext();
return context.evaluateInternal(() => {
let retVal = '';
if (document.doctype)
retVal = new XMLSerializer().serializeToString(document.doctype);
if (document.documentElement)
retVal += document.documentElement.outerHTML;
return retVal;
});
}
async setContent(controller: ProgressController, html: string, options: types.NavigateOptions = {}): Promise<void> {
this.setupNavigationProgressController(controller);
return controller.run(async progress => {
const waitUntil = options.waitUntil === undefined ? 'load' : options.waitUntil;
progress.log(`setting frame content, waiting until "${waitUntil}"`);
const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;
const context = await this._utilityContext();
const lifecyclePromise = new Promise((resolve, reject) => {
this._page._frameManager._consoleMessageTags.set(tag, () => {
// Clear lifecycle right after document.open() - see 'tag' below.
this._onClearLifecycle();
this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);
});
});
const contentPromise = context.evaluateInternal(({ html, tag }) => {
window.stop();
document.open();
console.debug(tag); // eslint-disable-line no-console
document.write(html);
document.close();
}, { html, tag });
await Promise.all([contentPromise, lifecyclePromise]);
await this._page._doSlowMo();
}, this._page._timeoutSettings.navigationTimeout(options));
}
name(): string {
return this._name || '';
}
url(): string {
return this._url;
}
parentFrame(): Frame | null {
return this._parentFrame;
}
childFrames(): Frame[] {
return Array.from(this._childFrames);
}
async addScriptTag(params: {
url?: string,
content?: string,
type?: string,
}): Promise<dom.ElementHandle> {
const {
url = null,
content = null,
type = ''
} = params;
if (!url && !content)
throw new Error('Provide an object with a `url`, `path` or `content` property');
const context = await this._mainContext();
return this._raceWithCSPError(async () => {
if (url !== null)
return (await context.evaluateHandleInternal(addScriptUrl, { url, type })).asElement()!;
const result = (await context.evaluateHandleInternal(addScriptContent, { content: content!, type })).asElement()!;
// Another round trip to the browser to ensure that we receive CSP error messages
// (if any) logged asynchronously in a separate task on the content main thread.
if (this._page._delegate.cspErrorsAsynchronousForInlineScipts)
await context.evaluateInternal(() => true);
return result;
});
async function addScriptUrl(params: { url: string, type: string }): Promise<HTMLElement> {
const script = document.createElement('script');
script.src = params.url;
if (params.type)
script.type = params.type;
const promise = new Promise((res, rej) => {
script.onload = res;
script.onerror = e => rej(typeof e === 'string' ? new Error(e) : new Error(`Failed to load script at ${script.src}`));
});
document.head.appendChild(script);
await promise;
return script;
}
function addScriptContent(params: { content: string, type: string }): HTMLElement {
const script = document.createElement('script');
script.type = params.type || 'text/javascript';
script.text = params.content;
let error = null;
script.onerror = e => error = e;
document.head.appendChild(script);
if (error)
throw error;
return script;
}
}
async addStyleTag(params: { url?: string, content?: string }): Promise<dom.ElementHandle> {
const {
url = null,
content = null
} = params;
if (!url && !content)
throw new Error('Provide an object with a `url`, `path` or `content` property');
const context = await this._mainContext();
return this._raceWithCSPError(async () => {
if (url !== null)
return (await context.evaluateHandleInternal(addStyleUrl, url)).asElement()!;
return (await context.evaluateHandleInternal(addStyleContent, content!)).asElement()!;
});
async function addStyleUrl(url: string): Promise<HTMLElement> {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
const promise = new Promise((res, rej) => {
link.onload = res;
link.onerror = rej;
});
document.head.appendChild(link);
await promise;
return link;
}
async function addStyleContent(content: string): Promise<HTMLElement> {
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(content));
const promise = new Promise((res, rej) => {
style.onload = res;
style.onerror = rej;
});
document.head.appendChild(style);
await promise;
return style;
}
}
private async _raceWithCSPError(func: () => Promise<dom.ElementHandle>): Promise<dom.ElementHandle> {
const listeners: RegisteredListener[] = [];
let result: dom.ElementHandle;
let error: Error | undefined;
let cspMessage: ConsoleMessage | undefined;
const actionPromise = new Promise<dom.ElementHandle>(async resolve => {
try {
result = await func();
} catch (e) {
error = e;
}
resolve();
});
const errorPromise = new Promise(resolve => {
listeners.push(helper.addEventListener(this._page, Page.Events.Console, (message: ConsoleMessage) => {
if (message.type() === 'error' && message.text().includes('Content Security Policy')) {
cspMessage = message;
resolve();
}
}));
});
await Promise.race([actionPromise, errorPromise]);
helper.removeEventListeners(listeners);
if (cspMessage)
throw new Error(cspMessage.text());
if (error)
throw error;
return result!;
}
private async _retryWithProgressIfNotConnected<R>(
progress: Progress,
selector: string,
action: (handle: dom.ElementHandle<Element>) => Promise<R | 'error:notconnected'>): Promise<R> {
const info = this._page.selectors._parseSelector(selector);
while (progress.isRunning()) {
progress.log(`waiting for selector "${selector}"`);
const task = dom.waitForSelectorTask(info, 'attached');
const handle = await this._scheduleRerunnableHandleTask(progress, info.world, task);
const element = handle.asElement() as dom.ElementHandle<Element>;
progress.cleanupWhenAborted(() => {
// Do not await here to avoid being blocked, either by stalled
// page (e.g. alert) or unresolved navigation in Chromium.
element.dispose();
});
const result = await action(element);
element.dispose();
if (result === 'error:notconnected') {
progress.log('element was detached from the DOM, retrying');
continue;
}
return result;
}
return undefined as any;
}
private async _retryWithSelectorIfNotConnected<R>(
selector: string, options: types.TimeoutOptions,
action: (progress: Progress, handle: dom.ElementHandle<Element>) => Promise<R | 'error:notconnected'>): Promise<R> {
return runAbortableTask(async progress => {
return this._retryWithProgressIfNotConnected(progress, selector, handle => action(progress, handle));
}, this._page._timeoutSettings.timeout(options));
}
async click(controller: ProgressController, selector: string, options: types.MouseClickOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._click(progress, options)));
}, this._page._timeoutSettings.timeout(options));
}
async dblclick(controller: ProgressController, selector: string, options: types.MouseMultiClickOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._dblclick(progress, options)));
}, this._page._timeoutSettings.timeout(options));
}
async tap(controller: ProgressController, selector: string, options: types.PointerActionWaitOptions & types.NavigatingActionWaitOptions) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._tap(progress, options)));
}, this._page._timeoutSettings.timeout(options));
}
async fill(controller: ProgressController, selector: string, value: string, options: types.NavigatingActionWaitOptions) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._fill(progress, value, options)));
}, this._page._timeoutSettings.timeout(options));
}
async focus(selector: string, options: types.TimeoutOptions = {}) {
await this._retryWithSelectorIfNotConnected(selector, options, (progress, handle) => handle._focus(progress));
await this._page._doSlowMo();
}
async textContent(selector: string, options: types.TimeoutOptions = {}): Promise<string | null> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.textContentTask(info);
return runAbortableTask(async progress => {
progress.log(` retrieving textContent from "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async innerText(selector: string, options: types.TimeoutOptions = {}): Promise<string> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.innerTextTask(info);
return runAbortableTask(async progress => {
progress.log(` retrieving innerText from "${selector}"`);
const result = dom.throwFatalDOMError(await this._scheduleRerunnableTask(progress, info.world, task));
return result.innerText;
}, this._page._timeoutSettings.timeout(options));
}
async innerHTML(selector: string, options: types.TimeoutOptions = {}): Promise<string> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.innerHTMLTask(info);
return runAbortableTask(async progress => {
progress.log(` retrieving innerHTML from "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async getAttribute(selector: string, name: string, options: types.TimeoutOptions = {}): Promise<string | null> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.getAttributeTask(info, name);
return runAbortableTask(async progress => {
progress.log(` retrieving attribute "${name}" from "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async isVisible(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.visibleTask(info);
return runAbortableTask(async progress => {
progress.log(` checking visibility of "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async isHidden(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
return !(await this.isVisible(selector, options));
}
async isDisabled(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.disabledTask(info);
return runAbortableTask(async progress => {
progress.log(` checking disabled state of "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async isEnabled(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
return !(await this.isDisabled(selector, options));
}
async isEditable(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.editableTask(info);
return runAbortableTask(async progress => {
progress.log(` checking editable state of "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async isChecked(selector: string, options: types.TimeoutOptions = {}): Promise<boolean> {
const info = this._page.selectors._parseSelector(selector);
const task = dom.checkedTask(info);
return runAbortableTask(async progress => {
progress.log(` checking checked state of "${selector}"`);
return this._scheduleRerunnableTask(progress, info.world, task);
}, this._page._timeoutSettings.timeout(options));
}
async hover(controller: ProgressController, selector: string, options: types.PointerActionOptions & types.PointerActionWaitOptions = {}) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._hover(progress, options)));
}, this._page._timeoutSettings.timeout(options));
}
async selectOption(controller: ProgressController, selector: string, elements: dom.ElementHandle[], values: types.SelectOption[], options: types.NavigatingActionWaitOptions = {}): Promise<string[]> {
return controller.run(async progress => {
return await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._selectOption(progress, elements, values, options));
}, this._page._timeoutSettings.timeout(options));
}
async setInputFiles(controller: ProgressController, selector: string, files: types.FilePayload[], options: types.NavigatingActionWaitOptions = {}): Promise<void> {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._setInputFiles(progress, files, options)));
}, this._page._timeoutSettings.timeout(options));
}
async type(controller: ProgressController, selector: string, text: string, options: { delay?: number } & types.NavigatingActionWaitOptions = {}) {
return controller.run(async progress => {
return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, handle => handle._type(progress, text, options)));
}, this._page._timeoutSettings.timeout(options));
}
async press(controller: ProgressController, selector: string, key: string, options: { delay?: number } & types.NavigatingActionWaitOptions = {}) {
return controller.run(async progress => {