Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/javascript/selenium-webdriver/lib/webdriver.js
2884 views
1
// Licensed to the Software Freedom Conservancy (SFC) under one
2
// or more contributor license agreements. See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership. The SFC licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License. You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied. See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
/**
19
* @fileoverview The heart of the WebDriver JavaScript API.
20
*/
21
22
'use strict'
23
24
const by = require('./by')
25
const { RelativeBy } = require('./by')
26
const command = require('./command')
27
const error = require('./error')
28
const input = require('./input')
29
const logging = require('./logging')
30
const promise = require('./promise')
31
const Symbols = require('./symbols')
32
const cdp = require('../devtools/CDPConnection')
33
const WebSocket = require('ws')
34
const http = require('../http/index')
35
const fs = require('node:fs')
36
const { Capabilities } = require('./capabilities')
37
const path = require('node:path')
38
const { NoSuchElementError } = require('./error')
39
const cdpTargets = ['page', 'browser']
40
const { Credential } = require('./virtual_authenticator')
41
const webElement = require('./webelement')
42
const { isObject } = require('./util')
43
const BIDI = require('../bidi')
44
const { PinnedScript } = require('./pinnedScript')
45
const JSZip = require('jszip')
46
const Script = require('./script')
47
const Network = require('./network')
48
const Dialog = require('./fedcm/dialog')
49
50
// Capability names that are defined in the W3C spec.
51
const W3C_CAPABILITY_NAMES = new Set([
52
'acceptInsecureCerts',
53
'browserName',
54
'browserVersion',
55
'pageLoadStrategy',
56
'platformName',
57
'proxy',
58
'setWindowRect',
59
'strictFileInteractability',
60
'timeouts',
61
'unhandledPromptBehavior',
62
'webSocketUrl',
63
])
64
65
/**
66
* Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait
67
* command}.
68
*
69
* @template OUT
70
*/
71
class Condition {
72
/**
73
* @param {string} message A descriptive error message. Should complete the
74
* sentence "Waiting [...]"
75
* @param {function(!WebDriver): OUT} fn The condition function to
76
* evaluate on each iteration of the wait loop.
77
*/
78
constructor(message, fn) {
79
/** @private {string} */
80
this.description_ = 'Waiting ' + message
81
82
/** @type {function(!WebDriver): OUT} */
83
this.fn = fn
84
}
85
86
/** @return {string} A description of this condition. */
87
description() {
88
return this.description_
89
}
90
}
91
92
/**
93
* Defines a condition that will result in a {@link WebElement}.
94
*
95
* @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
96
*/
97
class WebElementCondition extends Condition {
98
/**
99
* @param {string} message A descriptive error message. Should complete the
100
* sentence "Waiting [...]"
101
* @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}
102
* fn The condition function to evaluate on each iteration of the wait
103
* loop.
104
*/
105
constructor(message, fn) {
106
super(message, fn)
107
}
108
}
109
110
//////////////////////////////////////////////////////////////////////////////
111
//
112
// WebDriver
113
//
114
//////////////////////////////////////////////////////////////////////////////
115
116
/**
117
* Translates a command to its wire-protocol representation before passing it
118
* to the given `executor` for execution.
119
* @param {!command.Executor} executor The executor to use.
120
* @param {!command.Command} command The command to execute.
121
* @return {!Promise} A promise that will resolve with the command response.
122
*/
123
function executeCommand(executor, command) {
124
return toWireValue(command.getParameters()).then(function (parameters) {
125
command.setParameters(parameters)
126
return executor.execute(command)
127
})
128
}
129
130
/**
131
* Converts an object to its JSON representation in the WebDriver wire protocol.
132
* When converting values of type object, the following steps will be taken:
133
* <ol>
134
* <li>if the object is a WebElement, the return value will be the element's
135
* server ID
136
* <li>if the object defines a {@link Symbols.serialize} method, this algorithm
137
* will be recursively applied to the object's serialized representation
138
* <li>if the object provides a "toJSON" function, this algorithm will
139
* recursively be applied to the result of that function
140
* <li>otherwise, the value of each key will be recursively converted according
141
* to the rules above.
142
* </ol>
143
*
144
* @param {*} obj The object to convert.
145
* @return {!Promise<?>} A promise that will resolve to the input value's JSON
146
* representation.
147
*/
148
async function toWireValue(obj) {
149
let value = await Promise.resolve(obj)
150
if (value === void 0 || value === null) {
151
return value
152
}
153
154
if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
155
return value
156
}
157
158
if (Array.isArray(value)) {
159
return convertKeys(value)
160
}
161
162
if (typeof value === 'function') {
163
return '' + value
164
}
165
166
if (typeof value[Symbols.serialize] === 'function') {
167
return toWireValue(value[Symbols.serialize]())
168
} else if (typeof value.toJSON === 'function') {
169
return toWireValue(value.toJSON())
170
}
171
return convertKeys(value)
172
}
173
174
async function convertKeys(obj) {
175
const isArray = Array.isArray(obj)
176
const numKeys = isArray ? obj.length : Object.keys(obj).length
177
const ret = isArray ? new Array(numKeys) : {}
178
if (!numKeys) {
179
return ret
180
}
181
182
async function forEachKey(obj, fn) {
183
if (Array.isArray(obj)) {
184
for (let i = 0, n = obj.length; i < n; i++) {
185
await fn(obj[i], i)
186
}
187
} else {
188
for (let key in obj) {
189
await fn(obj[key], key)
190
}
191
}
192
}
193
194
await forEachKey(obj, async function (value, key) {
195
ret[key] = await toWireValue(value)
196
})
197
198
return ret
199
}
200
201
/**
202
* Converts a value from its JSON representation according to the WebDriver wire
203
* protocol. Any JSON object that defines a WebElement ID will be decoded to a
204
* {@link WebElement} object. All other values will be passed through as is.
205
*
206
* @param {!WebDriver} driver The driver to use as the parent of any unwrapped
207
* {@link WebElement} values.
208
* @param {*} value The value to convert.
209
* @return {*} The converted value.
210
*/
211
function fromWireValue(driver, value) {
212
if (Array.isArray(value)) {
213
value = value.map((v) => fromWireValue(driver, v))
214
} else if (WebElement.isId(value)) {
215
let id = WebElement.extractId(value)
216
value = new WebElement(driver, id)
217
} else if (ShadowRoot.isId(value)) {
218
let id = ShadowRoot.extractId(value)
219
value = new ShadowRoot(driver, id)
220
} else if (isObject(value)) {
221
let result = {}
222
for (let key in value) {
223
if (Object.prototype.hasOwnProperty.call(value, key)) {
224
result[key] = fromWireValue(driver, value[key])
225
}
226
}
227
value = result
228
}
229
return value
230
}
231
232
/**
233
* Resolves a wait message from either a function or a string.
234
* @param {(string|Function)=} message An optional message to use if the wait times out.
235
* @return {string} The resolved message
236
*/
237
function resolveWaitMessage(message) {
238
return message ? `${typeof message === 'function' ? message() : message}\n` : ''
239
}
240
241
/**
242
* Structural interface for a WebDriver client.
243
*
244
* @record
245
*/
246
class IWebDriver {
247
/**
248
* Executes the provided {@link command.Command} using this driver's
249
* {@link command.Executor}.
250
*
251
* @param {!command.Command} command The command to schedule.
252
* @return {!Promise<T>} A promise that will be resolved with the command
253
* result.
254
* @template T
255
*/
256
execute(command) {} // eslint-disable-line
257
258
/**
259
* Sets the {@linkplain input.FileDetector file detector} that should be
260
* used with this instance.
261
* @param {input.FileDetector} detector The detector to use or `null`.
262
*/
263
setFileDetector(detector) {} // eslint-disable-line
264
265
/**
266
* @return {!command.Executor} The command executor used by this instance.
267
*/
268
getExecutor() {}
269
270
/**
271
* @return {!Promise<!Session>} A promise for this client's session.
272
*/
273
getSession() {}
274
275
/**
276
* @return {!Promise<!Capabilities>} A promise that will resolve with
277
* the instance's capabilities.
278
*/
279
getCapabilities() {}
280
281
/**
282
* Terminates the browser session. After calling quit, this instance will be
283
* invalidated and may no longer be used to issue commands against the
284
* browser.
285
*
286
* @return {!Promise<void>} A promise that will be resolved when the
287
* command has completed.
288
*/
289
quit() {}
290
291
/**
292
* Creates a new action sequence using this driver. The sequence will not be
293
* submitted for execution until
294
* {@link ./input.Actions#perform Actions.perform()} is called.
295
*
296
* @param {{async: (boolean|undefined),
297
* bridge: (boolean|undefined)}=} options Configuration options for
298
* the action sequence (see {@link ./input.Actions Actions} documentation
299
* for details).
300
* @return {!input.Actions} A new action sequence for this instance.
301
*/
302
actions(options) {} // eslint-disable-line
303
304
/**
305
* Executes a snippet of JavaScript in the context of the currently selected
306
* frame or window. The script fragment will be executed as the body of an
307
* anonymous function. If the script is provided as a function object, that
308
* function will be converted to a string for injection into the target
309
* window.
310
*
311
* Any arguments provided in addition to the script will be included as script
312
* arguments and may be referenced using the `arguments` object. Arguments may
313
* be a boolean, number, string, or {@linkplain WebElement}. Arrays and
314
* objects may also be used as script arguments as long as each item adheres
315
* to the types previously mentioned.
316
*
317
* The script may refer to any variables accessible from the current window.
318
* Furthermore, the script will execute in the window's context, thus
319
* `document` may be used to refer to the current document. Any local
320
* variables will not be available once the script has finished executing,
321
* though global variables will persist.
322
*
323
* If the script has a return value (i.e. if the script contains a return
324
* statement), then the following steps will be taken for resolving this
325
* functions return value:
326
*
327
* - For a HTML element, the value will resolve to a {@linkplain WebElement}
328
* - Null and undefined return values will resolve to null</li>
329
* - Booleans, numbers, and strings will resolve as is</li>
330
* - Functions will resolve to their string representation</li>
331
* - For arrays and objects, each member item will be converted according to
332
* the rules above
333
*
334
* @param {!(string|Function)} script The script to execute.
335
* @param {...*} args The arguments to pass to the script.
336
* @return {!IThenable<T>} A promise that will resolve to the
337
* scripts return value.
338
* @template T
339
*/
340
executeScript(script, ...args) {} // eslint-disable-line
341
342
/**
343
* Executes a snippet of asynchronous JavaScript in the context of the
344
* currently selected frame or window. The script fragment will be executed as
345
* the body of an anonymous function. If the script is provided as a function
346
* object, that function will be converted to a string for injection into the
347
* target window.
348
*
349
* Any arguments provided in addition to the script will be included as script
350
* arguments and may be referenced using the `arguments` object. Arguments may
351
* be a boolean, number, string, or {@linkplain WebElement}. Arrays and
352
* objects may also be used as script arguments as long as each item adheres
353
* to the types previously mentioned.
354
*
355
* Unlike executing synchronous JavaScript with {@link #executeScript},
356
* scripts executed with this function must explicitly signal they are
357
* finished by invoking the provided callback. This callback will always be
358
* injected into the executed function as the last argument, and thus may be
359
* referenced with `arguments[arguments.length - 1]`. The following steps
360
* will be taken for resolving this functions return value against the first
361
* argument to the script's callback function:
362
*
363
* - For a HTML element, the value will resolve to a {@link WebElement}
364
* - Null and undefined return values will resolve to null
365
* - Booleans, numbers, and strings will resolve as is
366
* - Functions will resolve to their string representation
367
* - For arrays and objects, each member item will be converted according to
368
* the rules above
369
*
370
* __Example #1:__ Performing a sleep that is synchronized with the currently
371
* selected window:
372
*
373
* var start = new Date().getTime();
374
* driver.executeAsyncScript(
375
* 'window.setTimeout(arguments[arguments.length - 1], 500);').
376
* then(function() {
377
* console.log(
378
* 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
379
* });
380
*
381
* __Example #2:__ Synchronizing a test with an AJAX application:
382
*
383
* var button = driver.findElement(By.id('compose-button'));
384
* button.click();
385
* driver.executeAsyncScript(
386
* 'var callback = arguments[arguments.length - 1];' +
387
* 'mailClient.getComposeWindowWidget().onload(callback);');
388
* driver.switchTo().frame('composeWidget');
389
* driver.findElement(By.id('to')).sendKeys('[email protected]');
390
*
391
* __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
392
* this example, the inject script is specified with a function literal. When
393
* using this format, the function is converted to a string for injection, so
394
* it should not reference any symbols not defined in the scope of the page
395
* under test.
396
*
397
* driver.executeAsyncScript(function() {
398
* var callback = arguments[arguments.length - 1];
399
* var xhr = new XMLHttpRequest();
400
* xhr.open("GET", "/resource/data.json", true);
401
* xhr.onreadystatechange = function() {
402
* if (xhr.readyState == 4) {
403
* callback(xhr.responseText);
404
* }
405
* };
406
* xhr.send('');
407
* }).then(function(str) {
408
* console.log(JSON.parse(str)['food']);
409
* });
410
*
411
* @param {!(string|Function)} script The script to execute.
412
* @param {...*} args The arguments to pass to the script.
413
* @return {!IThenable<T>} A promise that will resolve to the scripts return
414
* value.
415
* @template T
416
*/
417
executeAsyncScript(script, ...args) {} // eslint-disable-line
418
419
/**
420
* Waits for a condition to evaluate to a "truthy" value. The condition may be
421
* specified by a {@link Condition}, as a custom function, or as any
422
* promise-like thenable.
423
*
424
* For a {@link Condition} or function, the wait will repeatedly
425
* evaluate the condition until it returns a truthy value. If any errors occur
426
* while evaluating the condition, they will be allowed to propagate. In the
427
* event a condition returns a {@linkplain Promise}, the polling loop will
428
* wait for it to be resolved and use the resolved value for whether the
429
* condition has been satisfied. The resolution time for a promise is always
430
* factored into whether a wait has timed out.
431
*
432
* If the provided condition is a {@link WebElementCondition}, then
433
* the wait will return a {@link WebElementPromise} that will resolve to the
434
* element that satisfied the condition.
435
*
436
* _Example:_ waiting up to 10 seconds for an element to be present on the
437
* page.
438
*
439
* async function example() {
440
* let button =
441
* await driver.wait(until.elementLocated(By.id('foo')), 10000);
442
* await button.click();
443
* }
444
*
445
* @param {!(IThenable<T>|
446
* Condition<T>|
447
* function(!WebDriver): T)} condition The condition to
448
* wait on, defined as a promise, condition object, or a function to
449
* evaluate as a condition.
450
* @param {number=} timeout The duration in milliseconds, how long to wait
451
* for the condition to be true.
452
* @param {(string|Function)=} message An optional message to use if the wait times out.
453
* @param {number=} pollTimeout The duration in milliseconds, how long to
454
* wait between polling the condition.
455
* @return {!(IThenable<T>|WebElementPromise)} A promise that will be
456
* resolved with the first truthy value returned by the condition
457
* function, or rejected if the condition times out. If the input
458
* condition is an instance of a {@link WebElementCondition},
459
* the returned value will be a {@link WebElementPromise}.
460
* @throws {TypeError} if the provided `condition` is not a valid type.
461
* @template T
462
*/
463
wait(
464
condition, // eslint-disable-line
465
timeout = undefined, // eslint-disable-line
466
message = undefined, // eslint-disable-line
467
pollTimeout = undefined, // eslint-disable-line
468
) {}
469
470
/**
471
* Makes the driver sleep for the given amount of time.
472
*
473
* @param {number} ms The amount of time, in milliseconds, to sleep.
474
* @return {!Promise<void>} A promise that will be resolved when the sleep has
475
* finished.
476
*/
477
sleep(ms) {} // eslint-disable-line
478
479
/**
480
* Retrieves the current window handle.
481
*
482
* @return {!Promise<string>} A promise that will be resolved with the current
483
* window handle.
484
*/
485
getWindowHandle() {}
486
487
/**
488
* Retrieves a list of all available window handles.
489
*
490
* @return {!Promise<!Array<string>>} A promise that will be resolved with an
491
* array of window handles.
492
*/
493
getAllWindowHandles() {}
494
495
/**
496
* Retrieves the current page's source. The returned source is a representation
497
* of the underlying DOM: do not expect it to be formatted or escaped in the
498
* same way as the raw response sent from the web server.
499
*
500
* @return {!Promise<string>} A promise that will be resolved with the current
501
* page source.
502
*/
503
getPageSource() {}
504
505
/**
506
* Closes the current window.
507
*
508
* @return {!Promise<void>} A promise that will be resolved when this command
509
* has completed.
510
*/
511
close() {}
512
513
/**
514
* Navigates to the given URL.
515
*
516
* @param {string} url The fully qualified URL to open.
517
* @return {!Promise<void>} A promise that will be resolved when the document
518
* has finished loading.
519
*/
520
get(url) {} // eslint-disable-line
521
522
/**
523
* Retrieves the URL for the current page.
524
*
525
* @return {!Promise<string>} A promise that will be resolved with the
526
* current URL.
527
*/
528
getCurrentUrl() {}
529
530
/**
531
* Retrieves the current page title.
532
*
533
* @return {!Promise<string>} A promise that will be resolved with the current
534
* page's title.
535
*/
536
getTitle() {}
537
538
/**
539
* Locates an element on the page. If the element cannot be found, a
540
* {@link error.NoSuchElementError} will be returned by the driver.
541
*
542
* This function should not be used to test whether an element is present on
543
* the page. Rather, you should use {@link #findElements}:
544
*
545
* driver.findElements(By.id('foo'))
546
* .then(found => console.log('Element found? %s', !!found.length));
547
*
548
* The search criteria for an element may be defined using one of the
549
* factories in the {@link webdriver.By} namespace, or as a short-hand
550
* {@link webdriver.By.Hash} object. For example, the following two statements
551
* are equivalent:
552
*
553
* var e1 = driver.findElement(By.id('foo'));
554
* var e2 = driver.findElement({id:'foo'});
555
*
556
* You may also provide a custom locator function, which takes as input this
557
* instance and returns a {@link WebElement}, or a promise that will resolve
558
* to a WebElement. If the returned promise resolves to an array of
559
* WebElements, WebDriver will use the first element. For example, to find the
560
* first visible link on a page, you could write:
561
*
562
* var link = driver.findElement(firstVisibleLink);
563
*
564
* function firstVisibleLink(driver) {
565
* var links = driver.findElements(By.tagName('a'));
566
* return promise.filter(links, function(link) {
567
* return link.isDisplayed();
568
* });
569
* }
570
*
571
* @param {!(by.By|Function)} locator The locator to use.
572
* @return {!WebElementPromise} A WebElement that can be used to issue
573
* commands against the located element. If the element is not found, the
574
* element will be invalidated and all scheduled commands aborted.
575
*/
576
findElement(locator) {} // eslint-disable-line
577
578
/**
579
* Search for multiple elements on the page. Refer to the documentation on
580
* {@link #findElement(by)} for information on element locator strategies.
581
*
582
* @param {!(by.By|Function)} locator The locator to use.
583
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
584
* array of WebElements.
585
*/
586
findElements(locator) {} // eslint-disable-line
587
588
/**
589
* Takes a screenshot of the current page. The driver makes the best effort to
590
* return a screenshot of the following, in order of preference:
591
*
592
* 1. Entire page
593
* 2. Current window
594
* 3. Visible portion of the current frame
595
* 4. The entire display containing the browser
596
*
597
* @return {!Promise<string>} A promise that will be resolved to the
598
* screenshot as a base-64 encoded PNG.
599
*/
600
takeScreenshot() {}
601
602
/**
603
* @return {!Options} The options interface for this instance.
604
*/
605
manage() {}
606
607
/**
608
* @return {!Navigation} The navigation interface for this instance.
609
*/
610
navigate() {}
611
612
/**
613
* @return {!TargetLocator} The target locator interface for this
614
* instance.
615
*/
616
switchTo() {}
617
618
/**
619
*
620
* Takes a PDF of the current page. The driver makes a best effort to
621
* return a PDF based on the provided parameters.
622
*
623
* @param {{orientation:(string|undefined),
624
* scale:(number|undefined),
625
* background:(boolean|undefined),
626
* width:(number|undefined),
627
* height:(number|undefined),
628
* top:(number|undefined),
629
* bottom:(number|undefined),
630
* left:(number|undefined),
631
* right:(number|undefined),
632
* shrinkToFit:(boolean|undefined),
633
* pageRanges:(Array|undefined)}} options
634
*/
635
printPage(options) {} // eslint-disable-line
636
}
637
638
/**
639
* @param {!Capabilities} capabilities A capabilities object.
640
* @return {!Capabilities} A copy of the parameter capabilities, omitting
641
* capability names that are not valid W3C names.
642
*/
643
function filterNonW3CCaps(capabilities) {
644
let newCaps = new Capabilities(capabilities)
645
for (let k of newCaps.keys()) {
646
// Any key containing a colon is a vendor-prefixed capability.
647
if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) {
648
newCaps.delete(k)
649
}
650
}
651
return newCaps
652
}
653
654
/**
655
* Each WebDriver instance provides automated control over a browser session.
656
*
657
* @implements {IWebDriver}
658
*/
659
class WebDriver {
660
#script = undefined
661
#network = undefined
662
/**
663
* @param {!(./session.Session|IThenable<!./session.Session>)} session Either
664
* a known session or a promise that will be resolved to a session.
665
* @param {!command.Executor} executor The executor to use when sending
666
* commands to the browser.
667
* @param {(function(this: void): ?)=} onQuit A function to call, if any,
668
* when the session is terminated.
669
*/
670
constructor(session, executor, onQuit = undefined) {
671
/** @private {!Promise<!Session>} */
672
this.session_ = Promise.resolve(session)
673
674
// If session is a rejected promise, add a no-op rejection handler.
675
// This effectively hides setup errors until users attempt to interact
676
// with the session.
677
this.session_.catch(function () {})
678
679
/** @private {!command.Executor} */
680
this.executor_ = executor
681
682
/** @private {input.FileDetector} */
683
this.fileDetector_ = null
684
685
/** @private @const {(function(this: void): ?|undefined)} */
686
this.onQuit_ = onQuit
687
688
/** @private {./virtual_authenticator}*/
689
this.authenticatorId_ = null
690
691
this.pinnedScripts_ = {}
692
}
693
694
/**
695
* Creates a new WebDriver session.
696
*
697
* This function will always return a WebDriver instance. If there is an error
698
* creating the session, such as the aforementioned SessionNotCreatedError,
699
* the driver will have a rejected {@linkplain #getSession session} promise.
700
* This rejection will propagate through any subsequent commands scheduled
701
* on the returned WebDriver instance.
702
*
703
* let required = Capabilities.firefox();
704
* let driver = WebDriver.createSession(executor, {required});
705
*
706
* // If the createSession operation failed, then this command will also
707
* // also fail, propagating the creation failure.
708
* driver.get('http://www.google.com').catch(e => console.log(e));
709
*
710
* @param {!command.Executor} executor The executor to create the new session
711
* with.
712
* @param {!Capabilities} capabilities The desired capabilities for the new
713
* session.
714
* @param {(function(this: void): ?)=} onQuit A callback to invoke when
715
* the newly created session is terminated. This should be used to clean
716
* up any resources associated with the session.
717
* @return {!WebDriver} The driver for the newly created session.
718
*/
719
static createSession(executor, capabilities, onQuit = undefined) {
720
let cmd = new command.Command(command.Name.NEW_SESSION)
721
722
// For W3C remote ends.
723
cmd.setParameter('capabilities', {
724
firstMatch: [{}],
725
alwaysMatch: filterNonW3CCaps(capabilities),
726
})
727
728
let session = executeCommand(executor, cmd)
729
if (typeof onQuit === 'function') {
730
session = session.catch((err) => {
731
return Promise.resolve(onQuit.call(void 0)).then((_) => {
732
throw err
733
})
734
})
735
}
736
return new this(session, executor, onQuit)
737
}
738
739
/** @override */
740
async execute(command) {
741
command.setParameter('sessionId', this.session_)
742
743
let parameters = await toWireValue(command.getParameters())
744
command.setParameters(parameters)
745
let value = await this.executor_.execute(command)
746
return fromWireValue(this, value)
747
}
748
749
/** @override */
750
setFileDetector(detector) {
751
this.fileDetector_ = detector
752
}
753
754
/** @override */
755
getExecutor() {
756
return this.executor_
757
}
758
759
/** @override */
760
getSession() {
761
return this.session_
762
}
763
764
/** @override */
765
getCapabilities() {
766
return this.session_.then((s) => s.getCapabilities())
767
}
768
769
/** @override */
770
quit() {
771
let result = this.execute(new command.Command(command.Name.QUIT))
772
// Delete our session ID when the quit command finishes; this will allow us
773
// to throw an error when attempting to use a driver post-quit.
774
return promise.finally(result, () => {
775
this.session_ = Promise.reject(
776
new error.NoSuchSessionError(
777
'This driver instance does not have a valid session ID ' +
778
'(did you call WebDriver.quit()?) and may no longer be used.',
779
),
780
)
781
782
// Only want the session rejection to bubble if accessed.
783
this.session_.catch(function () {})
784
785
if (this.onQuit_) {
786
return this.onQuit_.call(void 0)
787
}
788
789
// Close the websocket connection on quit
790
// If the websocket connection is not closed,
791
// and we are running CDP sessions against the Selenium Grid,
792
// the node process never exits since the websocket connection is open until the Grid is shutdown.
793
if (this._cdpWsConnection !== undefined) {
794
this._cdpWsConnection.close()
795
}
796
797
// Close the BiDi websocket connection
798
if (this._bidiConnection !== undefined) {
799
this._bidiConnection.close()
800
}
801
})
802
}
803
804
/** @override */
805
actions(options) {
806
return new input.Actions(this, options || undefined)
807
}
808
809
/** @override */
810
executeScript(script, ...args) {
811
if (typeof script === 'function') {
812
script = 'return (' + script + ').apply(null, arguments);'
813
}
814
815
if (script && script instanceof PinnedScript) {
816
return this.execute(
817
new command.Command(command.Name.EXECUTE_SCRIPT)
818
.setParameter('script', script.executionScript())
819
.setParameter('args', args),
820
)
821
}
822
823
return this.execute(
824
new command.Command(command.Name.EXECUTE_SCRIPT).setParameter('script', script).setParameter('args', args),
825
)
826
}
827
828
/** @override */
829
executeAsyncScript(script, ...args) {
830
if (typeof script === 'function') {
831
script = 'return (' + script + ').apply(null, arguments);'
832
}
833
834
if (script && script instanceof PinnedScript) {
835
return this.execute(
836
new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT)
837
.setParameter('script', script.executionScript())
838
.setParameter('args', args),
839
)
840
}
841
842
return this.execute(
843
new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).setParameter('script', script).setParameter('args', args),
844
)
845
}
846
847
/** @override */
848
wait(condition, timeout = 0, message = undefined, pollTimeout = 200) {
849
if (typeof timeout !== 'number' || timeout < 0) {
850
throw TypeError('timeout must be a number >= 0: ' + timeout)
851
}
852
853
if (typeof pollTimeout !== 'number' || pollTimeout < 0) {
854
throw TypeError('pollTimeout must be a number >= 0: ' + pollTimeout)
855
}
856
857
if (promise.isPromise(condition)) {
858
return new Promise((resolve, reject) => {
859
if (!timeout) {
860
resolve(condition)
861
return
862
}
863
864
let start = Date.now()
865
let timer = setTimeout(function () {
866
timer = null
867
try {
868
let timeoutMessage = resolveWaitMessage(message)
869
reject(
870
new error.TimeoutError(
871
`${timeoutMessage}Timed out waiting for promise to resolve after ${Date.now() - start}ms`,
872
),
873
)
874
} catch (ex) {
875
reject(
876
new error.TimeoutError(
877
`${ex.message}\nTimed out waiting for promise to resolve after ${Date.now() - start}ms`,
878
),
879
)
880
}
881
}, timeout)
882
const clearTimer = () => timer && clearTimeout(timer)
883
884
/** @type {!IThenable} */ condition.then(
885
function (value) {
886
clearTimer()
887
resolve(value)
888
},
889
function (error) {
890
clearTimer()
891
reject(error)
892
},
893
)
894
})
895
}
896
897
let fn = /** @type {!Function} */ (condition)
898
if (condition instanceof Condition) {
899
message = message || condition.description()
900
fn = condition.fn
901
}
902
903
if (typeof fn !== 'function') {
904
throw TypeError('Wait condition must be a promise-like object, function, or a ' + 'Condition object')
905
}
906
907
const driver = this
908
909
function evaluateCondition() {
910
return new Promise((resolve, reject) => {
911
try {
912
resolve(fn(driver))
913
} catch (ex) {
914
reject(ex)
915
}
916
})
917
}
918
919
let result = new Promise((resolve, reject) => {
920
const startTime = Date.now()
921
const pollCondition = async () => {
922
evaluateCondition().then(function (value) {
923
const elapsed = Date.now() - startTime
924
if (value) {
925
resolve(value)
926
} else if (timeout && elapsed >= timeout) {
927
try {
928
let timeoutMessage = resolveWaitMessage(message)
929
reject(new error.TimeoutError(`${timeoutMessage}Wait timed out after ${elapsed}ms`))
930
} catch (ex) {
931
reject(new error.TimeoutError(`${ex.message}\nWait timed out after ${elapsed}ms`))
932
}
933
} else {
934
setTimeout(pollCondition, pollTimeout)
935
}
936
}, reject)
937
}
938
pollCondition()
939
})
940
941
if (condition instanceof WebElementCondition) {
942
result = new WebElementPromise(
943
this,
944
result.then(function (value) {
945
if (!(value instanceof WebElement)) {
946
throw TypeError(
947
'WebElementCondition did not resolve to a WebElement: ' + Object.prototype.toString.call(value),
948
)
949
}
950
return value
951
}),
952
)
953
}
954
return result
955
}
956
957
/** @override */
958
sleep(ms) {
959
return new Promise((resolve) => setTimeout(resolve, ms))
960
}
961
962
/** @override */
963
getWindowHandle() {
964
return this.execute(new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE))
965
}
966
967
/** @override */
968
getAllWindowHandles() {
969
return this.execute(new command.Command(command.Name.GET_WINDOW_HANDLES))
970
}
971
972
/** @override */
973
getPageSource() {
974
return this.execute(new command.Command(command.Name.GET_PAGE_SOURCE))
975
}
976
977
/** @override */
978
close() {
979
return this.execute(new command.Command(command.Name.CLOSE))
980
}
981
982
/** @override */
983
get(url) {
984
return this.navigate().to(url)
985
}
986
987
/** @override */
988
getCurrentUrl() {
989
return this.execute(new command.Command(command.Name.GET_CURRENT_URL))
990
}
991
992
/** @override */
993
getTitle() {
994
return this.execute(new command.Command(command.Name.GET_TITLE))
995
}
996
997
/** @override */
998
findElement(locator) {
999
let id
1000
let cmd = null
1001
1002
if (locator instanceof RelativeBy) {
1003
cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall())
1004
} else {
1005
locator = by.checkedLocator(locator)
1006
}
1007
1008
if (typeof locator === 'function') {
1009
id = this.findElementInternal_(locator, this)
1010
return new WebElementPromise(this, id)
1011
} else if (cmd === null) {
1012
cmd = new command.Command(command.Name.FIND_ELEMENT)
1013
.setParameter('using', locator.using)
1014
.setParameter('value', locator.value)
1015
}
1016
1017
id = this.execute(cmd)
1018
if (locator instanceof RelativeBy) {
1019
return this.normalize_(id)
1020
} else {
1021
return new WebElementPromise(this, id)
1022
}
1023
}
1024
1025
/**
1026
* @param {!Function} webElementPromise The webElement in unresolved state
1027
* @return {!Promise<!WebElement>} First single WebElement from array of resolved promises
1028
*/
1029
async normalize_(webElementPromise) {
1030
let result = await webElementPromise
1031
if (result.length === 0) {
1032
throw new NoSuchElementError('Cannot locate an element with provided parameters')
1033
} else {
1034
return result[0]
1035
}
1036
}
1037
1038
/**
1039
* @param {!Function} locatorFn The locator function to use.
1040
* @param {!(WebDriver|WebElement)} context The search context.
1041
* @return {!Promise<!WebElement>} A promise that will resolve to a list of
1042
* WebElements.
1043
* @private
1044
*/
1045
async findElementInternal_(locatorFn, context) {
1046
let result = await locatorFn(context)
1047
if (Array.isArray(result)) {
1048
result = result[0]
1049
}
1050
if (!(result instanceof WebElement)) {
1051
throw new TypeError('Custom locator did not return a WebElement')
1052
}
1053
return result
1054
}
1055
1056
/** @override */
1057
async findElements(locator) {
1058
let cmd = null
1059
if (locator instanceof RelativeBy) {
1060
cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall())
1061
} else {
1062
locator = by.checkedLocator(locator)
1063
}
1064
1065
if (typeof locator === 'function') {
1066
return this.findElementsInternal_(locator, this)
1067
} else if (cmd === null) {
1068
cmd = new command.Command(command.Name.FIND_ELEMENTS)
1069
.setParameter('using', locator.using)
1070
.setParameter('value', locator.value)
1071
}
1072
try {
1073
let res = await this.execute(cmd)
1074
return Array.isArray(res) ? res : []
1075
} catch (ex) {
1076
if (ex instanceof error.NoSuchElementError) {
1077
return []
1078
}
1079
throw ex
1080
}
1081
}
1082
1083
/**
1084
* @param {!Function} locatorFn The locator function to use.
1085
* @param {!(WebDriver|WebElement)} context The search context.
1086
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
1087
* array of WebElements.
1088
* @private
1089
*/
1090
async findElementsInternal_(locatorFn, context) {
1091
const result = await locatorFn(context)
1092
if (result instanceof WebElement) {
1093
return [result]
1094
}
1095
1096
if (!Array.isArray(result)) {
1097
return []
1098
}
1099
1100
return result.filter(function (item) {
1101
return item instanceof WebElement
1102
})
1103
}
1104
1105
/** @override */
1106
takeScreenshot() {
1107
return this.execute(new command.Command(command.Name.SCREENSHOT))
1108
}
1109
1110
setDelayEnabled(enabled) {
1111
return this.execute(new command.Command(command.Name.SET_DELAY_ENABLED).setParameter('enabled', enabled))
1112
}
1113
1114
resetCooldown() {
1115
return this.execute(new command.Command(command.Name.RESET_COOLDOWN))
1116
}
1117
1118
getFederalCredentialManagementDialog() {
1119
return new Dialog(this)
1120
}
1121
1122
/** @override */
1123
manage() {
1124
return new Options(this)
1125
}
1126
1127
/** @override */
1128
navigate() {
1129
return new Navigation(this)
1130
}
1131
1132
/** @override */
1133
switchTo() {
1134
return new TargetLocator(this)
1135
}
1136
1137
script() {
1138
// The Script calls the LogInspector which maintains state of the callbacks.
1139
// Returning a new instance of the same driver will not work while removing callbacks.
1140
if (this.#script === undefined) {
1141
this.#script = new Script(this)
1142
}
1143
1144
return this.#script
1145
}
1146
1147
network() {
1148
// The Network maintains state of the callbacks.
1149
// Returning a new instance of the same driver will not work while removing callbacks.
1150
if (this.#network === undefined) {
1151
this.#network = new Network(this)
1152
}
1153
1154
return this.#network
1155
}
1156
1157
validatePrintPageParams(keys, object) {
1158
let page = {}
1159
let margin = {}
1160
let data
1161
Object.keys(keys).forEach(function (key) {
1162
data = keys[key]
1163
let obj = {
1164
orientation: function () {
1165
object.orientation = data
1166
},
1167
1168
scale: function () {
1169
object.scale = data
1170
},
1171
1172
background: function () {
1173
object.background = data
1174
},
1175
1176
width: function () {
1177
page.width = data
1178
object.page = page
1179
},
1180
1181
height: function () {
1182
page.height = data
1183
object.page = page
1184
},
1185
1186
top: function () {
1187
margin.top = data
1188
object.margin = margin
1189
},
1190
1191
left: function () {
1192
margin.left = data
1193
object.margin = margin
1194
},
1195
1196
bottom: function () {
1197
margin.bottom = data
1198
object.margin = margin
1199
},
1200
1201
right: function () {
1202
margin.right = data
1203
object.margin = margin
1204
},
1205
1206
shrinkToFit: function () {
1207
object.shrinkToFit = data
1208
},
1209
1210
pageRanges: function () {
1211
object.pageRanges = data
1212
},
1213
}
1214
1215
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
1216
throw new error.InvalidArgumentError(`Invalid Argument '${key}'`)
1217
} else {
1218
obj[key]()
1219
}
1220
})
1221
1222
return object
1223
}
1224
1225
/** @override */
1226
printPage(options = {}) {
1227
let keys = options
1228
let params = {}
1229
let resultObj
1230
1231
let self = this
1232
resultObj = self.validatePrintPageParams(keys, params)
1233
1234
return this.execute(new command.Command(command.Name.PRINT_PAGE).setParameters(resultObj))
1235
}
1236
1237
/**
1238
* Creates a new WebSocket connection.
1239
* @return {!Promise<resolved>} A new CDP instance.
1240
*/
1241
async createCDPConnection(target) {
1242
let debuggerUrl = null
1243
1244
const caps = await this.getCapabilities()
1245
1246
if (caps['map_'].get('browserName') === 'firefox') {
1247
throw new Error('CDP support for Firefox is removed. Please switch to WebDriver BiDi.')
1248
}
1249
1250
if (process.env.SELENIUM_REMOTE_URL) {
1251
const host = new URL(process.env.SELENIUM_REMOTE_URL).host
1252
const sessionId = await this.getSession().then((session) => session.getId())
1253
debuggerUrl = `ws://${host}/session/${sessionId}/se/cdp`
1254
} else {
1255
const seCdp = caps['map_'].get('se:cdp')
1256
const vendorInfo = caps['map_'].get('goog:chromeOptions') || caps['map_'].get('ms:edgeOptions') || new Map()
1257
debuggerUrl = seCdp || vendorInfo['debuggerAddress'] || vendorInfo
1258
}
1259
this._wsUrl = await this.getWsUrl(debuggerUrl, target, caps)
1260
return new Promise((resolve, reject) => {
1261
try {
1262
this._cdpWsConnection = new WebSocket(this._wsUrl.replace('localhost', '127.0.0.1'))
1263
this._cdpConnection = new cdp.CdpConnection(this._cdpWsConnection)
1264
} catch (err) {
1265
reject(err)
1266
return
1267
}
1268
1269
this._cdpWsConnection.on('open', async () => {
1270
await this.getCdpTargets()
1271
})
1272
1273
this._cdpWsConnection.on('message', async (message) => {
1274
const params = JSON.parse(message)
1275
if (params.result) {
1276
if (params.result.targetInfos) {
1277
const targets = params.result.targetInfos
1278
const page = targets.find((info) => info.type === 'page')
1279
if (page) {
1280
this.targetID = page.targetId
1281
this._cdpConnection.execute('Target.attachToTarget', { targetId: this.targetID, flatten: true }, null)
1282
} else {
1283
reject('Unable to find Page target.')
1284
}
1285
}
1286
if (params.result.sessionId) {
1287
this.sessionId = params.result.sessionId
1288
this._cdpConnection.sessionId = this.sessionId
1289
resolve(this._cdpConnection)
1290
}
1291
}
1292
})
1293
1294
this._cdpWsConnection.on('error', (error) => {
1295
reject(error)
1296
})
1297
})
1298
}
1299
1300
async getCdpTargets() {
1301
this._cdpConnection.execute('Target.getTargets')
1302
}
1303
1304
/**
1305
* Initiates bidi connection using 'webSocketUrl'
1306
* @returns {BIDI}
1307
*/
1308
async getBidi() {
1309
if (this._bidiConnection === undefined) {
1310
const caps = await this.getCapabilities()
1311
let WebSocketUrl = caps['map_'].get('webSocketUrl')
1312
this._bidiConnection = new BIDI(WebSocketUrl.replace('localhost', '127.0.0.1'))
1313
}
1314
return this._bidiConnection
1315
}
1316
1317
/**
1318
* Retrieves 'webSocketDebuggerUrl' by sending a http request using debugger address
1319
* @param {string} debuggerAddress
1320
* @param target
1321
* @param caps
1322
* @return {string} Returns parsed webSocketDebuggerUrl obtained from the http request
1323
*/
1324
async getWsUrl(debuggerAddress, target, caps) {
1325
if (target && cdpTargets.indexOf(target.toLowerCase()) === -1) {
1326
throw new error.InvalidArgumentError('invalid target value')
1327
}
1328
1329
if (debuggerAddress.match(/\/se\/cdp/)) {
1330
return debuggerAddress
1331
}
1332
1333
let path
1334
if (target === 'page' && caps['map_'].get('browserName') !== 'firefox') {
1335
path = '/json'
1336
} else if (target === 'page' && caps['map_'].get('browserName') === 'firefox') {
1337
path = '/json/list'
1338
} else {
1339
path = '/json/version'
1340
}
1341
1342
let request = new http.Request('GET', path)
1343
let client = new http.HttpClient('http://' + debuggerAddress)
1344
let response = await client.send(request)
1345
1346
if (target.toLowerCase() === 'page') {
1347
return JSON.parse(response.body)[0]['webSocketDebuggerUrl']
1348
} else {
1349
return JSON.parse(response.body)['webSocketDebuggerUrl']
1350
}
1351
}
1352
1353
/**
1354
* Sets a listener for Fetch.authRequired event from CDP
1355
* If event is triggered, it enters username and password
1356
* and allows the test to move forward
1357
* @param {string} username
1358
* @param {string} password
1359
* @param connection CDP Connection
1360
*/
1361
async register(username, password, connection) {
1362
this._cdpWsConnection.on('message', (message) => {
1363
const params = JSON.parse(message)
1364
1365
if (params.method === 'Fetch.authRequired') {
1366
const requestParams = params['params']
1367
connection.execute('Fetch.continueWithAuth', {
1368
requestId: requestParams['requestId'],
1369
authChallengeResponse: {
1370
response: 'ProvideCredentials',
1371
username: username,
1372
password: password,
1373
},
1374
})
1375
} else if (params.method === 'Fetch.requestPaused') {
1376
const requestPausedParams = params['params']
1377
connection.execute('Fetch.continueRequest', {
1378
requestId: requestPausedParams['requestId'],
1379
})
1380
}
1381
})
1382
1383
await connection.execute(
1384
'Fetch.enable',
1385
{
1386
handleAuthRequests: true,
1387
},
1388
null,
1389
)
1390
await connection.execute(
1391
'Network.setCacheDisabled',
1392
{
1393
cacheDisabled: true,
1394
},
1395
null,
1396
)
1397
}
1398
1399
/**
1400
* Handle Network interception requests
1401
* @param connection WebSocket connection to the browser
1402
* @param httpResponse Object representing what we are intercepting
1403
* as well as what should be returned.
1404
* @param callback callback called when we intercept requests.
1405
*/
1406
async onIntercept(connection, httpResponse, callback) {
1407
this._cdpWsConnection.on('message', (message) => {
1408
const params = JSON.parse(message)
1409
if (params.method === 'Fetch.requestPaused') {
1410
const requestPausedParams = params['params']
1411
if (requestPausedParams.request.url == httpResponse.urlToIntercept) {
1412
connection.execute('Fetch.fulfillRequest', {
1413
requestId: requestPausedParams['requestId'],
1414
responseCode: httpResponse.status,
1415
responseHeaders: httpResponse.headers,
1416
body: httpResponse.body,
1417
})
1418
callback()
1419
} else {
1420
connection.execute('Fetch.continueRequest', {
1421
requestId: requestPausedParams['requestId'],
1422
})
1423
}
1424
}
1425
})
1426
1427
await connection.execute('Fetch.enable', {}, null)
1428
await connection.execute(
1429
'Network.setCacheDisabled',
1430
{
1431
cacheDisabled: true,
1432
},
1433
null,
1434
)
1435
}
1436
1437
/**
1438
*
1439
* @param connection
1440
* @param callback
1441
* @returns {Promise<void>}
1442
*/
1443
async onLogEvent(connection, callback) {
1444
this._cdpWsConnection.on('message', (message) => {
1445
const params = JSON.parse(message)
1446
if (params.method === 'Runtime.consoleAPICalled') {
1447
const consoleEventParams = params['params']
1448
let event = {
1449
type: consoleEventParams['type'],
1450
timestamp: new Date(consoleEventParams['timestamp']),
1451
args: consoleEventParams['args'],
1452
}
1453
1454
callback(event)
1455
}
1456
1457
if (params.method === 'Log.entryAdded') {
1458
const logEventParams = params['params']
1459
const logEntry = logEventParams['entry']
1460
let event = {
1461
level: logEntry['level'],
1462
timestamp: new Date(logEntry['timestamp']),
1463
message: logEntry['text'],
1464
}
1465
1466
callback(event)
1467
}
1468
})
1469
await connection.execute('Runtime.enable', {}, null)
1470
}
1471
1472
/**
1473
*
1474
* @param connection
1475
* @param callback
1476
* @returns {Promise<void>}
1477
*/
1478
async onLogException(connection, callback) {
1479
await connection.execute('Runtime.enable', {}, null)
1480
1481
this._cdpWsConnection.on('message', (message) => {
1482
const params = JSON.parse(message)
1483
1484
if (params.method === 'Runtime.exceptionThrown') {
1485
const exceptionEventParams = params['params']
1486
let event = {
1487
exceptionDetails: exceptionEventParams['exceptionDetails'],
1488
timestamp: new Date(exceptionEventParams['timestamp']),
1489
}
1490
1491
callback(event)
1492
}
1493
})
1494
}
1495
1496
/**
1497
* @param connection
1498
* @param callback
1499
* @returns {Promise<void>}
1500
*/
1501
async logMutationEvents(connection, callback) {
1502
await connection.execute('Runtime.enable', {}, null)
1503
await connection.execute('Page.enable', {}, null)
1504
1505
await connection.execute(
1506
'Runtime.addBinding',
1507
{
1508
name: '__webdriver_attribute',
1509
},
1510
null,
1511
)
1512
1513
let mutationListener = ''
1514
try {
1515
// Depending on what is running the code it could appear in 2 different places which is why we try
1516
// here and then the other location
1517
mutationListener = fs
1518
.readFileSync('./javascript/selenium-webdriver/lib/atoms/mutation-listener.js', 'utf-8')
1519
.toString()
1520
} catch {
1521
mutationListener = fs.readFileSync(path.resolve(__dirname, './atoms/mutation-listener.js'), 'utf-8').toString()
1522
}
1523
1524
this.executeScript(mutationListener)
1525
1526
await connection.execute(
1527
'Page.addScriptToEvaluateOnNewDocument',
1528
{
1529
source: mutationListener,
1530
},
1531
null,
1532
)
1533
1534
this._cdpWsConnection.on('message', async (message) => {
1535
const params = JSON.parse(message)
1536
if (params.method === 'Runtime.bindingCalled') {
1537
let payload = JSON.parse(params['params']['payload'])
1538
let elements = await this.findElements({
1539
css: '*[data-__webdriver_id=' + by.escapeCss(payload['target']) + ']',
1540
})
1541
1542
if (elements.length === 0) {
1543
return
1544
}
1545
1546
let event = {
1547
element: elements[0],
1548
attribute_name: payload['name'],
1549
current_value: payload['value'],
1550
old_value: payload['oldValue'],
1551
}
1552
callback(event)
1553
}
1554
})
1555
}
1556
1557
async pinScript(script) {
1558
let pinnedScript = new PinnedScript(script)
1559
let connection
1560
if (Object.is(this._cdpConnection, undefined)) {
1561
connection = await this.createCDPConnection('page')
1562
} else {
1563
connection = this._cdpConnection
1564
}
1565
1566
await connection.execute('Page.enable', {}, null)
1567
1568
await connection.execute(
1569
'Runtime.evaluate',
1570
{
1571
expression: pinnedScript.creationScript(),
1572
},
1573
null,
1574
)
1575
1576
let result = await connection.send('Page.addScriptToEvaluateOnNewDocument', {
1577
source: pinnedScript.creationScript(),
1578
})
1579
1580
pinnedScript.scriptId = result['result']['identifier']
1581
1582
this.pinnedScripts_[pinnedScript.handle] = pinnedScript
1583
1584
return pinnedScript
1585
}
1586
1587
async unpinScript(script) {
1588
if (script && !(script instanceof PinnedScript)) {
1589
throw Error(`Pass valid PinnedScript object. Received: ${script}`)
1590
}
1591
1592
if (script.handle in this.pinnedScripts_) {
1593
let connection
1594
if (Object.is(this._cdpConnection, undefined)) {
1595
connection = this.createCDPConnection('page')
1596
} else {
1597
connection = this._cdpConnection
1598
}
1599
1600
await connection.execute('Page.enable', {}, null)
1601
1602
await connection.execute(
1603
'Runtime.evaluate',
1604
{
1605
expression: script.removalScript(),
1606
},
1607
null,
1608
)
1609
1610
await connection.execute(
1611
'Page.removeScriptToEvaluateOnLoad',
1612
{
1613
identifier: script.scriptId,
1614
},
1615
null,
1616
)
1617
1618
delete this.pinnedScripts_[script.handle]
1619
}
1620
}
1621
1622
/**
1623
*
1624
* @returns The value of authenticator ID added
1625
*/
1626
virtualAuthenticatorId() {
1627
return this.authenticatorId_
1628
}
1629
1630
/**
1631
* Adds a virtual authenticator with the given options.
1632
* @param options VirtualAuthenticatorOptions object to set authenticator options.
1633
*/
1634
async addVirtualAuthenticator(options) {
1635
this.authenticatorId_ = await this.execute(
1636
new command.Command(command.Name.ADD_VIRTUAL_AUTHENTICATOR).setParameters(options.toDict()),
1637
)
1638
}
1639
1640
/**
1641
* Removes a previously added virtual authenticator. The authenticator is no
1642
* longer valid after removal, so no methods may be called.
1643
*/
1644
async removeVirtualAuthenticator() {
1645
await this.execute(
1646
new command.Command(command.Name.REMOVE_VIRTUAL_AUTHENTICATOR).setParameter(
1647
'authenticatorId',
1648
this.authenticatorId_,
1649
),
1650
)
1651
this.authenticatorId_ = null
1652
}
1653
1654
/**
1655
* Injects a credential into the authenticator.
1656
* @param credential Credential to be added
1657
*/
1658
async addCredential(credential) {
1659
credential = credential.toDict()
1660
credential['authenticatorId'] = this.authenticatorId_
1661
await this.execute(new command.Command(command.Name.ADD_CREDENTIAL).setParameters(credential))
1662
}
1663
1664
/**
1665
*
1666
* @returns The list of credentials owned by the authenticator.
1667
*/
1668
async getCredentials() {
1669
let credential_data = await this.execute(
1670
new command.Command(command.Name.GET_CREDENTIALS).setParameter('authenticatorId', this.virtualAuthenticatorId()),
1671
)
1672
var credential_list = []
1673
for (var i = 0; i < credential_data.length; i++) {
1674
credential_list.push(new Credential().fromDict(credential_data[i]))
1675
}
1676
return credential_list
1677
}
1678
1679
/**
1680
* Removes a credential from the authenticator.
1681
* @param credential_id The ID of the credential to be removed.
1682
*/
1683
async removeCredential(credential_id) {
1684
// If credential_id is not a base64url, then convert it to base64url.
1685
if (Array.isArray(credential_id)) {
1686
credential_id = Buffer.from(credential_id).toString('base64url')
1687
}
1688
1689
await this.execute(
1690
new command.Command(command.Name.REMOVE_CREDENTIAL)
1691
.setParameter('credentialId', credential_id)
1692
.setParameter('authenticatorId', this.authenticatorId_),
1693
)
1694
}
1695
1696
/**
1697
* Removes all the credentials from the authenticator.
1698
*/
1699
async removeAllCredentials() {
1700
await this.execute(
1701
new command.Command(command.Name.REMOVE_ALL_CREDENTIALS).setParameter('authenticatorId', this.authenticatorId_),
1702
)
1703
}
1704
1705
/**
1706
* Sets whether the authenticator will simulate success or fail on user verification.
1707
* @param verified true if the authenticator will pass user verification, false otherwise.
1708
*/
1709
async setUserVerified(verified) {
1710
await this.execute(
1711
new command.Command(command.Name.SET_USER_VERIFIED)
1712
.setParameter('authenticatorId', this.authenticatorId_)
1713
.setParameter('isUserVerified', verified),
1714
)
1715
}
1716
1717
async getDownloadableFiles() {
1718
const caps = await this.getCapabilities()
1719
if (!caps['map_'].get('se:downloadsEnabled')) {
1720
throw new error.WebDriverError('Downloads must be enabled in options')
1721
}
1722
1723
return (await this.execute(new command.Command(command.Name.GET_DOWNLOADABLE_FILES))).names
1724
}
1725
1726
async downloadFile(fileName, targetDirectory) {
1727
const caps = await this.getCapabilities()
1728
if (!caps['map_'].get('se:downloadsEnabled')) {
1729
throw new Error('Downloads must be enabled in options')
1730
}
1731
1732
const response = await this.execute(new command.Command(command.Name.DOWNLOAD_FILE).setParameter('name', fileName))
1733
1734
const base64Content = response.contents
1735
1736
if (!targetDirectory.endsWith('/')) {
1737
targetDirectory += '/'
1738
}
1739
1740
fs.mkdirSync(targetDirectory, { recursive: true })
1741
const zipFilePath = path.join(targetDirectory, `${fileName}.zip`)
1742
fs.writeFileSync(zipFilePath, Buffer.from(base64Content, 'base64'))
1743
1744
const zipData = fs.readFileSync(zipFilePath)
1745
await JSZip.loadAsync(zipData)
1746
.then((zip) => {
1747
// Iterate through each file in the zip archive
1748
Object.keys(zip.files).forEach(async (fileName) => {
1749
const fileData = await zip.files[fileName].async('nodebuffer')
1750
fs.writeFileSync(`${targetDirectory}/${fileName}`, fileData)
1751
console.log(`File extracted: ${fileName}`)
1752
})
1753
})
1754
.catch((error) => {
1755
console.error('Error unzipping file:', error)
1756
})
1757
}
1758
1759
async deleteDownloadableFiles() {
1760
const caps = await this.getCapabilities()
1761
if (!caps['map_'].get('se:downloadsEnabled')) {
1762
throw new error.WebDriverError('Downloads must be enabled in options')
1763
}
1764
1765
return await this.execute(new command.Command(command.Name.DELETE_DOWNLOADABLE_FILES))
1766
}
1767
}
1768
1769
/**
1770
* Interface for navigating back and forth in the browser history.
1771
*
1772
* This class should never be instantiated directly. Instead, obtain an instance
1773
* with
1774
*
1775
* webdriver.navigate()
1776
*
1777
* @see WebDriver#navigate()
1778
*/
1779
class Navigation {
1780
/**
1781
* @param {!WebDriver} driver The parent driver.
1782
* @private
1783
*/
1784
constructor(driver) {
1785
/** @private {!WebDriver} */
1786
this.driver_ = driver
1787
}
1788
1789
/**
1790
* Navigates to a new URL.
1791
*
1792
* @param {string} url The URL to navigate to.
1793
* @return {!Promise<void>} A promise that will be resolved when the URL
1794
* has been loaded.
1795
*/
1796
to(url) {
1797
return this.driver_.execute(new command.Command(command.Name.GET).setParameter('url', url))
1798
}
1799
1800
/**
1801
* Moves backwards in the browser history.
1802
*
1803
* @return {!Promise<void>} A promise that will be resolved when the
1804
* navigation event has completed.
1805
*/
1806
back() {
1807
return this.driver_.execute(new command.Command(command.Name.GO_BACK))
1808
}
1809
1810
/**
1811
* Moves forwards in the browser history.
1812
*
1813
* @return {!Promise<void>} A promise that will be resolved when the
1814
* navigation event has completed.
1815
*/
1816
forward() {
1817
return this.driver_.execute(new command.Command(command.Name.GO_FORWARD))
1818
}
1819
1820
/**
1821
* Refreshes the current page.
1822
*
1823
* @return {!Promise<void>} A promise that will be resolved when the
1824
* navigation event has completed.
1825
*/
1826
refresh() {
1827
return this.driver_.execute(new command.Command(command.Name.REFRESH))
1828
}
1829
}
1830
1831
/**
1832
* Provides methods for managing browser and driver state.
1833
*
1834
* This class should never be instantiated directly. Instead, obtain an instance
1835
* with {@linkplain WebDriver#manage() webdriver.manage()}.
1836
*/
1837
class Options {
1838
/**
1839
* @param {!WebDriver} driver The parent driver.
1840
* @private
1841
*/
1842
constructor(driver) {
1843
/** @private {!WebDriver} */
1844
this.driver_ = driver
1845
}
1846
1847
/**
1848
* Adds a cookie.
1849
*
1850
* __Sample Usage:__
1851
*
1852
* // Set a basic cookie.
1853
* driver.manage().addCookie({name: 'foo', value: 'bar'});
1854
*
1855
* // Set a cookie that expires in 10 minutes.
1856
* let expiry = new Date(Date.now() + (10 * 60 * 1000));
1857
* driver.manage().addCookie({name: 'foo', value: 'bar', expiry});
1858
*
1859
* // The cookie expiration may also be specified in seconds since epoch.
1860
* driver.manage().addCookie({
1861
* name: 'foo',
1862
* value: 'bar',
1863
* expiry: Math.floor(Date.now() / 1000)
1864
* });
1865
*
1866
* @param {!Options.Cookie} spec Defines the cookie to add.
1867
* @return {!Promise<void>} A promise that will be resolved
1868
* when the cookie has been added to the page.
1869
* @throws {error.InvalidArgumentError} if any of the cookie parameters are
1870
* invalid.
1871
* @throws {TypeError} if `spec` is not a cookie object.
1872
*/
1873
addCookie({ name, value, path, domain, secure, httpOnly, expiry, sameSite }) {
1874
// We do not allow '=' or ';' in the name.
1875
if (/[;=]/.test(name)) {
1876
throw new error.InvalidArgumentError('Invalid cookie name "' + name + '"')
1877
}
1878
1879
// We do not allow ';' in value.
1880
if (/;/.test(value)) {
1881
throw new error.InvalidArgumentError('Invalid cookie value "' + value + '"')
1882
}
1883
1884
if (typeof expiry === 'number') {
1885
expiry = Math.floor(expiry)
1886
} else if (expiry instanceof Date) {
1887
let date = /** @type {!Date} */ (expiry)
1888
expiry = Math.floor(date.getTime() / 1000)
1889
}
1890
1891
if (sameSite && !['Strict', 'Lax', 'None'].includes(sameSite)) {
1892
throw new error.InvalidArgumentError(
1893
`Invalid sameSite cookie value '${sameSite}'. It should be one of "Lax", "Strict" or "None"`,
1894
)
1895
}
1896
1897
if (sameSite === 'None' && !secure) {
1898
throw new error.InvalidArgumentError('Invalid cookie configuration: SameSite=None must be Secure')
1899
}
1900
1901
return this.driver_.execute(
1902
new command.Command(command.Name.ADD_COOKIE).setParameter('cookie', {
1903
name: name,
1904
value: value,
1905
path: path,
1906
domain: domain,
1907
secure: !!secure,
1908
httpOnly: !!httpOnly,
1909
expiry: expiry,
1910
sameSite: sameSite,
1911
}),
1912
)
1913
}
1914
1915
/**
1916
* Deletes all cookies visible to the current page.
1917
*
1918
* @return {!Promise<void>} A promise that will be resolved
1919
* when all cookies have been deleted.
1920
*/
1921
deleteAllCookies() {
1922
return this.driver_.execute(new command.Command(command.Name.DELETE_ALL_COOKIES))
1923
}
1924
1925
/**
1926
* Deletes the cookie with the given name. This command is a no-op if there is
1927
* no cookie with the given name visible to the current page.
1928
*
1929
* @param {string} name The name of the cookie to delete.
1930
* @return {!Promise<void>} A promise that will be resolved
1931
* when the cookie has been deleted.
1932
*/
1933
deleteCookie(name) {
1934
// Validate the cookie name is non-empty and properly trimmed.
1935
if (!name?.trim()) {
1936
throw new error.InvalidArgumentError('Cookie name cannot be empty')
1937
}
1938
1939
return this.driver_.execute(new command.Command(command.Name.DELETE_COOKIE).setParameter('name', name))
1940
}
1941
1942
/**
1943
* Retrieves all cookies visible to the current page. Each cookie will be
1944
* returned as a JSON object as described by the WebDriver wire protocol.
1945
*
1946
* @return {!Promise<!Array<!Options.Cookie>>} A promise that will be
1947
* resolved with the cookies visible to the current browsing context.
1948
*/
1949
getCookies() {
1950
return this.driver_.execute(new command.Command(command.Name.GET_ALL_COOKIES))
1951
}
1952
1953
/**
1954
* Retrieves the cookie with the given name. Returns null if there is no such
1955
* cookie. The cookie will be returned as a JSON object as described by the
1956
* WebDriver wire protocol.
1957
*
1958
* @param {string} name The name of the cookie to retrieve.
1959
* @throws {InvalidArgumentError} - If the cookie name is empty or invalid.
1960
* @return {!Promise<?Options.Cookie>} A promise that will be resolved
1961
* with the named cookie
1962
* @throws {error.NoSuchCookieError} if there is no such cookie.
1963
*/
1964
async getCookie(name) {
1965
// Validate the cookie name is non-empty and properly trimmed.
1966
if (!name?.trim()) {
1967
throw new error.InvalidArgumentError('Cookie name cannot be empty')
1968
}
1969
1970
try {
1971
const cookie = await this.driver_.execute(new command.Command(command.Name.GET_COOKIE).setParameter('name', name))
1972
return cookie
1973
} catch (err) {
1974
if (!(err instanceof error.UnknownCommandError) && !(err instanceof error.UnsupportedOperationError)) {
1975
throw err
1976
}
1977
return null
1978
}
1979
}
1980
1981
/**
1982
* Fetches the timeouts currently configured for the current session.
1983
*
1984
* @return {!Promise<{script: number,
1985
* pageLoad: number,
1986
* implicit: number}>} A promise that will be
1987
* resolved with the timeouts currently configured for the current
1988
* session.
1989
* @see #setTimeouts()
1990
*/
1991
getTimeouts() {
1992
return this.driver_.execute(new command.Command(command.Name.GET_TIMEOUT))
1993
}
1994
1995
/**
1996
* Sets the timeout durations associated with the current session.
1997
*
1998
* The following timeouts are supported (all timeouts are specified in
1999
* milliseconds):
2000
*
2001
* - `implicit` specifies the maximum amount of time to wait for an element
2002
* locator to succeed when {@linkplain WebDriver#findElement locating}
2003
* {@linkplain WebDriver#findElements elements} on the page.
2004
* Defaults to 0 milliseconds.
2005
*
2006
* - `pageLoad` specifies the maximum amount of time to wait for a page to
2007
* finishing loading. Defaults to 300000 milliseconds.
2008
*
2009
* - `script` specifies the maximum amount of time to wait for an
2010
* {@linkplain WebDriver#executeScript evaluated script} to run. If set to
2011
* `null`, the script timeout will be indefinite.
2012
* Defaults to 30000 milliseconds.
2013
*
2014
* @param {{script: (number|null|undefined),
2015
* pageLoad: (number|null|undefined),
2016
* implicit: (number|null|undefined)}} conf
2017
* The desired timeout configuration.
2018
* @return {!Promise<void>} A promise that will be resolved when the timeouts
2019
* have been set.
2020
* @throws {!TypeError} if an invalid options object is provided.
2021
* @see #getTimeouts()
2022
* @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>
2023
*/
2024
setTimeouts({ script, pageLoad, implicit } = {}) {
2025
let cmd = new command.Command(command.Name.SET_TIMEOUT)
2026
2027
let valid = false
2028
2029
function setParam(key, value) {
2030
if (value === null || typeof value === 'number') {
2031
valid = true
2032
cmd.setParameter(key, value)
2033
} else if (typeof value !== 'undefined') {
2034
throw TypeError('invalid timeouts configuration:' + ` expected "${key}" to be a number, got ${typeof value}`)
2035
}
2036
}
2037
2038
setParam('implicit', implicit)
2039
setParam('pageLoad', pageLoad)
2040
setParam('script', script)
2041
2042
if (valid) {
2043
return this.driver_.execute(cmd).catch(() => {
2044
// Fallback to the legacy method.
2045
let cmds = []
2046
if (typeof script === 'number') {
2047
cmds.push(legacyTimeout(this.driver_, 'script', script))
2048
}
2049
if (typeof implicit === 'number') {
2050
cmds.push(legacyTimeout(this.driver_, 'implicit', implicit))
2051
}
2052
if (typeof pageLoad === 'number') {
2053
cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad))
2054
}
2055
return Promise.all(cmds)
2056
})
2057
}
2058
throw TypeError('no timeouts specified')
2059
}
2060
2061
/**
2062
* @return {!Logs} The interface for managing driver logs.
2063
*/
2064
logs() {
2065
return new Logs(this.driver_)
2066
}
2067
2068
/**
2069
* @return {!Window} The interface for managing the current window.
2070
*/
2071
window() {
2072
return new Window(this.driver_)
2073
}
2074
}
2075
2076
/**
2077
* @param {!WebDriver} driver
2078
* @param {string} type
2079
* @param {number} ms
2080
* @return {!Promise<void>}
2081
*/
2082
function legacyTimeout(driver, type, ms) {
2083
return driver.execute(new command.Command(command.Name.SET_TIMEOUT).setParameter('type', type).setParameter('ms', ms))
2084
}
2085
2086
/**
2087
* A record object describing a browser cookie.
2088
*
2089
* @record
2090
*/
2091
Options.Cookie = function () {}
2092
2093
/**
2094
* The name of the cookie.
2095
*
2096
* @type {string}
2097
*/
2098
Options.Cookie.prototype.name
2099
2100
/**
2101
* The cookie value.
2102
*
2103
* @type {string}
2104
*/
2105
Options.Cookie.prototype.value
2106
2107
/**
2108
* The cookie path. Defaults to "/" when adding a cookie.
2109
*
2110
* @type {(string|undefined)}
2111
*/
2112
Options.Cookie.prototype.path
2113
2114
/**
2115
* The domain the cookie is visible to. Defaults to the current browsing
2116
* context's document's URL when adding a cookie.
2117
*
2118
* @type {(string|undefined)}
2119
*/
2120
Options.Cookie.prototype.domain
2121
2122
/**
2123
* Whether the cookie is a secure cookie. Defaults to false when adding a new
2124
* cookie.
2125
*
2126
* @type {(boolean|undefined)}
2127
*/
2128
Options.Cookie.prototype.secure
2129
2130
/**
2131
* Whether the cookie is an HTTP only cookie. Defaults to false when adding a
2132
* new cookie.
2133
*
2134
* @type {(boolean|undefined)}
2135
*/
2136
Options.Cookie.prototype.httpOnly
2137
2138
/**
2139
* When the cookie expires.
2140
*
2141
* When {@linkplain Options#addCookie() adding a cookie}, this may be specified
2142
* as a {@link Date} object, or in _seconds_ since Unix epoch (January 1, 1970).
2143
*
2144
* The expiry is always returned in seconds since epoch when
2145
* {@linkplain Options#getCookies() retrieving cookies} from the browser.
2146
*
2147
* @type {(!Date|number|undefined)}
2148
*/
2149
Options.Cookie.prototype.expiry
2150
2151
/**
2152
* When the cookie applies to a SameSite policy.
2153
*
2154
* When {@linkplain Options#addCookie() adding a cookie}, this may be specified
2155
* as a {@link string} object which is one of 'Lax', 'Strict' or 'None'.
2156
*
2157
*
2158
* @type {(string|undefined)}
2159
*/
2160
Options.Cookie.prototype.sameSite
2161
2162
/**
2163
* An interface for managing the current window.
2164
*
2165
* This class should never be instantiated directly. Instead, obtain an instance
2166
* with
2167
*
2168
* webdriver.manage().window()
2169
*
2170
* @see WebDriver#manage()
2171
* @see Options#window()
2172
*/
2173
class Window {
2174
/**
2175
* @param {!WebDriver} driver The parent driver.
2176
* @private
2177
*/
2178
constructor(driver) {
2179
/** @private {!WebDriver} */
2180
this.driver_ = driver
2181
/** @private {!Logger} */
2182
this.log_ = logging.getLogger(logging.Type.DRIVER)
2183
}
2184
2185
/**
2186
* Retrieves a rect describing the current top-level window's size and
2187
* position.
2188
*
2189
* @return {!Promise<{x: number, y: number, width: number, height: number}>}
2190
* A promise that will resolve to the window rect of the current window.
2191
*/
2192
getRect() {
2193
return this.driver_.execute(new command.Command(command.Name.GET_WINDOW_RECT))
2194
}
2195
2196
/**
2197
* Sets the current top-level window's size and position. You may update just
2198
* the size by omitting `x` & `y`, or just the position by omitting
2199
* `width` & `height` options.
2200
*
2201
* @param {{x: (number|undefined),
2202
* y: (number|undefined),
2203
* width: (number|undefined),
2204
* height: (number|undefined)}} options
2205
* The desired window size and position.
2206
* @return {!Promise<{x: number, y: number, width: number, height: number}>}
2207
* A promise that will resolve to the current window's updated window
2208
* rect.
2209
*/
2210
setRect({ x, y, width, height }) {
2211
return this.driver_.execute(
2212
new command.Command(command.Name.SET_WINDOW_RECT).setParameters({
2213
x,
2214
y,
2215
width,
2216
height,
2217
}),
2218
)
2219
}
2220
2221
/**
2222
* Maximizes the current window. The exact behavior of this command is
2223
* specific to individual window managers, but typically involves increasing
2224
* the window to the maximum available size without going full-screen.
2225
*
2226
* @return {!Promise<void>} A promise that will be resolved when the command
2227
* has completed.
2228
*/
2229
maximize() {
2230
return this.driver_.execute(
2231
new command.Command(command.Name.MAXIMIZE_WINDOW).setParameter('windowHandle', 'current'),
2232
)
2233
}
2234
2235
/**
2236
* Minimizes the current window. The exact behavior of this command is
2237
* specific to individual window managers, but typically involves hiding
2238
* the window in the system tray.
2239
*
2240
* @return {!Promise<void>} A promise that will be resolved when the command
2241
* has completed.
2242
*/
2243
minimize() {
2244
return this.driver_.execute(new command.Command(command.Name.MINIMIZE_WINDOW))
2245
}
2246
2247
/**
2248
* Invokes the "full screen" operation on the current window. The exact
2249
* behavior of this command is specific to individual window managers, but
2250
* this will typically increase the window size to the size of the physical
2251
* display and hide the browser chrome.
2252
*
2253
* @return {!Promise<void>} A promise that will be resolved when the command
2254
* has completed.
2255
* @see <https://fullscreen.spec.whatwg.org/#fullscreen-an-element>
2256
*/
2257
fullscreen() {
2258
return this.driver_.execute(new command.Command(command.Name.FULLSCREEN_WINDOW))
2259
}
2260
2261
/**
2262
* Gets the width and height of the current window
2263
* @param windowHandle
2264
* @returns {Promise<{width: *, height: *}>}
2265
*/
2266
async getSize(windowHandle = 'current') {
2267
if (windowHandle !== 'current') {
2268
this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)
2269
}
2270
2271
const rect = await this.getRect()
2272
return { height: rect.height, width: rect.width }
2273
}
2274
2275
/**
2276
* Sets the width and height of the current window. (window.resizeTo)
2277
* @param x
2278
* @param y
2279
* @param width
2280
* @param height
2281
* @param windowHandle
2282
* @returns {Promise<void>}
2283
*/
2284
async setSize({ x = 0, y = 0, width = 0, height = 0 }, windowHandle = 'current') {
2285
if (windowHandle !== 'current') {
2286
this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)
2287
}
2288
2289
await this.setRect({ x, y, width, height })
2290
}
2291
}
2292
2293
/**
2294
* Interface for managing WebDriver log records.
2295
*
2296
* This class should never be instantiated directly. Instead, obtain an
2297
* instance with
2298
*
2299
* webdriver.manage().logs()
2300
*
2301
* @see WebDriver#manage()
2302
* @see Options#logs()
2303
*/
2304
class Logs {
2305
/**
2306
* @param {!WebDriver} driver The parent driver.
2307
* @private
2308
*/
2309
constructor(driver) {
2310
/** @private {!WebDriver} */
2311
this.driver_ = driver
2312
}
2313
2314
/**
2315
* Fetches available log entries for the given type.
2316
*
2317
* Note that log buffers are reset after each call, meaning that available
2318
* log entries correspond to those entries not yet returned for a given log
2319
* type. In practice, this means that this call will return the available log
2320
* entries since the last call, or from the start of the session.
2321
*
2322
* @param {!logging.Type} type The desired log type.
2323
* @return {!Promise<!Array.<!logging.Entry>>} A
2324
* promise that will resolve to a list of log entries for the specified
2325
* type.
2326
*/
2327
get(type) {
2328
let cmd = new command.Command(command.Name.GET_LOG).setParameter('type', type)
2329
return this.driver_.execute(cmd).then(function (entries) {
2330
return entries.map(function (entry) {
2331
if (!(entry instanceof logging.Entry)) {
2332
return new logging.Entry(entry['level'], entry['message'], entry['timestamp'], entry['type'])
2333
}
2334
return entry
2335
})
2336
})
2337
}
2338
2339
/**
2340
* Retrieves the log types available to this driver.
2341
* @return {!Promise<!Array<!logging.Type>>} A
2342
* promise that will resolve to a list of available log types.
2343
*/
2344
getAvailableLogTypes() {
2345
return this.driver_.execute(new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES))
2346
}
2347
}
2348
2349
/**
2350
* An interface for changing the focus of the driver to another frame or window.
2351
*
2352
* This class should never be instantiated directly. Instead, obtain an
2353
* instance with
2354
*
2355
* webdriver.switchTo()
2356
*
2357
* @see WebDriver#switchTo()
2358
*/
2359
class TargetLocator {
2360
/**
2361
* @param {!WebDriver} driver The parent driver.
2362
* @private
2363
*/
2364
constructor(driver) {
2365
/** @private {!WebDriver} */
2366
this.driver_ = driver
2367
}
2368
2369
/**
2370
* Locates the DOM element on the current page that corresponds to
2371
* `document.activeElement` or `document.body` if the active element is not
2372
* available.
2373
*
2374
* @return {!WebElementPromise} The active element.
2375
*/
2376
activeElement() {
2377
const id = this.driver_.execute(new command.Command(command.Name.GET_ACTIVE_ELEMENT))
2378
return new WebElementPromise(this.driver_, id)
2379
}
2380
2381
/**
2382
* Switches focus of all future commands to the topmost frame in the current
2383
* window.
2384
*
2385
* @return {!Promise<void>} A promise that will be resolved
2386
* when the driver has changed focus to the default content.
2387
*/
2388
defaultContent() {
2389
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', null))
2390
}
2391
2392
/**
2393
* Changes the focus of all future commands to another frame on the page. The
2394
* target frame may be specified as one of the following:
2395
*
2396
* - A number that specifies a (zero-based) index into [window.frames](
2397
* https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
2398
* - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
2399
* DOM element.
2400
* - The `null` value, to select the topmost frame on the page. Passing `null`
2401
* is the same as calling {@link #defaultContent defaultContent()}.
2402
*
2403
* If the specified frame can not be found, the returned promise will be
2404
* rejected with a {@linkplain error.NoSuchFrameError}.
2405
*
2406
* @param {(number|string|WebElement|null)} id The frame locator.
2407
* @return {!Promise<void>} A promise that will be resolved
2408
* when the driver has changed focus to the specified frame.
2409
*/
2410
frame(id) {
2411
let frameReference = id
2412
if (typeof id === 'string') {
2413
frameReference = this.driver_.findElement({ id }).catch((_) => this.driver_.findElement({ name: id }))
2414
}
2415
2416
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', frameReference))
2417
}
2418
2419
/**
2420
* Changes the focus of all future commands to the parent frame of the
2421
* currently selected frame. This command has no effect if the driver is
2422
* already focused on the top-level browsing context.
2423
*
2424
* @return {!Promise<void>} A promise that will be resolved when the command
2425
* has completed.
2426
*/
2427
parentFrame() {
2428
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME_PARENT))
2429
}
2430
2431
/**
2432
* Changes the focus of all future commands to another window. Windows may be
2433
* specified by their {@code window.name} attribute or by its handle
2434
* (as returned by {@link WebDriver#getWindowHandles}).
2435
*
2436
* If the specified window cannot be found, the returned promise will be
2437
* rejected with a {@linkplain error.NoSuchWindowError}.
2438
*
2439
* @param {string} nameOrHandle The name or window handle of the window to
2440
* switch focus to.
2441
* @return {!Promise<void>} A promise that will be resolved
2442
* when the driver has changed focus to the specified window.
2443
*/
2444
window(nameOrHandle) {
2445
return this.driver_.execute(
2446
new command.Command(command.Name.SWITCH_TO_WINDOW)
2447
// "name" supports the legacy drivers. "handle" is the W3C
2448
// compliant parameter.
2449
.setParameter('name', nameOrHandle)
2450
.setParameter('handle', nameOrHandle),
2451
)
2452
}
2453
2454
/**
2455
* Creates a new browser window and switches the focus for future
2456
* commands of this driver to the new window.
2457
*
2458
* @param {string} typeHint 'window' or 'tab'. The created window is not
2459
* guaranteed to be of the requested type; if the driver does not support
2460
* the requested type, a new browser window will be created of whatever type
2461
* the driver does support.
2462
* @return {!Promise<void>} A promise that will be resolved
2463
* when the driver has changed focus to the new window.
2464
*/
2465
newWindow(typeHint) {
2466
const driver = this.driver_
2467
return this.driver_
2468
.execute(new command.Command(command.Name.SWITCH_TO_NEW_WINDOW).setParameter('type', typeHint))
2469
.then(function (response) {
2470
return driver.switchTo().window(response.handle)
2471
})
2472
}
2473
2474
/**
2475
* Changes focus to the active modal dialog, such as those opened by
2476
* `window.alert()`, `window.confirm()`, and `window.prompt()`. The returned
2477
* promise will be rejected with a
2478
* {@linkplain error.NoSuchAlertError} if there are no open alerts.
2479
*
2480
* @return {!AlertPromise} The open alert.
2481
*/
2482
alert() {
2483
const text = this.driver_.execute(new command.Command(command.Name.GET_ALERT_TEXT))
2484
const driver = this.driver_
2485
return new AlertPromise(
2486
driver,
2487
text.then(function (text) {
2488
return new Alert(driver, text)
2489
}),
2490
)
2491
}
2492
}
2493
2494
//////////////////////////////////////////////////////////////////////////////
2495
//
2496
// WebElement
2497
//
2498
//////////////////////////////////////////////////////////////////////////////
2499
2500
const LEGACY_ELEMENT_ID_KEY = 'ELEMENT'
2501
const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf'
2502
const SHADOW_ROOT_ID_KEY = 'shadow-6066-11e4-a52e-4f735466cecf'
2503
2504
/**
2505
* Represents a DOM element. WebElements can be found by searching from the
2506
* document root using a {@link WebDriver} instance, or by searching
2507
* under another WebElement:
2508
*
2509
* driver.get('http://www.google.com');
2510
* var searchForm = driver.findElement(By.tagName('form'));
2511
* var searchBox = searchForm.findElement(By.name('q'));
2512
* searchBox.sendKeys('webdriver');
2513
*/
2514
class WebElement {
2515
/**
2516
* @param {!WebDriver} driver the parent WebDriver instance for this element.
2517
* @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
2518
* the underlying DOM element.
2519
*/
2520
constructor(driver, id) {
2521
/** @private {!WebDriver} */
2522
this.driver_ = driver
2523
2524
/** @private {!Promise<string>} */
2525
this.id_ = Promise.resolve(id)
2526
2527
/** @private {!Logger} */
2528
this.log_ = logging.getLogger(logging.Type.DRIVER)
2529
}
2530
2531
/**
2532
* @param {string} id The raw ID.
2533
* @param {boolean=} noLegacy Whether to exclude the legacy element key.
2534
* @return {!Object} The element ID for use with WebDriver's wire protocol.
2535
*/
2536
static buildId(id, noLegacy = false) {
2537
return noLegacy ? { [ELEMENT_ID_KEY]: id } : { [ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id }
2538
}
2539
2540
/**
2541
* Extracts the encoded WebElement ID from the object.
2542
*
2543
* @param {?} obj The object to extract the ID from.
2544
* @return {string} the extracted ID.
2545
* @throws {TypeError} if the object is not a valid encoded ID.
2546
*/
2547
static extractId(obj) {
2548
return webElement.extractId(obj)
2549
}
2550
2551
/**
2552
* @param {?} obj the object to test.
2553
* @return {boolean} whether the object is a valid encoded WebElement ID.
2554
*/
2555
static isId(obj) {
2556
return webElement.isId(obj)
2557
}
2558
2559
/**
2560
* Compares two WebElements for equality.
2561
*
2562
* @param {!WebElement} a A WebElement.
2563
* @param {!WebElement} b A WebElement.
2564
* @return {!Promise<boolean>} A promise that will be
2565
* resolved to whether the two WebElements are equal.
2566
*/
2567
static async equals(a, b) {
2568
if (a === b) {
2569
return true
2570
}
2571
return a.driver_.executeScript('return arguments[0] === arguments[1]', a, b)
2572
}
2573
2574
/** @return {!WebDriver} The parent driver for this instance. */
2575
getDriver() {
2576
return this.driver_
2577
}
2578
2579
/**
2580
* @return {!Promise<string>} A promise that resolves to
2581
* the server-assigned opaque ID assigned to this element.
2582
*/
2583
getId() {
2584
return this.id_
2585
}
2586
2587
/**
2588
* @return {!Object} Returns the serialized representation of this WebElement.
2589
*/
2590
[Symbols.serialize]() {
2591
return this.getId().then(WebElement.buildId)
2592
}
2593
2594
/**
2595
* Schedules a command that targets this element with the parent WebDriver
2596
* instance. Will ensure this element's ID is included in the command
2597
* parameters under the "id" key.
2598
*
2599
* @param {!command.Command} command The command to schedule.
2600
* @return {!Promise<T>} A promise that will be resolved with the result.
2601
* @template T
2602
* @see WebDriver#schedule
2603
* @private
2604
*/
2605
execute_(command) {
2606
command.setParameter('id', this)
2607
return this.driver_.execute(command)
2608
}
2609
2610
/**
2611
* Schedule a command to find a descendant of this element. If the element
2612
* cannot be found, the returned promise will be rejected with a
2613
* {@linkplain error.NoSuchElementError NoSuchElementError}.
2614
*
2615
* The search criteria for an element may be defined using one of the static
2616
* factories on the {@link by.By} class, or as a short-hand
2617
* {@link ./by.ByHash} object. For example, the following two statements
2618
* are equivalent:
2619
*
2620
* var e1 = element.findElement(By.id('foo'));
2621
* var e2 = element.findElement({id:'foo'});
2622
*
2623
* You may also provide a custom locator function, which takes as input this
2624
* instance and returns a {@link WebElement}, or a promise that will resolve
2625
* to a WebElement. If the returned promise resolves to an array of
2626
* WebElements, WebDriver will use the first element. For example, to find the
2627
* first visible link on a page, you could write:
2628
*
2629
* var link = element.findElement(firstVisibleLink);
2630
*
2631
* function firstVisibleLink(element) {
2632
* var links = element.findElements(By.tagName('a'));
2633
* return promise.filter(links, function(link) {
2634
* return link.isDisplayed();
2635
* });
2636
* }
2637
*
2638
* @param {!(by.By|Function)} locator The locator strategy to use when
2639
* searching for the element.
2640
* @return {!WebElementPromise} A WebElement that can be used to issue
2641
* commands against the located element. If the element is not found, the
2642
* element will be invalidated and all scheduled commands aborted.
2643
*/
2644
findElement(locator) {
2645
locator = by.checkedLocator(locator)
2646
let id
2647
if (typeof locator === 'function') {
2648
id = this.driver_.findElementInternal_(locator, this)
2649
} else {
2650
let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENT)
2651
.setParameter('using', locator.using)
2652
.setParameter('value', locator.value)
2653
id = this.execute_(cmd)
2654
}
2655
return new WebElementPromise(this.driver_, id)
2656
}
2657
2658
/**
2659
* Locates all the descendants of this element that match the given search
2660
* criteria.
2661
*
2662
* @param {!(by.By|Function)} locator The locator strategy to use when
2663
* searching for the element.
2664
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
2665
* array of WebElements.
2666
*/
2667
async findElements(locator) {
2668
locator = by.checkedLocator(locator)
2669
if (typeof locator === 'function') {
2670
return this.driver_.findElementsInternal_(locator, this)
2671
} else {
2672
let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENTS)
2673
.setParameter('using', locator.using)
2674
.setParameter('value', locator.value)
2675
let result = await this.execute_(cmd)
2676
return Array.isArray(result) ? result : []
2677
}
2678
}
2679
2680
/**
2681
* Clicks on this element.
2682
*
2683
* @return {!Promise<void>} A promise that will be resolved when the click
2684
* command has completed.
2685
*/
2686
click() {
2687
return this.execute_(new command.Command(command.Name.CLICK_ELEMENT))
2688
}
2689
2690
/**
2691
* Types a key sequence on the DOM element represented by this instance.
2692
*
2693
* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
2694
* processed in the key sequence, that key state is toggled until one of the
2695
* following occurs:
2696
*
2697
* - The modifier key is encountered again in the sequence. At this point the
2698
* state of the key is toggled (along with the appropriate keyup/down
2699
* events).
2700
* - The {@link input.Key.NULL} key is encountered in the sequence. When
2701
* this key is encountered, all modifier keys current in the down state are
2702
* released (with accompanying keyup events). The NULL key can be used to
2703
* simulate common keyboard shortcuts:
2704
*
2705
* element.sendKeys("text was",
2706
* Key.CONTROL, "a", Key.NULL,
2707
* "now text is");
2708
* // Alternatively:
2709
* element.sendKeys("text was",
2710
* Key.chord(Key.CONTROL, "a"),
2711
* "now text is");
2712
*
2713
* - The end of the key sequence is encountered. When there are no more keys
2714
* to type, all depressed modifier keys are released (with accompanying
2715
* keyup events).
2716
*
2717
* If this element is a file input ({@code <input type="file">}), the
2718
* specified key sequence should specify the path to the file to attach to
2719
* the element. This is analogous to the user clicking "Browse..." and entering
2720
* the path into the file select dialog.
2721
*
2722
* var form = driver.findElement(By.css('form'));
2723
* var element = form.findElement(By.css('input[type=file]'));
2724
* element.sendKeys('/path/to/file.txt');
2725
* form.submit();
2726
*
2727
* For uploads to function correctly, the entered path must reference a file
2728
* on the _browser's_ machine, not the local machine running this script. When
2729
* running against a remote Selenium server, a {@link input.FileDetector}
2730
* may be used to transparently copy files to the remote machine before
2731
* attempting to upload them in the browser.
2732
*
2733
* __Note:__ On browsers where native keyboard events are not supported
2734
* (e.g. Firefox on OS X), key events will be synthesized. Special
2735
* punctuation keys will be synthesized according to a standard QWERTY en-us
2736
* keyboard layout.
2737
*
2738
* @param {...(number|string|!IThenable<(number|string)>)} args The
2739
* sequence of keys to type. Number keys may be referenced numerically or
2740
* by string (1 or '1'). All arguments will be joined into a single
2741
* sequence.
2742
* @return {!Promise<void>} A promise that will be resolved when all keys
2743
* have been typed.
2744
*/
2745
async sendKeys(...args) {
2746
let keys = []
2747
;(await Promise.all(args)).forEach((key) => {
2748
let type = typeof key
2749
if (type === 'number') {
2750
key = String(key)
2751
} else if (type !== 'string') {
2752
throw TypeError('each key must be a number or string; got ' + type)
2753
}
2754
2755
// The W3C protocol requires keys to be specified as an array where
2756
// each element is a single key.
2757
keys.push(...key)
2758
})
2759
2760
if (!this.driver_.fileDetector_) {
2761
return this.execute_(
2762
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)
2763
.setParameter('text', keys.join(''))
2764
.setParameter('value', keys),
2765
)
2766
}
2767
2768
try {
2769
keys = await this.driver_.fileDetector_.handleFile(this.driver_, keys.join(''))
2770
} catch (ex) {
2771
this.log_.severe('Error trying parse string as a file with file detector; sending keys instead' + ex)
2772
keys = keys.join('')
2773
}
2774
2775
return this.execute_(
2776
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)
2777
.setParameter('text', keys)
2778
.setParameter('value', keys.split('')),
2779
)
2780
}
2781
2782
/**
2783
* Retrieves the element's tag name.
2784
*
2785
* @return {!Promise<string>} A promise that will be resolved with the
2786
* element's tag name.
2787
*/
2788
getTagName() {
2789
return this.execute_(new command.Command(command.Name.GET_ELEMENT_TAG_NAME))
2790
}
2791
2792
/**
2793
* Retrieves the value of a computed style property for this instance. If
2794
* the element inherits the named style from its parent, the parent will be
2795
* queried for its value. Where possible, color values will be converted to
2796
* their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)).
2797
*
2798
* _Warning:_ the value returned will be as the browser interprets it, so
2799
* it may be tricky to form a proper assertion.
2800
*
2801
* @param {string} cssStyleProperty The name of the CSS style property to look
2802
* up.
2803
* @return {!Promise<string>} A promise that will be resolved with the
2804
* requested CSS value.
2805
*/
2806
getCssValue(cssStyleProperty) {
2807
const name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY
2808
return this.execute_(new command.Command(name).setParameter('propertyName', cssStyleProperty))
2809
}
2810
2811
/**
2812
* Retrieves the current value of the given attribute of this element.
2813
* Will return the current value, even if it has been modified after the page
2814
* has been loaded. More exactly, this method will return the value
2815
* of the given attribute, unless that attribute is not present, in which case
2816
* the value of the property with the same name is returned. If neither value
2817
* is set, null is returned (for example, the "value" property of a textarea
2818
* element). The "style" attribute is converted as best can be to a
2819
* text representation with a trailing semicolon. The following are deemed to
2820
* be "boolean" attributes and will return either "true" or null:
2821
*
2822
* async, autofocus, autoplay, checked, compact, complete, controls, declare,
2823
* defaultchecked, defaultselected, defer, disabled, draggable, ended,
2824
* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
2825
* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
2826
* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
2827
* selected, spellcheck, truespeed, willvalidate
2828
*
2829
* Finally, the following commonly mis-capitalized attribute/property names
2830
* are evaluated as expected:
2831
*
2832
* - "class"
2833
* - "readonly"
2834
*
2835
* @param {string} attributeName The name of the attribute to query.
2836
* @return {!Promise<?string>} A promise that will be
2837
* resolved with the attribute's value. The returned value will always be
2838
* either a string or null.
2839
*/
2840
getAttribute(attributeName) {
2841
return this.execute_(new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).setParameter('name', attributeName))
2842
}
2843
2844
/**
2845
* Get the value of the given attribute of the element.
2846
* <p>
2847
* This method, unlike {@link #getAttribute(String)}, returns the value of the attribute with the
2848
* given name but not the property with the same name.
2849
* <p>
2850
* The following are deemed to be "boolean" attributes, and will return either "true" or null:
2851
* <p>
2852
* async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked,
2853
* defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate,
2854
* iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade,
2855
* novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless,
2856
* seeking, selected, truespeed, willvalidate
2857
* <p>
2858
* See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver specification</a>
2859
* for more details.
2860
*
2861
* @param attributeName The name of the attribute.
2862
* @return The attribute's value or null if the value is not set.
2863
*/
2864
2865
getDomAttribute(attributeName) {
2866
return this.execute_(new command.Command(command.Name.GET_DOM_ATTRIBUTE).setParameter('name', attributeName))
2867
}
2868
2869
/**
2870
* Get the given property of the referenced web element
2871
* @param {string} propertyName The name of the attribute to query.
2872
* @return {!Promise<string>} A promise that will be
2873
* resolved with the element's property value
2874
*/
2875
getProperty(propertyName) {
2876
return this.execute_(new command.Command(command.Name.GET_ELEMENT_PROPERTY).setParameter('name', propertyName))
2877
}
2878
2879
/**
2880
* Get the shadow root of the current web element.
2881
* @returns {!Promise<ShadowRoot>} A promise that will be
2882
* resolved with the elements shadow root or rejected
2883
* with {@link NoSuchShadowRootError}
2884
*/
2885
getShadowRoot() {
2886
return this.execute_(new command.Command(command.Name.GET_SHADOW_ROOT))
2887
}
2888
2889
/**
2890
* Get the visible (i.e. not hidden by CSS) innerText of this element,
2891
* including sub-elements, without any leading or trailing whitespace.
2892
*
2893
* @return {!Promise<string>} A promise that will be
2894
* resolved with the element's visible text.
2895
*/
2896
getText() {
2897
return this.execute_(new command.Command(command.Name.GET_ELEMENT_TEXT))
2898
}
2899
2900
/**
2901
* Get the computed WAI-ARIA role of element.
2902
*
2903
* @return {!Promise<string>} A promise that will be
2904
* resolved with the element's computed role.
2905
*/
2906
getAriaRole() {
2907
return this.execute_(new command.Command(command.Name.GET_COMPUTED_ROLE))
2908
}
2909
2910
/**
2911
* Get the computed WAI-ARIA label of element.
2912
*
2913
* @return {!Promise<string>} A promise that will be
2914
* resolved with the element's computed label.
2915
*/
2916
getAccessibleName() {
2917
return this.execute_(new command.Command(command.Name.GET_COMPUTED_LABEL))
2918
}
2919
2920
/**
2921
* Returns an object describing an element's location, in pixels relative to
2922
* the document element, and the element's size in pixels.
2923
*
2924
* @return {!Promise<{width: number, height: number, x: number, y: number}>}
2925
* A promise that will resolve with the element's rect.
2926
*/
2927
getRect() {
2928
return this.execute_(new command.Command(command.Name.GET_ELEMENT_RECT))
2929
}
2930
2931
/**
2932
* Tests whether this element is enabled, as dictated by the `disabled`
2933
* attribute.
2934
*
2935
* @return {!Promise<boolean>} A promise that will be
2936
* resolved with whether this element is currently enabled.
2937
*/
2938
isEnabled() {
2939
return this.execute_(new command.Command(command.Name.IS_ELEMENT_ENABLED))
2940
}
2941
2942
/**
2943
* Tests whether this element is selected.
2944
*
2945
* @return {!Promise<boolean>} A promise that will be
2946
* resolved with whether this element is currently selected.
2947
*/
2948
isSelected() {
2949
return this.execute_(new command.Command(command.Name.IS_ELEMENT_SELECTED))
2950
}
2951
2952
/**
2953
* Submits the form containing this element (or this element if it is itself
2954
* a FORM element). his command is a no-op if the element is not contained in
2955
* a form.
2956
*
2957
* @return {!Promise<void>} A promise that will be resolved
2958
* when the form has been submitted.
2959
*/
2960
submit() {
2961
const script =
2962
'/* submitForm */var form = arguments[0];\n' +
2963
'while (form.nodeName != "FORM" && form.parentNode) {\n' +
2964
' form = form.parentNode;\n' +
2965
'}\n' +
2966
"if (!form) { throw Error('Unable to find containing form element'); }\n" +
2967
"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n" +
2968
"var e = form.ownerDocument.createEvent('Event');\n" +
2969
"e.initEvent('submit', true, true);\n" +
2970
'if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n'
2971
2972
return this.driver_.executeScript(script, this)
2973
}
2974
2975
/**
2976
* Clear the `value` of this element. This command has no effect if the
2977
* underlying DOM element is neither a text INPUT element nor a TEXTAREA
2978
* element.
2979
*
2980
* @return {!Promise<void>} A promise that will be resolved
2981
* when the element has been cleared.
2982
*/
2983
clear() {
2984
return this.execute_(new command.Command(command.Name.CLEAR_ELEMENT))
2985
}
2986
2987
/**
2988
* Test whether this element is currently displayed.
2989
*
2990
* @return {!Promise<boolean>} A promise that will be
2991
* resolved with whether this element is currently visible on the page.
2992
*/
2993
isDisplayed() {
2994
return this.execute_(new command.Command(command.Name.IS_ELEMENT_DISPLAYED))
2995
}
2996
2997
/**
2998
* Take a screenshot of the visible region encompassed by this element's
2999
* bounding rectangle.
3000
*
3001
* @return {!Promise<string>} A promise that will be
3002
* resolved to the screenshot as a base-64 encoded PNG.
3003
*/
3004
takeScreenshot() {
3005
return this.execute_(new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT))
3006
}
3007
}
3008
3009
/**
3010
* WebElementPromise is a promise that will be fulfilled with a WebElement.
3011
* This serves as a forward proxy on WebElement, allowing calls to be
3012
* scheduled without directly on this instance before the underlying
3013
* WebElement has been fulfilled. In other words, the following two statements
3014
* are equivalent:
3015
*
3016
* driver.findElement({id: 'my-button'}).click();
3017
* driver.findElement({id: 'my-button'}).then(function(el) {
3018
* return el.click();
3019
* });
3020
*
3021
* @implements {IThenable<!WebElement>}
3022
* @final
3023
*/
3024
class WebElementPromise extends WebElement {
3025
/**
3026
* @param {!WebDriver} driver The parent WebDriver instance for this
3027
* element.
3028
* @param {!Promise<!WebElement>} el A promise
3029
* that will resolve to the promised element.
3030
*/
3031
constructor(driver, el) {
3032
super(driver, 'unused')
3033
3034
/** @override */
3035
this.then = el.then.bind(el)
3036
3037
/** @override */
3038
this.catch = el.catch.bind(el)
3039
3040
/**
3041
* Defers returning the element ID until the wrapped WebElement has been
3042
* resolved.
3043
* @override
3044
*/
3045
this.getId = function () {
3046
return el.then(function (el) {
3047
return el.getId()
3048
})
3049
}
3050
}
3051
}
3052
3053
//////////////////////////////////////////////////////////////////////////////
3054
//
3055
// ShadowRoot
3056
//
3057
//////////////////////////////////////////////////////////////////////////////
3058
3059
/**
3060
* Represents a ShadowRoot of a {@link WebElement}. Provides functions to
3061
* retrieve elements that live in the DOM below the ShadowRoot.
3062
*/
3063
class ShadowRoot {
3064
constructor(driver, id) {
3065
this.driver_ = driver
3066
this.id_ = id
3067
}
3068
3069
/**
3070
* Extracts the encoded ShadowRoot ID from the object.
3071
*
3072
* @param {?} obj The object to extract the ID from.
3073
* @return {string} the extracted ID.
3074
* @throws {TypeError} if the object is not a valid encoded ID.
3075
*/
3076
static extractId(obj) {
3077
if (obj && typeof obj === 'object') {
3078
if (typeof obj[SHADOW_ROOT_ID_KEY] === 'string') {
3079
return obj[SHADOW_ROOT_ID_KEY]
3080
}
3081
}
3082
throw new TypeError('object is not a ShadowRoot ID')
3083
}
3084
3085
/**
3086
* @param {?} obj the object to test.
3087
* @return {boolean} whether the object is a valid encoded WebElement ID.
3088
*/
3089
static isId(obj) {
3090
return obj && typeof obj === 'object' && typeof obj[SHADOW_ROOT_ID_KEY] === 'string'
3091
}
3092
3093
/**
3094
* @return {!Object} Returns the serialized representation of this ShadowRoot.
3095
*/
3096
[Symbols.serialize]() {
3097
return this.getId()
3098
}
3099
3100
/**
3101
* Schedules a command that targets this element with the parent WebDriver
3102
* instance. Will ensure this element's ID is included in the command
3103
* parameters under the "id" key.
3104
*
3105
* @param {!command.Command} command The command to schedule.
3106
* @return {!Promise<T>} A promise that will be resolved with the result.
3107
* @template T
3108
* @see WebDriver#schedule
3109
* @private
3110
*/
3111
execute_(command) {
3112
command.setParameter('id', this)
3113
return this.driver_.execute(command)
3114
}
3115
3116
/**
3117
* Schedule a command to find a descendant of this ShadowROot. If the element
3118
* cannot be found, the returned promise will be rejected with a
3119
* {@linkplain error.NoSuchElementError NoSuchElementError}.
3120
*
3121
* The search criteria for an element may be defined using one of the static
3122
* factories on the {@link by.By} class, or as a short-hand
3123
* {@link ./by.ByHash} object. For example, the following two statements
3124
* are equivalent:
3125
*
3126
* var e1 = shadowroot.findElement(By.id('foo'));
3127
* var e2 = shadowroot.findElement({id:'foo'});
3128
*
3129
* You may also provide a custom locator function, which takes as input this
3130
* instance and returns a {@link WebElement}, or a promise that will resolve
3131
* to a WebElement. If the returned promise resolves to an array of
3132
* WebElements, WebDriver will use the first element. For example, to find the
3133
* first visible link on a page, you could write:
3134
*
3135
* var link = element.findElement(firstVisibleLink);
3136
*
3137
* function firstVisibleLink(shadowRoot) {
3138
* var links = shadowRoot.findElements(By.tagName('a'));
3139
* return promise.filter(links, function(link) {
3140
* return link.isDisplayed();
3141
* });
3142
* }
3143
*
3144
* @param {!(by.By|Function)} locator The locator strategy to use when
3145
* searching for the element.
3146
* @return {!WebElementPromise} A WebElement that can be used to issue
3147
* commands against the located element. If the element is not found, the
3148
* element will be invalidated and all scheduled commands aborted.
3149
*/
3150
findElement(locator) {
3151
locator = by.checkedLocator(locator)
3152
let id
3153
if (typeof locator === 'function') {
3154
id = this.driver_.findElementInternal_(locator, this)
3155
} else {
3156
let cmd = new command.Command(command.Name.FIND_ELEMENT_FROM_SHADOWROOT)
3157
.setParameter('using', locator.using)
3158
.setParameter('value', locator.value)
3159
id = this.execute_(cmd)
3160
}
3161
return new ShadowRootPromise(this.driver_, id)
3162
}
3163
3164
/**
3165
* Locates all the descendants of this element that match the given search
3166
* criteria.
3167
*
3168
* @param {!(by.By|Function)} locator The locator strategy to use when
3169
* searching for the element.
3170
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
3171
* array of WebElements.
3172
*/
3173
async findElements(locator) {
3174
locator = by.checkedLocator(locator)
3175
if (typeof locator === 'function') {
3176
return this.driver_.findElementsInternal_(locator, this)
3177
} else {
3178
let cmd = new command.Command(command.Name.FIND_ELEMENTS_FROM_SHADOWROOT)
3179
.setParameter('using', locator.using)
3180
.setParameter('value', locator.value)
3181
let result = await this.execute_(cmd)
3182
return Array.isArray(result) ? result : []
3183
}
3184
}
3185
3186
getId() {
3187
return this.id_
3188
}
3189
}
3190
3191
/**
3192
* ShadowRootPromise is a promise that will be fulfilled with a WebElement.
3193
* This serves as a forward proxy on ShadowRoot, allowing calls to be
3194
* scheduled without directly on this instance before the underlying
3195
* ShadowRoot has been fulfilled.
3196
*
3197
* @implements { IThenable<!ShadowRoot>}
3198
* @final
3199
*/
3200
class ShadowRootPromise extends ShadowRoot {
3201
/**
3202
* @param {!WebDriver} driver The parent WebDriver instance for this
3203
* element.
3204
* @param {!Promise<!ShadowRoot>} shadow A promise
3205
* that will resolve to the promised element.
3206
*/
3207
constructor(driver, shadow) {
3208
super(driver, 'unused')
3209
3210
/** @override */
3211
this.then = shadow.then.bind(shadow)
3212
3213
/** @override */
3214
this.catch = shadow.catch.bind(shadow)
3215
3216
/**
3217
* Defers returning the ShadowRoot ID until the wrapped WebElement has been
3218
* resolved.
3219
* @override
3220
*/
3221
this.getId = function () {
3222
return shadow.then(function (shadow) {
3223
return shadow.getId()
3224
})
3225
}
3226
}
3227
}
3228
3229
//////////////////////////////////////////////////////////////////////////////
3230
//
3231
// Alert
3232
//
3233
//////////////////////////////////////////////////////////////////////////////
3234
3235
/**
3236
* Represents a modal dialog such as {@code alert}, {@code confirm}, or
3237
* {@code prompt}. Provides functions to retrieve the message displayed with
3238
* the alert, accept or dismiss the alert, and set the response text (in the
3239
* case of {@code prompt}).
3240
*/
3241
class Alert {
3242
/**
3243
* @param {!WebDriver} driver The driver controlling the browser this alert
3244
* is attached to.
3245
* @param {string} text The message text displayed with this alert.
3246
*/
3247
constructor(driver, text) {
3248
/** @private {!WebDriver} */
3249
this.driver_ = driver
3250
3251
/** @private {!Promise<string>} */
3252
this.text_ = Promise.resolve(text)
3253
}
3254
3255
/**
3256
* Retrieves the message text displayed with this alert. For instance, if the
3257
* alert were opened with alert("hello"), then this would return "hello".
3258
*
3259
* @return {!Promise<string>} A promise that will be
3260
* resolved to the text displayed with this alert.
3261
*/
3262
getText() {
3263
return this.text_
3264
}
3265
3266
/**
3267
* Accepts this alert.
3268
*
3269
* @return {!Promise<void>} A promise that will be resolved
3270
* when this command has completed.
3271
*/
3272
accept() {
3273
return this.driver_.execute(new command.Command(command.Name.ACCEPT_ALERT))
3274
}
3275
3276
/**
3277
* Dismisses this alert.
3278
*
3279
* @return {!Promise<void>} A promise that will be resolved
3280
* when this command has completed.
3281
*/
3282
dismiss() {
3283
return this.driver_.execute(new command.Command(command.Name.DISMISS_ALERT))
3284
}
3285
3286
/**
3287
* Sets the response text on this alert. This command will return an error if
3288
* the underlying alert does not support response text (e.g. window.alert and
3289
* window.confirm).
3290
*
3291
* @param {string} text The text to set.
3292
* @return {!Promise<void>} A promise that will be resolved
3293
* when this command has completed.
3294
*/
3295
sendKeys(text) {
3296
return this.driver_.execute(new command.Command(command.Name.SET_ALERT_TEXT).setParameter('text', text))
3297
}
3298
}
3299
3300
/**
3301
* AlertPromise is a promise that will be fulfilled with an Alert. This promise
3302
* serves as a forward proxy on an Alert, allowing calls to be scheduled
3303
* directly on this instance before the underlying Alert has been fulfilled. In
3304
* other words, the following two statements are equivalent:
3305
*
3306
* driver.switchTo().alert().dismiss();
3307
* driver.switchTo().alert().then(function(alert) {
3308
* return alert.dismiss();
3309
* });
3310
*
3311
* @implements {IThenable<!Alert>}
3312
* @final
3313
*/
3314
class AlertPromise extends Alert {
3315
/**
3316
* @param {!WebDriver} driver The driver controlling the browser this
3317
* alert is attached to.
3318
* @param {!Promise<!Alert>} alert A thenable
3319
* that will be fulfilled with the promised alert.
3320
*/
3321
constructor(driver, alert) {
3322
super(driver, 'unused')
3323
3324
/** @override */
3325
this.then = alert.then.bind(alert)
3326
3327
/** @override */
3328
this.catch = alert.catch.bind(alert)
3329
3330
/**
3331
* Defer returning text until the promised alert has been resolved.
3332
* @override
3333
*/
3334
this.getText = function () {
3335
return alert.then(function (alert) {
3336
return alert.getText()
3337
})
3338
}
3339
3340
/**
3341
* Defers action until the alert has been located.
3342
* @override
3343
*/
3344
this.accept = function () {
3345
return alert.then(function (alert) {
3346
return alert.accept()
3347
})
3348
}
3349
3350
/**
3351
* Defers action until the alert has been located.
3352
* @override
3353
*/
3354
this.dismiss = function () {
3355
return alert.then(function (alert) {
3356
return alert.dismiss()
3357
})
3358
}
3359
3360
/**
3361
* Defers action until the alert has been located.
3362
* @override
3363
*/
3364
this.sendKeys = function (text) {
3365
return alert.then(function (alert) {
3366
return alert.sendKeys(text)
3367
})
3368
}
3369
}
3370
}
3371
3372
// PUBLIC API
3373
3374
module.exports = {
3375
Alert,
3376
AlertPromise,
3377
Condition,
3378
Logs,
3379
Navigation,
3380
Options,
3381
ShadowRoot,
3382
TargetLocator,
3383
IWebDriver,
3384
WebDriver,
3385
WebElement,
3386
WebElementCondition,
3387
WebElementPromise,
3388
Window,
3389
}
3390
3391