-
-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
webdriver.js
3378 lines (3053 loc) · 105 KB
/
webdriver.js
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
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you 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.
/**
* @fileoverview The heart of the WebDriver JavaScript API.
*/
'use strict'
const by = require('./by')
const { RelativeBy } = require('./by')
const command = require('./command')
const error = require('./error')
const input = require('./input')
const logging = require('./logging')
const promise = require('./promise')
const Symbols = require('./symbols')
const cdp = require('../devtools/CDPConnection')
const WebSocket = require('ws')
const http = require('../http/index')
const fs = require('node:fs')
const { Capabilities } = require('./capabilities')
const path = require('node:path')
const { NoSuchElementError } = require('./error')
const cdpTargets = ['page', 'browser']
const { Credential } = require('./virtual_authenticator')
const webElement = require('./webelement')
const { isObject } = require('./util')
const BIDI = require('../bidi')
const { PinnedScript } = require('./pinnedScript')
const JSZip = require('jszip')
const Script = require('./script')
const Network = require('./network')
// Capability names that are defined in the W3C spec.
const W3C_CAPABILITY_NAMES = new Set([
'acceptInsecureCerts',
'browserName',
'browserVersion',
'pageLoadStrategy',
'platformName',
'proxy',
'setWindowRect',
'strictFileInteractability',
'timeouts',
'unhandledPromptBehavior',
'webSocketUrl',
])
/**
* Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait
* command}.
*
* @template OUT
*/
class Condition {
/**
* @param {string} message A descriptive error message. Should complete the
* sentence "Waiting [...]"
* @param {function(!WebDriver): OUT} fn The condition function to
* evaluate on each iteration of the wait loop.
*/
constructor(message, fn) {
/** @private {string} */
this.description_ = 'Waiting ' + message
/** @type {function(!WebDriver): OUT} */
this.fn = fn
}
/** @return {string} A description of this condition. */
description() {
return this.description_
}
}
/**
* Defines a condition that will result in a {@link WebElement}.
*
* @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
*/
class WebElementCondition extends Condition {
/**
* @param {string} message A descriptive error message. Should complete the
* sentence "Waiting [...]"
* @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}
* fn The condition function to evaluate on each iteration of the wait
* loop.
*/
constructor(message, fn) {
super(message, fn)
}
}
//////////////////////////////////////////////////////////////////////////////
//
// WebDriver
//
//////////////////////////////////////////////////////////////////////////////
/**
* Translates a command to its wire-protocol representation before passing it
* to the given `executor` for execution.
* @param {!command.Executor} executor The executor to use.
* @param {!command.Command} command The command to execute.
* @return {!Promise} A promise that will resolve with the command response.
*/
function executeCommand(executor, command) {
return toWireValue(command.getParameters()).then(function (parameters) {
command.setParameters(parameters)
return executor.execute(command)
})
}
/**
* Converts an object to its JSON representation in the WebDriver wire protocol.
* When converting values of type object, the following steps will be taken:
* <ol>
* <li>if the object is a WebElement, the return value will be the element's
* server ID
* <li>if the object defines a {@link Symbols.serialize} method, this algorithm
* will be recursively applied to the object's serialized representation
* <li>if the object provides a "toJSON" function, this algorithm will
* recursively be applied to the result of that function
* <li>otherwise, the value of each key will be recursively converted according
* to the rules above.
* </ol>
*
* @param {*} obj The object to convert.
* @return {!Promise<?>} A promise that will resolve to the input value's JSON
* representation.
*/
async function toWireValue(obj) {
let value = await Promise.resolve(obj)
if (value === void 0 || value === null) {
return value
}
if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
return convertKeys(value)
}
if (typeof value === 'function') {
return '' + value
}
if (typeof value[Symbols.serialize] === 'function') {
return toWireValue(value[Symbols.serialize]())
} else if (typeof value.toJSON === 'function') {
return toWireValue(value.toJSON())
}
return convertKeys(value)
}
async function convertKeys(obj) {
const isArray = Array.isArray(obj)
const numKeys = isArray ? obj.length : Object.keys(obj).length
const ret = isArray ? new Array(numKeys) : {}
if (!numKeys) {
return ret
}
async function forEachKey(obj, fn) {
if (Array.isArray(obj)) {
for (let i = 0, n = obj.length; i < n; i++) {
await fn(obj[i], i)
}
} else {
for (let key in obj) {
await fn(obj[key], key)
}
}
}
await forEachKey(obj, async function (value, key) {
ret[key] = await toWireValue(value)
})
return ret
}
/**
* Converts a value from its JSON representation according to the WebDriver wire
* protocol. Any JSON object that defines a WebElement ID will be decoded to a
* {@link WebElement} object. All other values will be passed through as is.
*
* @param {!WebDriver} driver The driver to use as the parent of any unwrapped
* {@link WebElement} values.
* @param {*} value The value to convert.
* @return {*} The converted value.
*/
function fromWireValue(driver, value) {
if (Array.isArray(value)) {
value = value.map((v) => fromWireValue(driver, v))
} else if (WebElement.isId(value)) {
let id = WebElement.extractId(value)
value = new WebElement(driver, id)
} else if (ShadowRoot.isId(value)) {
let id = ShadowRoot.extractId(value)
value = new ShadowRoot(driver, id)
} else if (isObject(value)) {
let result = {}
for (let key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
result[key] = fromWireValue(driver, value[key])
}
}
value = result
}
return value
}
/**
* Resolves a wait message from either a function or a string.
* @param {(string|Function)=} message An optional message to use if the wait times out.
* @return {string} The resolved message
*/
function resolveWaitMessage(message) {
return message ? `${typeof message === 'function' ? message() : message}\n` : ''
}
/**
* Structural interface for a WebDriver client.
*
* @record
*/
class IWebDriver {
/**
* Executes the provided {@link command.Command} using this driver's
* {@link command.Executor}.
*
* @param {!command.Command} command The command to schedule.
* @return {!Promise<T>} A promise that will be resolved with the command
* result.
* @template T
*/
execute(command) {} // eslint-disable-line
/**
* Sets the {@linkplain input.FileDetector file detector} that should be
* used with this instance.
* @param {input.FileDetector} detector The detector to use or `null`.
*/
setFileDetector(detector) {} // eslint-disable-line
/**
* @return {!command.Executor} The command executor used by this instance.
*/
getExecutor() {}
/**
* @return {!Promise<!Session>} A promise for this client's session.
*/
getSession() {}
/**
* @return {!Promise<!Capabilities>} A promise that will resolve with
* the instance's capabilities.
*/
getCapabilities() {}
/**
* Terminates the browser session. After calling quit, this instance will be
* invalidated and may no longer be used to issue commands against the
* browser.
*
* @return {!Promise<void>} A promise that will be resolved when the
* command has completed.
*/
quit() {}
/**
* Creates a new action sequence using this driver. The sequence will not be
* submitted for execution until
* {@link ./input.Actions#perform Actions.perform()} is called.
*
* @param {{async: (boolean|undefined),
* bridge: (boolean|undefined)}=} options Configuration options for
* the action sequence (see {@link ./input.Actions Actions} documentation
* for details).
* @return {!input.Actions} A new action sequence for this instance.
*/
actions(options) {} // eslint-disable-line
/**
* Executes a snippet of JavaScript in the context of the currently selected
* frame or window. The script fragment will be executed as the body of an
* anonymous function. If the script is provided as a function object, that
* function will be converted to a string for injection into the target
* window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the `arguments` object. Arguments may
* be a boolean, number, string, or {@linkplain WebElement}. Arrays and
* objects may also be used as script arguments as long as each item adheres
* to the types previously mentioned.
*
* The script may refer to any variables accessible from the current window.
* Furthermore, the script will execute in the window's context, thus
* `document` may be used to refer to the current document. Any local
* variables will not be available once the script has finished executing,
* though global variables will persist.
*
* If the script has a return value (i.e. if the script contains a return
* statement), then the following steps will be taken for resolving this
* functions return value:
*
* - For a HTML element, the value will resolve to a {@linkplain WebElement}
* - Null and undefined return values will resolve to null</li>
* - Booleans, numbers, and strings will resolve as is</li>
* - Functions will resolve to their string representation</li>
* - For arrays and objects, each member item will be converted according to
* the rules above
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} args The arguments to pass to the script.
* @return {!IThenable<T>} A promise that will resolve to the
* scripts return value.
* @template T
*/
executeScript(script, ...args) {} // eslint-disable-line
/**
* Executes a snippet of asynchronous JavaScript in the context of the
* currently selected frame or window. The script fragment will be executed as
* the body of an anonymous function. If the script is provided as a function
* object, that function will be converted to a string for injection into the
* target window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the `arguments` object. Arguments may
* be a boolean, number, string, or {@linkplain WebElement}. Arrays and
* objects may also be used as script arguments as long as each item adheres
* to the types previously mentioned.
*
* Unlike executing synchronous JavaScript with {@link #executeScript},
* scripts executed with this function must explicitly signal they are
* finished by invoking the provided callback. This callback will always be
* injected into the executed function as the last argument, and thus may be
* referenced with `arguments[arguments.length - 1]`. The following steps
* will be taken for resolving this functions return value against the first
* argument to the script's callback function:
*
* - For a HTML element, the value will resolve to a {@link WebElement}
* - Null and undefined return values will resolve to null
* - Booleans, numbers, and strings will resolve as is
* - Functions will resolve to their string representation
* - For arrays and objects, each member item will be converted according to
* the rules above
*
* __Example #1:__ Performing a sleep that is synchronized with the currently
* selected window:
*
* var start = new Date().getTime();
* driver.executeAsyncScript(
* 'window.setTimeout(arguments[arguments.length - 1], 500);').
* then(function() {
* console.log(
* 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
* });
*
* __Example #2:__ Synchronizing a test with an AJAX application:
*
* var button = driver.findElement(By.id('compose-button'));
* button.click();
* driver.executeAsyncScript(
* 'var callback = arguments[arguments.length - 1];' +
* 'mailClient.getComposeWindowWidget().onload(callback);');
* driver.switchTo().frame('composeWidget');
* driver.findElement(By.id('to')).sendKeys('[email protected]');
*
* __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
* this example, the inject script is specified with a function literal. When
* using this format, the function is converted to a string for injection, so
* it should not reference any symbols not defined in the scope of the page
* under test.
*
* driver.executeAsyncScript(function() {
* var callback = arguments[arguments.length - 1];
* var xhr = new XMLHttpRequest();
* xhr.open("GET", "/resource/data.json", true);
* xhr.onreadystatechange = function() {
* if (xhr.readyState == 4) {
* callback(xhr.responseText);
* }
* };
* xhr.send('');
* }).then(function(str) {
* console.log(JSON.parse(str)['food']);
* });
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} args The arguments to pass to the script.
* @return {!IThenable<T>} A promise that will resolve to the scripts return
* value.
* @template T
*/
executeAsyncScript(script, ...args) {} // eslint-disable-line
/**
* Waits for a condition to evaluate to a "truthy" value. The condition may be
* specified by a {@link Condition}, as a custom function, or as any
* promise-like thenable.
*
* For a {@link Condition} or function, the wait will repeatedly
* evaluate the condition until it returns a truthy value. If any errors occur
* while evaluating the condition, they will be allowed to propagate. In the
* event a condition returns a {@linkplain Promise}, the polling loop will
* wait for it to be resolved and use the resolved value for whether the
* condition has been satisfied. The resolution time for a promise is always
* factored into whether a wait has timed out.
*
* If the provided condition is a {@link WebElementCondition}, then
* the wait will return a {@link WebElementPromise} that will resolve to the
* element that satisfied the condition.
*
* _Example:_ waiting up to 10 seconds for an element to be present on the
* page.
*
* async function example() {
* let button =
* await driver.wait(until.elementLocated(By.id('foo')), 10000);
* await button.click();
* }
*
* @param {!(IThenable<T>|
* Condition<T>|
* function(!WebDriver): T)} condition The condition to
* wait on, defined as a promise, condition object, or a function to
* evaluate as a condition.
* @param {number=} timeout The duration in milliseconds, how long to wait
* for the condition to be true.
* @param {(string|Function)=} message An optional message to use if the wait times out.
* @param {number=} pollTimeout The duration in milliseconds, how long to
* wait between polling the condition.
* @return {!(IThenable<T>|WebElementPromise)} A promise that will be
* resolved with the first truthy value returned by the condition
* function, or rejected if the condition times out. If the input
* condition is an instance of a {@link WebElementCondition},
* the returned value will be a {@link WebElementPromise}.
* @throws {TypeError} if the provided `condition` is not a valid type.
* @template T
*/
wait(
condition, // eslint-disable-line
timeout = undefined, // eslint-disable-line
message = undefined, // eslint-disable-line
pollTimeout = undefined, // eslint-disable-line
) {}
/**
* Makes the driver sleep for the given amount of time.
*
* @param {number} ms The amount of time, in milliseconds, to sleep.
* @return {!Promise<void>} A promise that will be resolved when the sleep has
* finished.
*/
sleep(ms) {} // eslint-disable-line
/**
* Retrieves the current window handle.
*
* @return {!Promise<string>} A promise that will be resolved with the current
* window handle.
*/
getWindowHandle() {}
/**
* Retrieves a list of all available window handles.
*
* @return {!Promise<!Array<string>>} A promise that will be resolved with an
* array of window handles.
*/
getAllWindowHandles() {}
/**
* Retrieves the current page's source. The returned source is a representation
* of the underlying DOM: do not expect it to be formatted or escaped in the
* same way as the raw response sent from the web server.
*
* @return {!Promise<string>} A promise that will be resolved with the current
* page source.
*/
getPageSource() {}
/**
* Closes the current window.
*
* @return {!Promise<void>} A promise that will be resolved when this command
* has completed.
*/
close() {}
/**
* Navigates to the given URL.
*
* @param {string} url The fully qualified URL to open.
* @return {!Promise<void>} A promise that will be resolved when the document
* has finished loading.
*/
get(url) {} // eslint-disable-line
/**
* Retrieves the URL for the current page.
*
* @return {!Promise<string>} A promise that will be resolved with the
* current URL.
*/
getCurrentUrl() {}
/**
* Retrieves the current page title.
*
* @return {!Promise<string>} A promise that will be resolved with the current
* page's title.
*/
getTitle() {}
/**
* Locates an element on the page. If the element cannot be found, a
* {@link error.NoSuchElementError} will be returned by the driver.
*
* This function should not be used to test whether an element is present on
* the page. Rather, you should use {@link #findElements}:
*
* driver.findElements(By.id('foo'))
* .then(found => console.log('Element found? %s', !!found.length));
*
* The search criteria for an element may be defined using one of the
* factories in the {@link webdriver.By} namespace, or as a short-hand
* {@link webdriver.By.Hash} object. For example, the following two statements
* are equivalent:
*
* var e1 = driver.findElement(By.id('foo'));
* var e2 = driver.findElement({id:'foo'});
*
* You may also provide a custom locator function, which takes as input this
* instance and returns a {@link WebElement}, or a promise that will resolve
* to a WebElement. If the returned promise resolves to an array of
* WebElements, WebDriver will use the first element. For example, to find the
* first visible link on a page, you could write:
*
* var link = driver.findElement(firstVisibleLink);
*
* function firstVisibleLink(driver) {
* var links = driver.findElements(By.tagName('a'));
* return promise.filter(links, function(link) {
* return link.isDisplayed();
* });
* }
*
* @param {!(by.By|Function)} locator The locator to use.
* @return {!WebElementPromise} A WebElement that can be used to issue
* commands against the located element. If the element is not found, the
* element will be invalidated and all scheduled commands aborted.
*/
findElement(locator) {} // eslint-disable-line
/**
* Search for multiple elements on the page. Refer to the documentation on
* {@link #findElement(by)} for information on element locator strategies.
*
* @param {!(by.By|Function)} locator The locator to use.
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
* array of WebElements.
*/
findElements(locator) {} // eslint-disable-line
/**
* Takes a screenshot of the current page. The driver makes the best effort to
* return a screenshot of the following, in order of preference:
*
* 1. Entire page
* 2. Current window
* 3. Visible portion of the current frame
* 4. The entire display containing the browser
*
* @return {!Promise<string>} A promise that will be resolved to the
* screenshot as a base-64 encoded PNG.
*/
takeScreenshot() {}
/**
* @return {!Options} The options interface for this instance.
*/
manage() {}
/**
* @return {!Navigation} The navigation interface for this instance.
*/
navigate() {}
/**
* @return {!TargetLocator} The target locator interface for this
* instance.
*/
switchTo() {}
/**
*
* Takes a PDF of the current page. The driver makes a best effort to
* return a PDF based on the provided parameters.
*
* @param {{orientation:(string|undefined),
* scale:(number|undefined),
* background:(boolean|undefined),
* width:(number|undefined),
* height:(number|undefined),
* top:(number|undefined),
* bottom:(number|undefined),
* left:(number|undefined),
* right:(number|undefined),
* shrinkToFit:(boolean|undefined),
* pageRanges:(Array|undefined)}} options
*/
printPage(options) {} // eslint-disable-line
}
/**
* @param {!Capabilities} capabilities A capabilities object.
* @return {!Capabilities} A copy of the parameter capabilities, omitting
* capability names that are not valid W3C names.
*/
function filterNonW3CCaps(capabilities) {
let newCaps = new Capabilities(capabilities)
for (let k of newCaps.keys()) {
// Any key containing a colon is a vendor-prefixed capability.
if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) {
newCaps.delete(k)
}
}
return newCaps
}
/**
* Each WebDriver instance provides automated control over a browser session.
*
* @implements {IWebDriver}
*/
class WebDriver {
#script = undefined
#network = undefined
/**
* @param {!(./session.Session|IThenable<!./session.Session>)} session Either
* a known session or a promise that will be resolved to a session.
* @param {!command.Executor} executor The executor to use when sending
* commands to the browser.
* @param {(function(this: void): ?)=} onQuit A function to call, if any,
* when the session is terminated.
*/
constructor(session, executor, onQuit = undefined) {
/** @private {!Promise<!Session>} */
this.session_ = Promise.resolve(session)
// If session is a rejected promise, add a no-op rejection handler.
// This effectively hides setup errors until users attempt to interact
// with the session.
this.session_.catch(function () {})
/** @private {!command.Executor} */
this.executor_ = executor
/** @private {input.FileDetector} */
this.fileDetector_ = null
/** @private @const {(function(this: void): ?|undefined)} */
this.onQuit_ = onQuit
/** @private {./virtual_authenticator}*/
this.authenticatorId_ = null
this.pinnedScripts_ = {}
}
/**
* Creates a new WebDriver session.
*
* This function will always return a WebDriver instance. If there is an error
* creating the session, such as the aforementioned SessionNotCreatedError,
* the driver will have a rejected {@linkplain #getSession session} promise.
* This rejection will propagate through any subsequent commands scheduled
* on the returned WebDriver instance.
*
* let required = Capabilities.firefox();
* let driver = WebDriver.createSession(executor, {required});
*
* // If the createSession operation failed, then this command will also
* // also fail, propagating the creation failure.
* driver.get('http://www.google.com').catch(e => console.log(e));
*
* @param {!command.Executor} executor The executor to create the new session
* with.
* @param {!Capabilities} capabilities The desired capabilities for the new
* session.
* @param {(function(this: void): ?)=} onQuit A callback to invoke when
* the newly created session is terminated. This should be used to clean
* up any resources associated with the session.
* @return {!WebDriver} The driver for the newly created session.
*/
static createSession(executor, capabilities, onQuit = undefined) {
let cmd = new command.Command(command.Name.NEW_SESSION)
// For W3C remote ends.
cmd.setParameter('capabilities', {
firstMatch: [{}],
alwaysMatch: filterNonW3CCaps(capabilities),
})
let session = executeCommand(executor, cmd)
if (typeof onQuit === 'function') {
session = session.catch((err) => {
return Promise.resolve(onQuit.call(void 0)).then((_) => {
throw err
})
})
}
return new this(session, executor, onQuit)
}
/** @override */
async execute(command) {
command.setParameter('sessionId', this.session_)
let parameters = await toWireValue(command.getParameters())
command.setParameters(parameters)
let value = await this.executor_.execute(command)
return fromWireValue(this, value)
}
/** @override */
setFileDetector(detector) {
this.fileDetector_ = detector
}
/** @override */
getExecutor() {
return this.executor_
}
/** @override */
getSession() {
return this.session_
}
/** @override */
getCapabilities() {
return this.session_.then((s) => s.getCapabilities())
}
/** @override */
quit() {
let result = this.execute(new command.Command(command.Name.QUIT))
// Delete our session ID when the quit command finishes; this will allow us
// to throw an error when attempting to use a driver post-quit.
return promise.finally(result, () => {
this.session_ = Promise.reject(
new error.NoSuchSessionError(
'This driver instance does not have a valid session ID ' +
'(did you call WebDriver.quit()?) and may no longer be used.',
),
)
// Only want the session rejection to bubble if accessed.
this.session_.catch(function () {})
if (this.onQuit_) {
return this.onQuit_.call(void 0)
}
// Close the websocket connection on quit
// If the websocket connection is not closed,
// and we are running CDP sessions against the Selenium Grid,
// the node process never exits since the websocket connection is open until the Grid is shutdown.
if (this._cdpWsConnection !== undefined) {
this._cdpWsConnection.close()
}
// Close the BiDi websocket connection
if (this._bidiConnection !== undefined) {
this._bidiConnection.close()
}
})
}
/** @override */
actions(options) {
return new input.Actions(this, options || undefined)
}
/** @override */
executeScript(script, ...args) {
if (typeof script === 'function') {
script = 'return (' + script + ').apply(null, arguments);'
}
if (script && script instanceof PinnedScript) {
return this.execute(
new command.Command(command.Name.EXECUTE_SCRIPT)
.setParameter('script', script.executionScript())
.setParameter('args', args),
)
}
return this.execute(
new command.Command(command.Name.EXECUTE_SCRIPT).setParameter('script', script).setParameter('args', args),
)
}
/** @override */
executeAsyncScript(script, ...args) {
if (typeof script === 'function') {
script = 'return (' + script + ').apply(null, arguments);'
}
if (script && script instanceof PinnedScript) {
return this.execute(
new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT)
.setParameter('script', script.executionScript())
.setParameter('args', args),
)
}
return this.execute(
new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).setParameter('script', script).setParameter('args', args),
)
}
/** @override */
wait(condition, timeout = 0, message = undefined, pollTimeout = 200) {
if (typeof timeout !== 'number' || timeout < 0) {
throw TypeError('timeout must be a number >= 0: ' + timeout)
}
if (typeof pollTimeout !== 'number' || pollTimeout < 0) {
throw TypeError('pollTimeout must be a number >= 0: ' + pollTimeout)
}
if (promise.isPromise(condition)) {
return new Promise((resolve, reject) => {
if (!timeout) {
resolve(condition)
return
}
let start = Date.now()
let timer = setTimeout(function () {
timer = null
try {
let timeoutMessage = resolveWaitMessage(message)
reject(
new error.TimeoutError(
`${timeoutMessage}Timed out waiting for promise to resolve after ${Date.now() - start}ms`,
),
)
} catch (ex) {
reject(
new error.TimeoutError(
`${ex.message}\nTimed out waiting for promise to resolve after ${Date.now() - start}ms`,
),
)
}
}, timeout)
const clearTimer = () => timer && clearTimeout(timer)
/** @type {!IThenable} */ condition.then(
function (value) {
clearTimer()
resolve(value)
},
function (error) {
clearTimer()
reject(error)
},
)
})
}
let fn = /** @type {!Function} */ (condition)
if (condition instanceof Condition) {
message = message || condition.description()
fn = condition.fn
}
if (typeof fn !== 'function') {
throw TypeError('Wait condition must be a promise-like object, function, or a ' + 'Condition object')
}
const driver = this
function evaluateCondition() {
return new Promise((resolve, reject) => {
try {
resolve(fn(driver))
} catch (ex) {
reject(ex)
}
})
}
let result = new Promise((resolve, reject) => {
const startTime = Date.now()
const pollCondition = async () => {
evaluateCondition().then(function (value) {
const elapsed = Date.now() - startTime
if (value) {
resolve(value)
} else if (timeout && elapsed >= timeout) {
try {
let timeoutMessage = resolveWaitMessage(message)
reject(new error.TimeoutError(`${timeoutMessage}Wait timed out after ${elapsed}ms`))
} catch (ex) {
reject(new error.TimeoutError(`${ex.message}\nWait timed out after ${elapsed}ms`))
}
} else {
setTimeout(pollCondition, pollTimeout)
}
}, reject)
}
pollCondition()
})
if (condition instanceof WebElementCondition) {
result = new WebElementPromise(
this,
result.then(function (value) {
if (!(value instanceof WebElement)) {
throw TypeError(
'WebElementCondition did not resolve to a WebElement: ' + Object.prototype.toString.call(value),
)
}
return value
}),
)
}
return result
}
/** @override */
sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/** @override */
getWindowHandle() {
return this.execute(new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE))
}
/** @override */
getAllWindowHandles() {
return this.execute(new command.Command(command.Name.GET_WINDOW_HANDLES))
}
/** @override */
getPageSource() {
return this.execute(new command.Command(command.Name.GET_PAGE_SOURCE))
}
/** @override */
close() {
return this.execute(new command.Command(command.Name.CLOSE))
}
/** @override */
get(url) {
return this.navigate().to(url)
}
/** @override */
getCurrentUrl() {
return this.execute(new command.Command(command.Name.GET_CURRENT_URL))
}
/** @override */
getTitle() {
return this.execute(new command.Command(command.Name.GET_TITLE))
}
/** @override */
findElement(locator) {
let id
let cmd = null