Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/javascript/selenium-webdriver/lib/webdriver.js
4011 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.send('Fetch.enable', {
1384
handleAuthRequests: true,
1385
})
1386
await connection.send('Network.setCacheDisabled', {
1387
cacheDisabled: true,
1388
})
1389
}
1390
1391
/**
1392
* Handle Network interception requests
1393
* @param connection WebSocket connection to the browser
1394
* @param httpResponse Object representing what we are intercepting
1395
* as well as what should be returned.
1396
* @param callback callback called when we intercept requests.
1397
*/
1398
async onIntercept(connection, httpResponse, callback) {
1399
this._cdpWsConnection.on('message', (message) => {
1400
const params = JSON.parse(message)
1401
if (params.method === 'Fetch.requestPaused') {
1402
const requestPausedParams = params['params']
1403
if (requestPausedParams.request.url == httpResponse.urlToIntercept) {
1404
connection.execute('Fetch.fulfillRequest', {
1405
requestId: requestPausedParams['requestId'],
1406
responseCode: httpResponse.status,
1407
responseHeaders: httpResponse.headers,
1408
body: httpResponse.body,
1409
})
1410
callback()
1411
} else {
1412
connection.execute('Fetch.continueRequest', {
1413
requestId: requestPausedParams['requestId'],
1414
})
1415
}
1416
}
1417
})
1418
1419
await connection.execute('Fetch.enable', {}, null)
1420
await connection.execute(
1421
'Network.setCacheDisabled',
1422
{
1423
cacheDisabled: true,
1424
},
1425
null,
1426
)
1427
}
1428
1429
/**
1430
*
1431
* @param connection
1432
* @param callback
1433
* @returns {Promise<void>}
1434
*/
1435
async onLogEvent(connection, callback) {
1436
this._cdpWsConnection.on('message', (message) => {
1437
const params = JSON.parse(message)
1438
if (params.method === 'Runtime.consoleAPICalled') {
1439
const consoleEventParams = params['params']
1440
let event = {
1441
type: consoleEventParams['type'],
1442
timestamp: new Date(consoleEventParams['timestamp']),
1443
args: consoleEventParams['args'],
1444
}
1445
1446
callback(event)
1447
}
1448
1449
if (params.method === 'Log.entryAdded') {
1450
const logEventParams = params['params']
1451
const logEntry = logEventParams['entry']
1452
let event = {
1453
level: logEntry['level'],
1454
timestamp: new Date(logEntry['timestamp']),
1455
message: logEntry['text'],
1456
}
1457
1458
callback(event)
1459
}
1460
})
1461
await connection.execute('Runtime.enable', {}, null)
1462
}
1463
1464
/**
1465
*
1466
* @param connection
1467
* @param callback
1468
* @returns {Promise<void>}
1469
*/
1470
async onLogException(connection, callback) {
1471
await connection.execute('Runtime.enable', {}, null)
1472
1473
this._cdpWsConnection.on('message', (message) => {
1474
const params = JSON.parse(message)
1475
1476
if (params.method === 'Runtime.exceptionThrown') {
1477
const exceptionEventParams = params['params']
1478
let event = {
1479
exceptionDetails: exceptionEventParams['exceptionDetails'],
1480
timestamp: new Date(exceptionEventParams['timestamp']),
1481
}
1482
1483
callback(event)
1484
}
1485
})
1486
}
1487
1488
/**
1489
* @param connection
1490
* @param callback
1491
* @returns {Promise<void>}
1492
*/
1493
async logMutationEvents(connection, callback) {
1494
await connection.execute('Runtime.enable', {}, null)
1495
await connection.execute('Page.enable', {}, null)
1496
1497
await connection.execute(
1498
'Runtime.addBinding',
1499
{
1500
name: '__webdriver_attribute',
1501
},
1502
null,
1503
)
1504
1505
let mutationListener = ''
1506
try {
1507
// Depending on what is running the code it could appear in 2 different places which is why we try
1508
// here and then the other location
1509
mutationListener = fs
1510
.readFileSync('./javascript/selenium-webdriver/lib/atoms/mutation-listener.js', 'utf-8')
1511
.toString()
1512
} catch {
1513
mutationListener = fs.readFileSync(path.resolve(__dirname, './atoms/mutation-listener.js'), 'utf-8').toString()
1514
}
1515
1516
this.executeScript(mutationListener)
1517
1518
await connection.execute(
1519
'Page.addScriptToEvaluateOnNewDocument',
1520
{
1521
source: mutationListener,
1522
},
1523
null,
1524
)
1525
1526
this._cdpWsConnection.on('message', async (message) => {
1527
const params = JSON.parse(message)
1528
if (params.method === 'Runtime.bindingCalled') {
1529
let payload = JSON.parse(params['params']['payload'])
1530
let elements = await this.findElements({
1531
css: '*[data-__webdriver_id=' + by.escapeCss(payload['target']) + ']',
1532
})
1533
1534
if (elements.length === 0) {
1535
return
1536
}
1537
1538
let event = {
1539
element: elements[0],
1540
attribute_name: payload['name'],
1541
current_value: payload['value'],
1542
old_value: payload['oldValue'],
1543
}
1544
callback(event)
1545
}
1546
})
1547
}
1548
1549
async pinScript(script) {
1550
let pinnedScript = new PinnedScript(script)
1551
let connection
1552
if (Object.is(this._cdpConnection, undefined)) {
1553
connection = await this.createCDPConnection('page')
1554
} else {
1555
connection = this._cdpConnection
1556
}
1557
1558
await connection.send('Page.enable', {})
1559
1560
await connection.send('Runtime.evaluate', {
1561
expression: pinnedScript.creationScript(),
1562
})
1563
1564
let result = await connection.send('Page.addScriptToEvaluateOnNewDocument', {
1565
source: pinnedScript.creationScript(),
1566
})
1567
1568
pinnedScript.scriptId = result['result']['identifier']
1569
1570
this.pinnedScripts_[pinnedScript.handle] = pinnedScript
1571
1572
return pinnedScript
1573
}
1574
1575
async unpinScript(script) {
1576
if (script && !(script instanceof PinnedScript)) {
1577
throw Error(`Pass valid PinnedScript object. Received: ${script}`)
1578
}
1579
1580
if (script.handle in this.pinnedScripts_) {
1581
let connection
1582
if (Object.is(this._cdpConnection, undefined)) {
1583
connection = this.createCDPConnection('page')
1584
} else {
1585
connection = this._cdpConnection
1586
}
1587
1588
await connection.send('Page.enable', {})
1589
1590
await connection.send('Runtime.evaluate', {
1591
expression: script.removalScript(),
1592
})
1593
1594
await connection.send('Page.removeScriptToEvaluateOnLoad', {
1595
identifier: script.scriptId,
1596
})
1597
1598
delete this.pinnedScripts_[script.handle]
1599
}
1600
}
1601
1602
/**
1603
*
1604
* @returns The value of authenticator ID added
1605
*/
1606
virtualAuthenticatorId() {
1607
return this.authenticatorId_
1608
}
1609
1610
/**
1611
* Adds a virtual authenticator with the given options.
1612
* @param options VirtualAuthenticatorOptions object to set authenticator options.
1613
*/
1614
async addVirtualAuthenticator(options) {
1615
this.authenticatorId_ = await this.execute(
1616
new command.Command(command.Name.ADD_VIRTUAL_AUTHENTICATOR).setParameters(options.toDict()),
1617
)
1618
}
1619
1620
/**
1621
* Removes a previously added virtual authenticator. The authenticator is no
1622
* longer valid after removal, so no methods may be called.
1623
*/
1624
async removeVirtualAuthenticator() {
1625
await this.execute(
1626
new command.Command(command.Name.REMOVE_VIRTUAL_AUTHENTICATOR).setParameter(
1627
'authenticatorId',
1628
this.authenticatorId_,
1629
),
1630
)
1631
this.authenticatorId_ = null
1632
}
1633
1634
/**
1635
* Injects a credential into the authenticator.
1636
* @param credential Credential to be added
1637
*/
1638
async addCredential(credential) {
1639
credential = credential.toDict()
1640
credential['authenticatorId'] = this.authenticatorId_
1641
await this.execute(new command.Command(command.Name.ADD_CREDENTIAL).setParameters(credential))
1642
}
1643
1644
/**
1645
*
1646
* @returns The list of credentials owned by the authenticator.
1647
*/
1648
async getCredentials() {
1649
let credential_data = await this.execute(
1650
new command.Command(command.Name.GET_CREDENTIALS).setParameter('authenticatorId', this.virtualAuthenticatorId()),
1651
)
1652
var credential_list = []
1653
for (var i = 0; i < credential_data.length; i++) {
1654
credential_list.push(new Credential().fromDict(credential_data[i]))
1655
}
1656
return credential_list
1657
}
1658
1659
/**
1660
* Removes a credential from the authenticator.
1661
* @param credential_id The ID of the credential to be removed.
1662
*/
1663
async removeCredential(credential_id) {
1664
// If credential_id is not a base64url, then convert it to base64url.
1665
if (Array.isArray(credential_id)) {
1666
credential_id = Buffer.from(credential_id).toString('base64url')
1667
}
1668
1669
await this.execute(
1670
new command.Command(command.Name.REMOVE_CREDENTIAL)
1671
.setParameter('credentialId', credential_id)
1672
.setParameter('authenticatorId', this.authenticatorId_),
1673
)
1674
}
1675
1676
/**
1677
* Removes all the credentials from the authenticator.
1678
*/
1679
async removeAllCredentials() {
1680
await this.execute(
1681
new command.Command(command.Name.REMOVE_ALL_CREDENTIALS).setParameter('authenticatorId', this.authenticatorId_),
1682
)
1683
}
1684
1685
/**
1686
* Sets whether the authenticator will simulate success or fail on user verification.
1687
* @param verified true if the authenticator will pass user verification, false otherwise.
1688
*/
1689
async setUserVerified(verified) {
1690
await this.execute(
1691
new command.Command(command.Name.SET_USER_VERIFIED)
1692
.setParameter('authenticatorId', this.authenticatorId_)
1693
.setParameter('isUserVerified', verified),
1694
)
1695
}
1696
1697
async getDownloadableFiles() {
1698
const caps = await this.getCapabilities()
1699
if (!caps['map_'].get('se:downloadsEnabled')) {
1700
throw new error.WebDriverError('Downloads must be enabled in options')
1701
}
1702
1703
return (await this.execute(new command.Command(command.Name.GET_DOWNLOADABLE_FILES))).names
1704
}
1705
1706
async downloadFile(fileName, targetDirectory) {
1707
const caps = await this.getCapabilities()
1708
if (!caps['map_'].get('se:downloadsEnabled')) {
1709
throw new Error('Downloads must be enabled in options')
1710
}
1711
1712
const response = await this.execute(new command.Command(command.Name.DOWNLOAD_FILE).setParameter('name', fileName))
1713
1714
const base64Content = response.contents
1715
1716
if (!targetDirectory.endsWith('/')) {
1717
targetDirectory += '/'
1718
}
1719
1720
fs.mkdirSync(targetDirectory, { recursive: true })
1721
const zipFilePath = path.join(targetDirectory, `${fileName}.zip`)
1722
fs.writeFileSync(zipFilePath, Buffer.from(base64Content, 'base64'))
1723
1724
const zipData = fs.readFileSync(zipFilePath)
1725
await JSZip.loadAsync(zipData)
1726
.then((zip) => {
1727
// Iterate through each file in the zip archive
1728
Object.keys(zip.files).forEach(async (fileName) => {
1729
const fileData = await zip.files[fileName].async('nodebuffer')
1730
fs.writeFileSync(`${targetDirectory}/${fileName}`, fileData)
1731
console.log(`File extracted: ${fileName}`)
1732
})
1733
})
1734
.catch((error) => {
1735
console.error('Error unzipping file:', error)
1736
})
1737
}
1738
1739
async deleteDownloadableFiles() {
1740
const caps = await this.getCapabilities()
1741
if (!caps['map_'].get('se:downloadsEnabled')) {
1742
throw new error.WebDriverError('Downloads must be enabled in options')
1743
}
1744
1745
return await this.execute(new command.Command(command.Name.DELETE_DOWNLOADABLE_FILES))
1746
}
1747
1748
/**
1749
* Fires a custom session event to the remote server event bus.
1750
*
1751
* This allows test code to trigger server-side utilities that subscribe to the event bus.
1752
*
1753
* @param {string} eventType The type of event (e.g., "test:failed", "log:collect").
1754
* @param {Object=} payload Optional data to include with the event.
1755
* @return {!Promise<Object>} A promise that resolves to the response containing
1756
* success status, event type, and timestamp.
1757
*
1758
* @example
1759
* // Fire a simple event
1760
* await driver.fireSessionEvent('test:started');
1761
*
1762
* @example
1763
* // Fire an event with payload
1764
* await driver.fireSessionEvent('test:failed', {
1765
* testName: 'LoginTest',
1766
* error: 'Element not found'
1767
* });
1768
*/
1769
async fireSessionEvent(eventType, payload = null) {
1770
if (!eventType || typeof eventType !== 'string') {
1771
throw new error.InvalidArgumentError('eventType must be a non-empty string')
1772
}
1773
const cmd = new command.Command(command.Name.FIRE_SESSION_EVENT).setParameter('eventType', eventType)
1774
if (payload) {
1775
cmd.setParameter('payload', payload)
1776
}
1777
return await this.execute(cmd)
1778
}
1779
}
1780
1781
/**
1782
* Interface for navigating back and forth in the browser history.
1783
*
1784
* This class should never be instantiated directly. Instead, obtain an instance
1785
* with
1786
*
1787
* webdriver.navigate()
1788
*
1789
* @see WebDriver#navigate()
1790
*/
1791
class Navigation {
1792
/**
1793
* @param {!WebDriver} driver The parent driver.
1794
* @private
1795
*/
1796
constructor(driver) {
1797
/** @private {!WebDriver} */
1798
this.driver_ = driver
1799
}
1800
1801
/**
1802
* Navigates to a new URL.
1803
*
1804
* @param {string} url The URL to navigate to.
1805
* @return {!Promise<void>} A promise that will be resolved when the URL
1806
* has been loaded.
1807
*/
1808
to(url) {
1809
return this.driver_.execute(new command.Command(command.Name.GET).setParameter('url', url))
1810
}
1811
1812
/**
1813
* Moves backwards in the browser history.
1814
*
1815
* @return {!Promise<void>} A promise that will be resolved when the
1816
* navigation event has completed.
1817
*/
1818
back() {
1819
return this.driver_.execute(new command.Command(command.Name.GO_BACK))
1820
}
1821
1822
/**
1823
* Moves forwards in the browser history.
1824
*
1825
* @return {!Promise<void>} A promise that will be resolved when the
1826
* navigation event has completed.
1827
*/
1828
forward() {
1829
return this.driver_.execute(new command.Command(command.Name.GO_FORWARD))
1830
}
1831
1832
/**
1833
* Refreshes the current page.
1834
*
1835
* @return {!Promise<void>} A promise that will be resolved when the
1836
* navigation event has completed.
1837
*/
1838
refresh() {
1839
return this.driver_.execute(new command.Command(command.Name.REFRESH))
1840
}
1841
}
1842
1843
/**
1844
* Provides methods for managing browser and driver state.
1845
*
1846
* This class should never be instantiated directly. Instead, obtain an instance
1847
* with {@linkplain WebDriver#manage() webdriver.manage()}.
1848
*/
1849
class Options {
1850
/**
1851
* @param {!WebDriver} driver The parent driver.
1852
* @private
1853
*/
1854
constructor(driver) {
1855
/** @private {!WebDriver} */
1856
this.driver_ = driver
1857
}
1858
1859
/**
1860
* Adds a cookie.
1861
*
1862
* __Sample Usage:__
1863
*
1864
* // Set a basic cookie.
1865
* driver.manage().addCookie({name: 'foo', value: 'bar'});
1866
*
1867
* // Set a cookie that expires in 10 minutes.
1868
* let expiry = new Date(Date.now() + (10 * 60 * 1000));
1869
* driver.manage().addCookie({name: 'foo', value: 'bar', expiry});
1870
*
1871
* // The cookie expiration may also be specified in seconds since epoch.
1872
* driver.manage().addCookie({
1873
* name: 'foo',
1874
* value: 'bar',
1875
* expiry: Math.floor(Date.now() / 1000)
1876
* });
1877
*
1878
* @param {!Options.Cookie} spec Defines the cookie to add.
1879
* @return {!Promise<void>} A promise that will be resolved
1880
* when the cookie has been added to the page.
1881
* @throws {error.InvalidArgumentError} if any of the cookie parameters are
1882
* invalid.
1883
* @throws {TypeError} if `spec` is not a cookie object.
1884
*/
1885
addCookie({ name, value, path, domain, secure, httpOnly, expiry, sameSite }) {
1886
// We do not allow '=' or ';' in the name.
1887
if (/[;=]/.test(name)) {
1888
throw new error.InvalidArgumentError('Invalid cookie name "' + name + '"')
1889
}
1890
1891
// We do not allow ';' in value.
1892
if (/;/.test(value)) {
1893
throw new error.InvalidArgumentError('Invalid cookie value "' + value + '"')
1894
}
1895
1896
if (typeof expiry === 'number') {
1897
expiry = Math.floor(expiry)
1898
} else if (expiry instanceof Date) {
1899
let date = /** @type {!Date} */ (expiry)
1900
expiry = Math.floor(date.getTime() / 1000)
1901
}
1902
1903
if (sameSite && !['Strict', 'Lax', 'None'].includes(sameSite)) {
1904
throw new error.InvalidArgumentError(
1905
`Invalid sameSite cookie value '${sameSite}'. It should be one of "Lax", "Strict" or "None"`,
1906
)
1907
}
1908
1909
if (sameSite === 'None' && !secure) {
1910
throw new error.InvalidArgumentError('Invalid cookie configuration: SameSite=None must be Secure')
1911
}
1912
1913
return this.driver_.execute(
1914
new command.Command(command.Name.ADD_COOKIE).setParameter('cookie', {
1915
name: name,
1916
value: value,
1917
path: path,
1918
domain: domain,
1919
secure: !!secure,
1920
httpOnly: !!httpOnly,
1921
expiry: expiry,
1922
sameSite: sameSite,
1923
}),
1924
)
1925
}
1926
1927
/**
1928
* Deletes all cookies visible to the current page.
1929
*
1930
* @return {!Promise<void>} A promise that will be resolved
1931
* when all cookies have been deleted.
1932
*/
1933
deleteAllCookies() {
1934
return this.driver_.execute(new command.Command(command.Name.DELETE_ALL_COOKIES))
1935
}
1936
1937
/**
1938
* Deletes the cookie with the given name. This command is a no-op if there is
1939
* no cookie with the given name visible to the current page.
1940
*
1941
* @param {string} name The name of the cookie to delete.
1942
* @return {!Promise<void>} A promise that will be resolved
1943
* when the cookie has been deleted.
1944
*/
1945
deleteCookie(name) {
1946
// Validate the cookie name is non-empty and properly trimmed.
1947
if (!name?.trim()) {
1948
throw new error.InvalidArgumentError('Cookie name cannot be empty')
1949
}
1950
1951
return this.driver_.execute(new command.Command(command.Name.DELETE_COOKIE).setParameter('name', name))
1952
}
1953
1954
/**
1955
* Retrieves all cookies visible to the current page. Each cookie will be
1956
* returned as a JSON object as described by the WebDriver wire protocol.
1957
*
1958
* @return {!Promise<!Array<!Options.Cookie>>} A promise that will be
1959
* resolved with the cookies visible to the current browsing context.
1960
*/
1961
getCookies() {
1962
return this.driver_.execute(new command.Command(command.Name.GET_ALL_COOKIES))
1963
}
1964
1965
/**
1966
* Retrieves the cookie with the given name. Returns null if there is no such
1967
* cookie. The cookie will be returned as a JSON object as described by the
1968
* WebDriver wire protocol.
1969
*
1970
* @param {string} name The name of the cookie to retrieve.
1971
* @throws {InvalidArgumentError} - If the cookie name is empty or invalid.
1972
* @return {!Promise<?Options.Cookie>} A promise that will be resolved
1973
* with the named cookie
1974
* @throws {error.NoSuchCookieError} if there is no such cookie.
1975
*/
1976
async getCookie(name) {
1977
// Validate the cookie name is non-empty and properly trimmed.
1978
if (!name?.trim()) {
1979
throw new error.InvalidArgumentError('Cookie name cannot be empty')
1980
}
1981
1982
try {
1983
const cookie = await this.driver_.execute(new command.Command(command.Name.GET_COOKIE).setParameter('name', name))
1984
return cookie
1985
} catch (err) {
1986
if (!(err instanceof error.UnknownCommandError) && !(err instanceof error.UnsupportedOperationError)) {
1987
throw err
1988
}
1989
return null
1990
}
1991
}
1992
1993
/**
1994
* Fetches the timeouts currently configured for the current session.
1995
*
1996
* @return {!Promise<{script: number,
1997
* pageLoad: number,
1998
* implicit: number}>} A promise that will be
1999
* resolved with the timeouts currently configured for the current
2000
* session.
2001
* @see #setTimeouts()
2002
*/
2003
getTimeouts() {
2004
return this.driver_.execute(new command.Command(command.Name.GET_TIMEOUT))
2005
}
2006
2007
/**
2008
* Sets the timeout durations associated with the current session.
2009
*
2010
* The following timeouts are supported (all timeouts are specified in
2011
* milliseconds):
2012
*
2013
* - `implicit` specifies the maximum amount of time to wait for an element
2014
* locator to succeed when {@linkplain WebDriver#findElement locating}
2015
* {@linkplain WebDriver#findElements elements} on the page.
2016
* Defaults to 0 milliseconds.
2017
*
2018
* - `pageLoad` specifies the maximum amount of time to wait for a page to
2019
* finishing loading. Defaults to 300000 milliseconds.
2020
*
2021
* - `script` specifies the maximum amount of time to wait for an
2022
* {@linkplain WebDriver#executeScript evaluated script} to run. If set to
2023
* `null`, the script timeout will be indefinite.
2024
* Defaults to 30000 milliseconds.
2025
*
2026
* @param {{script: (number|null|undefined),
2027
* pageLoad: (number|null|undefined),
2028
* implicit: (number|null|undefined)}} conf
2029
* The desired timeout configuration.
2030
* @return {!Promise<void>} A promise that will be resolved when the timeouts
2031
* have been set.
2032
* @throws {!TypeError} if an invalid options object is provided.
2033
* @see #getTimeouts()
2034
* @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>
2035
*/
2036
setTimeouts({ script, pageLoad, implicit } = {}) {
2037
let cmd = new command.Command(command.Name.SET_TIMEOUT)
2038
2039
let valid = false
2040
2041
function setParam(key, value) {
2042
if (value === null || typeof value === 'number') {
2043
valid = true
2044
cmd.setParameter(key, value)
2045
} else if (typeof value !== 'undefined') {
2046
throw TypeError('invalid timeouts configuration:' + ` expected "${key}" to be a number, got ${typeof value}`)
2047
}
2048
}
2049
2050
setParam('implicit', implicit)
2051
setParam('pageLoad', pageLoad)
2052
setParam('script', script)
2053
2054
if (valid) {
2055
return this.driver_.execute(cmd).catch(() => {
2056
// Fallback to the legacy method.
2057
let cmds = []
2058
if (typeof script === 'number') {
2059
cmds.push(legacyTimeout(this.driver_, 'script', script))
2060
}
2061
if (typeof implicit === 'number') {
2062
cmds.push(legacyTimeout(this.driver_, 'implicit', implicit))
2063
}
2064
if (typeof pageLoad === 'number') {
2065
cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad))
2066
}
2067
return Promise.all(cmds)
2068
})
2069
}
2070
throw TypeError('no timeouts specified')
2071
}
2072
2073
/**
2074
* @return {!Logs} The interface for managing driver logs.
2075
*/
2076
logs() {
2077
return new Logs(this.driver_)
2078
}
2079
2080
/**
2081
* @return {!Window} The interface for managing the current window.
2082
*/
2083
window() {
2084
return new Window(this.driver_)
2085
}
2086
}
2087
2088
/**
2089
* @param {!WebDriver} driver
2090
* @param {string} type
2091
* @param {number} ms
2092
* @return {!Promise<void>}
2093
*/
2094
function legacyTimeout(driver, type, ms) {
2095
return driver.execute(new command.Command(command.Name.SET_TIMEOUT).setParameter('type', type).setParameter('ms', ms))
2096
}
2097
2098
/**
2099
* A record object describing a browser cookie.
2100
*
2101
* @record
2102
*/
2103
Options.Cookie = function () {}
2104
2105
/**
2106
* The name of the cookie.
2107
*
2108
* @type {string}
2109
*/
2110
Options.Cookie.prototype.name
2111
2112
/**
2113
* The cookie value.
2114
*
2115
* @type {string}
2116
*/
2117
Options.Cookie.prototype.value
2118
2119
/**
2120
* The cookie path. Defaults to "/" when adding a cookie.
2121
*
2122
* @type {(string|undefined)}
2123
*/
2124
Options.Cookie.prototype.path
2125
2126
/**
2127
* The domain the cookie is visible to. Defaults to the current browsing
2128
* context's document's URL when adding a cookie.
2129
*
2130
* @type {(string|undefined)}
2131
*/
2132
Options.Cookie.prototype.domain
2133
2134
/**
2135
* Whether the cookie is a secure cookie. Defaults to false when adding a new
2136
* cookie.
2137
*
2138
* @type {(boolean|undefined)}
2139
*/
2140
Options.Cookie.prototype.secure
2141
2142
/**
2143
* Whether the cookie is an HTTP only cookie. Defaults to false when adding a
2144
* new cookie.
2145
*
2146
* @type {(boolean|undefined)}
2147
*/
2148
Options.Cookie.prototype.httpOnly
2149
2150
/**
2151
* When the cookie expires.
2152
*
2153
* When {@linkplain Options#addCookie() adding a cookie}, this may be specified
2154
* as a {@link Date} object, or in _seconds_ since Unix epoch (January 1, 1970).
2155
*
2156
* The expiry is always returned in seconds since epoch when
2157
* {@linkplain Options#getCookies() retrieving cookies} from the browser.
2158
*
2159
* @type {(!Date|number|undefined)}
2160
*/
2161
Options.Cookie.prototype.expiry
2162
2163
/**
2164
* When the cookie applies to a SameSite policy.
2165
*
2166
* When {@linkplain Options#addCookie() adding a cookie}, this may be specified
2167
* as a {@link string} object which is one of 'Lax', 'Strict' or 'None'.
2168
*
2169
*
2170
* @type {(string|undefined)}
2171
*/
2172
Options.Cookie.prototype.sameSite
2173
2174
/**
2175
* An interface for managing the current window.
2176
*
2177
* This class should never be instantiated directly. Instead, obtain an instance
2178
* with
2179
*
2180
* webdriver.manage().window()
2181
*
2182
* @see WebDriver#manage()
2183
* @see Options#window()
2184
*/
2185
class Window {
2186
/**
2187
* @param {!WebDriver} driver The parent driver.
2188
* @private
2189
*/
2190
constructor(driver) {
2191
/** @private {!WebDriver} */
2192
this.driver_ = driver
2193
/** @private {!Logger} */
2194
this.log_ = logging.getLogger(logging.Type.DRIVER)
2195
}
2196
2197
/**
2198
* Retrieves a rect describing the current top-level window's size and
2199
* position.
2200
*
2201
* @return {!Promise<{x: number, y: number, width: number, height: number}>}
2202
* A promise that will resolve to the window rect of the current window.
2203
*/
2204
getRect() {
2205
return this.driver_.execute(new command.Command(command.Name.GET_WINDOW_RECT))
2206
}
2207
2208
/**
2209
* Sets the current top-level window's size and position. You may update just
2210
* the size by omitting `x` & `y`, or just the position by omitting
2211
* `width` & `height` options.
2212
*
2213
* @param {{x: (number|undefined),
2214
* y: (number|undefined),
2215
* width: (number|undefined),
2216
* height: (number|undefined)}} options
2217
* The desired window size and position.
2218
* @return {!Promise<{x: number, y: number, width: number, height: number}>}
2219
* A promise that will resolve to the current window's updated window
2220
* rect.
2221
*/
2222
setRect({ x, y, width, height }) {
2223
return this.driver_.execute(
2224
new command.Command(command.Name.SET_WINDOW_RECT).setParameters({
2225
x,
2226
y,
2227
width,
2228
height,
2229
}),
2230
)
2231
}
2232
2233
/**
2234
* Maximizes the current window. The exact behavior of this command is
2235
* specific to individual window managers, but typically involves increasing
2236
* the window to the maximum available size without going full-screen.
2237
*
2238
* @return {!Promise<void>} A promise that will be resolved when the command
2239
* has completed.
2240
*/
2241
maximize() {
2242
return this.driver_.execute(
2243
new command.Command(command.Name.MAXIMIZE_WINDOW).setParameter('windowHandle', 'current'),
2244
)
2245
}
2246
2247
/**
2248
* Minimizes the current window. The exact behavior of this command is
2249
* specific to individual window managers, but typically involves hiding
2250
* the window in the system tray.
2251
*
2252
* @return {!Promise<void>} A promise that will be resolved when the command
2253
* has completed.
2254
*/
2255
minimize() {
2256
return this.driver_.execute(new command.Command(command.Name.MINIMIZE_WINDOW))
2257
}
2258
2259
/**
2260
* Invokes the "full screen" operation on the current window. The exact
2261
* behavior of this command is specific to individual window managers, but
2262
* this will typically increase the window size to the size of the physical
2263
* display and hide the browser chrome.
2264
*
2265
* @return {!Promise<void>} A promise that will be resolved when the command
2266
* has completed.
2267
* @see <https://fullscreen.spec.whatwg.org/#fullscreen-an-element>
2268
*/
2269
fullscreen() {
2270
return this.driver_.execute(new command.Command(command.Name.FULLSCREEN_WINDOW))
2271
}
2272
2273
/**
2274
* Gets the width and height of the current window
2275
* @param windowHandle
2276
* @returns {Promise<{width: *, height: *}>}
2277
*/
2278
async getSize(windowHandle = 'current') {
2279
if (windowHandle !== 'current') {
2280
this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)
2281
}
2282
2283
const rect = await this.getRect()
2284
return { height: rect.height, width: rect.width }
2285
}
2286
2287
/**
2288
* Sets the width and height of the current window. (window.resizeTo)
2289
* @param x
2290
* @param y
2291
* @param width
2292
* @param height
2293
* @param windowHandle
2294
* @returns {Promise<void>}
2295
*/
2296
async setSize({ x = 0, y = 0, width = 0, height = 0 }, windowHandle = 'current') {
2297
if (windowHandle !== 'current') {
2298
this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)
2299
}
2300
2301
await this.setRect({ x, y, width, height })
2302
}
2303
}
2304
2305
/**
2306
* Interface for managing WebDriver log records.
2307
*
2308
* This class should never be instantiated directly. Instead, obtain an
2309
* instance with
2310
*
2311
* webdriver.manage().logs()
2312
*
2313
* @see WebDriver#manage()
2314
* @see Options#logs()
2315
*/
2316
class Logs {
2317
/**
2318
* @param {!WebDriver} driver The parent driver.
2319
* @private
2320
*/
2321
constructor(driver) {
2322
/** @private {!WebDriver} */
2323
this.driver_ = driver
2324
}
2325
2326
/**
2327
* Fetches available log entries for the given type.
2328
*
2329
* Note that log buffers are reset after each call, meaning that available
2330
* log entries correspond to those entries not yet returned for a given log
2331
* type. In practice, this means that this call will return the available log
2332
* entries since the last call, or from the start of the session.
2333
*
2334
* @param {!logging.Type} type The desired log type.
2335
* @return {!Promise<!Array.<!logging.Entry>>} A
2336
* promise that will resolve to a list of log entries for the specified
2337
* type.
2338
*/
2339
get(type) {
2340
let cmd = new command.Command(command.Name.GET_LOG).setParameter('type', type)
2341
return this.driver_.execute(cmd).then(function (entries) {
2342
return entries.map(function (entry) {
2343
if (!(entry instanceof logging.Entry)) {
2344
return new logging.Entry(entry['level'], entry['message'], entry['timestamp'], entry['type'])
2345
}
2346
return entry
2347
})
2348
})
2349
}
2350
2351
/**
2352
* Retrieves the log types available to this driver.
2353
* @return {!Promise<!Array<!logging.Type>>} A
2354
* promise that will resolve to a list of available log types.
2355
*/
2356
getAvailableLogTypes() {
2357
return this.driver_.execute(new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES))
2358
}
2359
}
2360
2361
/**
2362
* An interface for changing the focus of the driver to another frame or window.
2363
*
2364
* This class should never be instantiated directly. Instead, obtain an
2365
* instance with
2366
*
2367
* webdriver.switchTo()
2368
*
2369
* @see WebDriver#switchTo()
2370
*/
2371
class TargetLocator {
2372
/**
2373
* @param {!WebDriver} driver The parent driver.
2374
* @private
2375
*/
2376
constructor(driver) {
2377
/** @private {!WebDriver} */
2378
this.driver_ = driver
2379
}
2380
2381
/**
2382
* Locates the DOM element on the current page that corresponds to
2383
* `document.activeElement` or `document.body` if the active element is not
2384
* available.
2385
*
2386
* @return {!WebElementPromise} The active element.
2387
*/
2388
activeElement() {
2389
const id = this.driver_.execute(new command.Command(command.Name.GET_ACTIVE_ELEMENT))
2390
return new WebElementPromise(this.driver_, id)
2391
}
2392
2393
/**
2394
* Switches focus of all future commands to the topmost frame in the current
2395
* window.
2396
*
2397
* @return {!Promise<void>} A promise that will be resolved
2398
* when the driver has changed focus to the default content.
2399
*/
2400
defaultContent() {
2401
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', null))
2402
}
2403
2404
/**
2405
* Changes the focus of all future commands to another frame on the page. The
2406
* target frame may be specified as one of the following:
2407
*
2408
* - A number that specifies a (zero-based) index into [window.frames](
2409
* https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
2410
* - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
2411
* DOM element.
2412
* - The `null` value, to select the topmost frame on the page. Passing `null`
2413
* is the same as calling {@link #defaultContent defaultContent()}.
2414
*
2415
* If the specified frame can not be found, the returned promise will be
2416
* rejected with a {@linkplain error.NoSuchFrameError}.
2417
*
2418
* @param {(number|string|WebElement|null)} id The frame locator.
2419
* @return {!Promise<void>} A promise that will be resolved
2420
* when the driver has changed focus to the specified frame.
2421
*/
2422
frame(id) {
2423
let frameReference = id
2424
if (typeof id === 'string') {
2425
frameReference = this.driver_.findElement({ id }).catch((_) => this.driver_.findElement({ name: id }))
2426
}
2427
2428
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', frameReference))
2429
}
2430
2431
/**
2432
* Changes the focus of all future commands to the parent frame of the
2433
* currently selected frame. This command has no effect if the driver is
2434
* already focused on the top-level browsing context.
2435
*
2436
* @return {!Promise<void>} A promise that will be resolved when the command
2437
* has completed.
2438
*/
2439
parentFrame() {
2440
return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME_PARENT))
2441
}
2442
2443
/**
2444
* Changes the focus of all future commands to another window. Windows may be
2445
* specified by their {@code window.name} attribute or by its handle
2446
* (as returned by {@link WebDriver#getWindowHandles}).
2447
*
2448
* If the specified window cannot be found, the returned promise will be
2449
* rejected with a {@linkplain error.NoSuchWindowError}.
2450
*
2451
* @param {string} nameOrHandle The name or window handle of the window to
2452
* switch focus to.
2453
* @return {!Promise<void>} A promise that will be resolved
2454
* when the driver has changed focus to the specified window.
2455
*/
2456
window(nameOrHandle) {
2457
return this.driver_.execute(
2458
new command.Command(command.Name.SWITCH_TO_WINDOW)
2459
// "name" supports the legacy drivers. "handle" is the W3C
2460
// compliant parameter.
2461
.setParameter('name', nameOrHandle)
2462
.setParameter('handle', nameOrHandle),
2463
)
2464
}
2465
2466
/**
2467
* Creates a new browser window and switches the focus for future
2468
* commands of this driver to the new window.
2469
*
2470
* @param {string} typeHint 'window' or 'tab'. The created window is not
2471
* guaranteed to be of the requested type; if the driver does not support
2472
* the requested type, a new browser window will be created of whatever type
2473
* the driver does support.
2474
* @return {!Promise<void>} A promise that will be resolved
2475
* when the driver has changed focus to the new window.
2476
*/
2477
newWindow(typeHint) {
2478
const driver = this.driver_
2479
return this.driver_
2480
.execute(new command.Command(command.Name.SWITCH_TO_NEW_WINDOW).setParameter('type', typeHint))
2481
.then(function (response) {
2482
return driver.switchTo().window(response.handle)
2483
})
2484
}
2485
2486
/**
2487
* Changes focus to the active modal dialog, such as those opened by
2488
* `window.alert()`, `window.confirm()`, and `window.prompt()`. The returned
2489
* promise will be rejected with a
2490
* {@linkplain error.NoSuchAlertError} if there are no open alerts.
2491
*
2492
* @return {!AlertPromise} The open alert.
2493
*/
2494
alert() {
2495
const text = this.driver_.execute(new command.Command(command.Name.GET_ALERT_TEXT))
2496
const driver = this.driver_
2497
return new AlertPromise(
2498
driver,
2499
text.then(function (text) {
2500
return new Alert(driver, text)
2501
}),
2502
)
2503
}
2504
}
2505
2506
//////////////////////////////////////////////////////////////////////////////
2507
//
2508
// WebElement
2509
//
2510
//////////////////////////////////////////////////////////////////////////////
2511
2512
const LEGACY_ELEMENT_ID_KEY = 'ELEMENT'
2513
const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf'
2514
const SHADOW_ROOT_ID_KEY = 'shadow-6066-11e4-a52e-4f735466cecf'
2515
2516
/**
2517
* Represents a DOM element. WebElements can be found by searching from the
2518
* document root using a {@link WebDriver} instance, or by searching
2519
* under another WebElement:
2520
*
2521
* driver.get('http://www.google.com');
2522
* var searchForm = driver.findElement(By.tagName('form'));
2523
* var searchBox = searchForm.findElement(By.name('q'));
2524
* searchBox.sendKeys('webdriver');
2525
*/
2526
class WebElement {
2527
/**
2528
* @param {!WebDriver} driver the parent WebDriver instance for this element.
2529
* @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
2530
* the underlying DOM element.
2531
*/
2532
constructor(driver, id) {
2533
/** @private {!WebDriver} */
2534
this.driver_ = driver
2535
2536
/** @private {!Promise<string>} */
2537
this.id_ = Promise.resolve(id)
2538
2539
/** @private {!Logger} */
2540
this.log_ = logging.getLogger(logging.Type.DRIVER)
2541
}
2542
2543
/**
2544
* @param {string} id The raw ID.
2545
* @param {boolean=} noLegacy Whether to exclude the legacy element key.
2546
* @return {!Object} The element ID for use with WebDriver's wire protocol.
2547
*/
2548
static buildId(id, noLegacy = false) {
2549
return noLegacy ? { [ELEMENT_ID_KEY]: id } : { [ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id }
2550
}
2551
2552
/**
2553
* Extracts the encoded WebElement ID from the object.
2554
*
2555
* @param {?} obj The object to extract the ID from.
2556
* @return {string} the extracted ID.
2557
* @throws {TypeError} if the object is not a valid encoded ID.
2558
*/
2559
static extractId(obj) {
2560
return webElement.extractId(obj)
2561
}
2562
2563
/**
2564
* @param {?} obj the object to test.
2565
* @return {boolean} whether the object is a valid encoded WebElement ID.
2566
*/
2567
static isId(obj) {
2568
return webElement.isId(obj)
2569
}
2570
2571
/**
2572
* Compares two WebElements for equality.
2573
*
2574
* @param {!WebElement} a A WebElement.
2575
* @param {!WebElement} b A WebElement.
2576
* @return {!Promise<boolean>} A promise that will be
2577
* resolved to whether the two WebElements are equal.
2578
*/
2579
static async equals(a, b) {
2580
if (a === b) {
2581
return true
2582
}
2583
return a.driver_.executeScript('return arguments[0] === arguments[1]', a, b)
2584
}
2585
2586
/** @return {!WebDriver} The parent driver for this instance. */
2587
getDriver() {
2588
return this.driver_
2589
}
2590
2591
/**
2592
* @return {!Promise<string>} A promise that resolves to
2593
* the server-assigned opaque ID assigned to this element.
2594
*/
2595
getId() {
2596
return this.id_
2597
}
2598
2599
/**
2600
* @return {!Object} Returns the serialized representation of this WebElement.
2601
*/
2602
[Symbols.serialize]() {
2603
return this.getId().then(WebElement.buildId)
2604
}
2605
2606
/**
2607
* Schedules a command that targets this element with the parent WebDriver
2608
* instance. Will ensure this element's ID is included in the command
2609
* parameters under the "id" key.
2610
*
2611
* @param {!command.Command} command The command to schedule.
2612
* @return {!Promise<T>} A promise that will be resolved with the result.
2613
* @template T
2614
* @see WebDriver#schedule
2615
* @private
2616
*/
2617
execute_(command) {
2618
command.setParameter('id', this)
2619
return this.driver_.execute(command)
2620
}
2621
2622
/**
2623
* Schedule a command to find a descendant of this element. If the element
2624
* cannot be found, the returned promise will be rejected with a
2625
* {@linkplain error.NoSuchElementError NoSuchElementError}.
2626
*
2627
* The search criteria for an element may be defined using one of the static
2628
* factories on the {@link by.By} class, or as a short-hand
2629
* {@link ./by.ByHash} object. For example, the following two statements
2630
* are equivalent:
2631
*
2632
* var e1 = element.findElement(By.id('foo'));
2633
* var e2 = element.findElement({id:'foo'});
2634
*
2635
* You may also provide a custom locator function, which takes as input this
2636
* instance and returns a {@link WebElement}, or a promise that will resolve
2637
* to a WebElement. If the returned promise resolves to an array of
2638
* WebElements, WebDriver will use the first element. For example, to find the
2639
* first visible link on a page, you could write:
2640
*
2641
* var link = element.findElement(firstVisibleLink);
2642
*
2643
* function firstVisibleLink(element) {
2644
* var links = element.findElements(By.tagName('a'));
2645
* return promise.filter(links, function(link) {
2646
* return link.isDisplayed();
2647
* });
2648
* }
2649
*
2650
* @param {!(by.By|Function)} locator The locator strategy to use when
2651
* searching for the element.
2652
* @return {!WebElementPromise} A WebElement that can be used to issue
2653
* commands against the located element. If the element is not found, the
2654
* element will be invalidated and all scheduled commands aborted.
2655
*/
2656
findElement(locator) {
2657
locator = by.checkedLocator(locator)
2658
let id
2659
if (typeof locator === 'function') {
2660
id = this.driver_.findElementInternal_(locator, this)
2661
} else {
2662
let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENT)
2663
.setParameter('using', locator.using)
2664
.setParameter('value', locator.value)
2665
id = this.execute_(cmd)
2666
}
2667
return new WebElementPromise(this.driver_, id)
2668
}
2669
2670
/**
2671
* Locates all the descendants of this element that match the given search
2672
* criteria.
2673
*
2674
* @param {!(by.By|Function)} locator The locator strategy to use when
2675
* searching for the element.
2676
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
2677
* array of WebElements.
2678
*/
2679
async findElements(locator) {
2680
locator = by.checkedLocator(locator)
2681
if (typeof locator === 'function') {
2682
return this.driver_.findElementsInternal_(locator, this)
2683
} else {
2684
let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENTS)
2685
.setParameter('using', locator.using)
2686
.setParameter('value', locator.value)
2687
let result = await this.execute_(cmd)
2688
return Array.isArray(result) ? result : []
2689
}
2690
}
2691
2692
/**
2693
* Clicks on this element.
2694
*
2695
* @return {!Promise<void>} A promise that will be resolved when the click
2696
* command has completed.
2697
*/
2698
click() {
2699
return this.execute_(new command.Command(command.Name.CLICK_ELEMENT))
2700
}
2701
2702
/**
2703
* Types a key sequence on the DOM element represented by this instance.
2704
*
2705
* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
2706
* processed in the key sequence, that key state is toggled until one of the
2707
* following occurs:
2708
*
2709
* - The modifier key is encountered again in the sequence. At this point the
2710
* state of the key is toggled (along with the appropriate keyup/down
2711
* events).
2712
* - The {@link input.Key.NULL} key is encountered in the sequence. When
2713
* this key is encountered, all modifier keys current in the down state are
2714
* released (with accompanying keyup events). The NULL key can be used to
2715
* simulate common keyboard shortcuts:
2716
*
2717
* element.sendKeys("text was",
2718
* Key.CONTROL, "a", Key.NULL,
2719
* "now text is");
2720
* // Alternatively:
2721
* element.sendKeys("text was",
2722
* Key.chord(Key.CONTROL, "a"),
2723
* "now text is");
2724
*
2725
* - The end of the key sequence is encountered. When there are no more keys
2726
* to type, all depressed modifier keys are released (with accompanying
2727
* keyup events).
2728
*
2729
* If this element is a file input ({@code <input type="file">}), the
2730
* specified key sequence should specify the path to the file to attach to
2731
* the element. This is analogous to the user clicking "Browse..." and entering
2732
* the path into the file select dialog.
2733
*
2734
* var form = driver.findElement(By.css('form'));
2735
* var element = form.findElement(By.css('input[type=file]'));
2736
* element.sendKeys('/path/to/file.txt');
2737
* form.submit();
2738
*
2739
* For uploads to function correctly, the entered path must reference a file
2740
* on the _browser's_ machine, not the local machine running this script. When
2741
* running against a remote Selenium server, a {@link input.FileDetector}
2742
* may be used to transparently copy files to the remote machine before
2743
* attempting to upload them in the browser.
2744
*
2745
* __Note:__ On browsers where native keyboard events are not supported
2746
* (e.g. Firefox on OS X), key events will be synthesized. Special
2747
* punctuation keys will be synthesized according to a standard QWERTY en-us
2748
* keyboard layout.
2749
*
2750
* @param {...(number|string|!IThenable<(number|string)>)} args The
2751
* sequence of keys to type. Number keys may be referenced numerically or
2752
* by string (1 or '1'). All arguments will be joined into a single
2753
* sequence.
2754
* @return {!Promise<void>} A promise that will be resolved when all keys
2755
* have been typed.
2756
*/
2757
async sendKeys(...args) {
2758
let keys = []
2759
;(await Promise.all(args)).forEach((key) => {
2760
let type = typeof key
2761
if (type === 'number') {
2762
key = String(key)
2763
} else if (type !== 'string') {
2764
throw TypeError('each key must be a number or string; got ' + type)
2765
}
2766
2767
// The W3C protocol requires keys to be specified as an array where
2768
// each element is a single key.
2769
keys.push(...key)
2770
})
2771
2772
if (!this.driver_.fileDetector_) {
2773
return this.execute_(
2774
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)
2775
.setParameter('text', keys.join(''))
2776
.setParameter('value', keys),
2777
)
2778
}
2779
2780
try {
2781
keys = await this.driver_.fileDetector_.handleFile(this.driver_, keys.join(''))
2782
} catch (ex) {
2783
this.log_.severe('Error trying parse string as a file with file detector; sending keys instead' + ex)
2784
keys = keys.join('')
2785
}
2786
2787
return this.execute_(
2788
new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)
2789
.setParameter('text', keys)
2790
.setParameter('value', keys.split('')),
2791
)
2792
}
2793
2794
/**
2795
* Retrieves the element's tag name.
2796
*
2797
* @return {!Promise<string>} A promise that will be resolved with the
2798
* element's tag name.
2799
*/
2800
getTagName() {
2801
return this.execute_(new command.Command(command.Name.GET_ELEMENT_TAG_NAME))
2802
}
2803
2804
/**
2805
* Retrieves the value of a computed style property for this instance. If
2806
* the element inherits the named style from its parent, the parent will be
2807
* queried for its value. Where possible, color values will be converted to
2808
* their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)).
2809
*
2810
* _Warning:_ the value returned will be as the browser interprets it, so
2811
* it may be tricky to form a proper assertion.
2812
*
2813
* @param {string} cssStyleProperty The name of the CSS style property to look
2814
* up.
2815
* @return {!Promise<string>} A promise that will be resolved with the
2816
* requested CSS value.
2817
*/
2818
getCssValue(cssStyleProperty) {
2819
const name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY
2820
return this.execute_(new command.Command(name).setParameter('propertyName', cssStyleProperty))
2821
}
2822
2823
/**
2824
* Retrieves the current value of the given attribute of this element.
2825
* Will return the current value, even if it has been modified after the page
2826
* has been loaded. More exactly, this method will return the value
2827
* of the given attribute, unless that attribute is not present, in which case
2828
* the value of the property with the same name is returned. If neither value
2829
* is set, null is returned (for example, the "value" property of a textarea
2830
* element). The "style" attribute is converted as best can be to a
2831
* text representation with a trailing semicolon. The following are deemed to
2832
* be "boolean" attributes and will return either "true" or null:
2833
*
2834
* async, autofocus, autoplay, checked, compact, complete, controls, declare,
2835
* defaultchecked, defaultselected, defer, disabled, draggable, ended,
2836
* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
2837
* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
2838
* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
2839
* selected, spellcheck, truespeed, willvalidate
2840
*
2841
* Finally, the following commonly mis-capitalized attribute/property names
2842
* are evaluated as expected:
2843
*
2844
* - "class"
2845
* - "readonly"
2846
*
2847
* @param {string} attributeName The name of the attribute to query.
2848
* @return {!Promise<?string>} A promise that will be
2849
* resolved with the attribute's value. The returned value will always be
2850
* either a string or null.
2851
*/
2852
getAttribute(attributeName) {
2853
return this.execute_(new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).setParameter('name', attributeName))
2854
}
2855
2856
/**
2857
* Get the value of the given attribute of the element.
2858
* <p>
2859
* This method, unlike {@link #getAttribute(String)}, returns the value of the attribute with the
2860
* given name but not the property with the same name.
2861
* <p>
2862
* The following are deemed to be "boolean" attributes, and will return either "true" or null:
2863
* <p>
2864
* async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked,
2865
* defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate,
2866
* iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade,
2867
* novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless,
2868
* seeking, selected, truespeed, willvalidate
2869
* <p>
2870
* See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver specification</a>
2871
* for more details.
2872
*
2873
* @param attributeName The name of the attribute.
2874
* @return The attribute's value or null if the value is not set.
2875
*/
2876
2877
getDomAttribute(attributeName) {
2878
return this.execute_(new command.Command(command.Name.GET_DOM_ATTRIBUTE).setParameter('name', attributeName))
2879
}
2880
2881
/**
2882
* Get the given property of the referenced web element
2883
* @param {string} propertyName The name of the attribute to query.
2884
* @return {!Promise<string>} A promise that will be
2885
* resolved with the element's property value
2886
*/
2887
getProperty(propertyName) {
2888
return this.execute_(new command.Command(command.Name.GET_ELEMENT_PROPERTY).setParameter('name', propertyName))
2889
}
2890
2891
/**
2892
* Get the shadow root of the current web element.
2893
* @returns {!Promise<ShadowRoot>} A promise that will be
2894
* resolved with the elements shadow root or rejected
2895
* with {@link NoSuchShadowRootError}
2896
*/
2897
getShadowRoot() {
2898
return this.execute_(new command.Command(command.Name.GET_SHADOW_ROOT))
2899
}
2900
2901
/**
2902
* Get the visible (i.e. not hidden by CSS) innerText of this element,
2903
* including sub-elements, without any leading or trailing whitespace.
2904
*
2905
* @return {!Promise<string>} A promise that will be
2906
* resolved with the element's visible text.
2907
*/
2908
getText() {
2909
return this.execute_(new command.Command(command.Name.GET_ELEMENT_TEXT))
2910
}
2911
2912
/**
2913
* Get the computed WAI-ARIA role of element.
2914
*
2915
* @return {!Promise<string>} A promise that will be
2916
* resolved with the element's computed role.
2917
*/
2918
getAriaRole() {
2919
return this.execute_(new command.Command(command.Name.GET_COMPUTED_ROLE))
2920
}
2921
2922
/**
2923
* Get the computed WAI-ARIA label of element.
2924
*
2925
* @return {!Promise<string>} A promise that will be
2926
* resolved with the element's computed label.
2927
*/
2928
getAccessibleName() {
2929
return this.execute_(new command.Command(command.Name.GET_COMPUTED_LABEL))
2930
}
2931
2932
/**
2933
* Returns an object describing an element's location, in pixels relative to
2934
* the document element, and the element's size in pixels.
2935
*
2936
* @return {!Promise<{width: number, height: number, x: number, y: number}>}
2937
* A promise that will resolve with the element's rect.
2938
*/
2939
getRect() {
2940
return this.execute_(new command.Command(command.Name.GET_ELEMENT_RECT))
2941
}
2942
2943
/**
2944
* Tests whether this element is enabled, as dictated by the `disabled`
2945
* attribute.
2946
*
2947
* @return {!Promise<boolean>} A promise that will be
2948
* resolved with whether this element is currently enabled.
2949
*/
2950
isEnabled() {
2951
return this.execute_(new command.Command(command.Name.IS_ELEMENT_ENABLED))
2952
}
2953
2954
/**
2955
* Tests whether this element is selected.
2956
*
2957
* @return {!Promise<boolean>} A promise that will be
2958
* resolved with whether this element is currently selected.
2959
*/
2960
isSelected() {
2961
return this.execute_(new command.Command(command.Name.IS_ELEMENT_SELECTED))
2962
}
2963
2964
/**
2965
* Submits the form containing this element (or this element if it is itself
2966
* a FORM element). his command is a no-op if the element is not contained in
2967
* a form.
2968
*
2969
* @return {!Promise<void>} A promise that will be resolved
2970
* when the form has been submitted.
2971
*/
2972
submit() {
2973
const script =
2974
'/* submitForm */var form = arguments[0];\n' +
2975
'while (form.nodeName != "FORM" && form.parentNode) {\n' +
2976
' form = form.parentNode;\n' +
2977
'}\n' +
2978
"if (!form) { throw Error('Unable to find containing form element'); }\n" +
2979
"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n" +
2980
"var e = form.ownerDocument.createEvent('Event');\n" +
2981
"e.initEvent('submit', true, true);\n" +
2982
'if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n'
2983
2984
return this.driver_.executeScript(script, this)
2985
}
2986
2987
/**
2988
* Clear the `value` of this element. This command has no effect if the
2989
* underlying DOM element is neither a text INPUT element nor a TEXTAREA
2990
* element.
2991
*
2992
* @return {!Promise<void>} A promise that will be resolved
2993
* when the element has been cleared.
2994
*/
2995
clear() {
2996
return this.execute_(new command.Command(command.Name.CLEAR_ELEMENT))
2997
}
2998
2999
/**
3000
* Test whether this element is currently displayed.
3001
*
3002
* @return {!Promise<boolean>} A promise that will be
3003
* resolved with whether this element is currently visible on the page.
3004
*/
3005
isDisplayed() {
3006
return this.execute_(new command.Command(command.Name.IS_ELEMENT_DISPLAYED))
3007
}
3008
3009
/**
3010
* Take a screenshot of the visible region encompassed by this element's
3011
* bounding rectangle.
3012
*
3013
* @return {!Promise<string>} A promise that will be
3014
* resolved to the screenshot as a base-64 encoded PNG.
3015
*/
3016
takeScreenshot() {
3017
return this.execute_(new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT))
3018
}
3019
}
3020
3021
/**
3022
* WebElementPromise is a promise that will be fulfilled with a WebElement.
3023
* This serves as a forward proxy on WebElement, allowing calls to be
3024
* scheduled without directly on this instance before the underlying
3025
* WebElement has been fulfilled. In other words, the following two statements
3026
* are equivalent:
3027
*
3028
* driver.findElement({id: 'my-button'}).click();
3029
* driver.findElement({id: 'my-button'}).then(function(el) {
3030
* return el.click();
3031
* });
3032
*
3033
* @implements {IThenable<!WebElement>}
3034
* @final
3035
*/
3036
class WebElementPromise extends WebElement {
3037
/**
3038
* @param {!WebDriver} driver The parent WebDriver instance for this
3039
* element.
3040
* @param {!Promise<!WebElement>} el A promise
3041
* that will resolve to the promised element.
3042
*/
3043
constructor(driver, el) {
3044
super(driver, 'unused')
3045
3046
/** @override */
3047
this.then = el.then.bind(el)
3048
3049
/** @override */
3050
this.catch = el.catch.bind(el)
3051
3052
/**
3053
* Defers returning the element ID until the wrapped WebElement has been
3054
* resolved.
3055
* @override
3056
*/
3057
this.getId = function () {
3058
return el.then(function (el) {
3059
return el.getId()
3060
})
3061
}
3062
}
3063
}
3064
3065
//////////////////////////////////////////////////////////////////////////////
3066
//
3067
// ShadowRoot
3068
//
3069
//////////////////////////////////////////////////////////////////////////////
3070
3071
/**
3072
* Represents a ShadowRoot of a {@link WebElement}. Provides functions to
3073
* retrieve elements that live in the DOM below the ShadowRoot.
3074
*/
3075
class ShadowRoot {
3076
constructor(driver, id) {
3077
this.driver_ = driver
3078
this.id_ = id
3079
}
3080
3081
/**
3082
* Extracts the encoded ShadowRoot ID from the object.
3083
*
3084
* @param {?} obj The object to extract the ID from.
3085
* @return {string} the extracted ID.
3086
* @throws {TypeError} if the object is not a valid encoded ID.
3087
*/
3088
static extractId(obj) {
3089
if (obj && typeof obj === 'object') {
3090
if (typeof obj[SHADOW_ROOT_ID_KEY] === 'string') {
3091
return obj[SHADOW_ROOT_ID_KEY]
3092
}
3093
}
3094
throw new TypeError('object is not a ShadowRoot ID')
3095
}
3096
3097
/**
3098
* @param {?} obj the object to test.
3099
* @return {boolean} whether the object is a valid encoded WebElement ID.
3100
*/
3101
static isId(obj) {
3102
return obj && typeof obj === 'object' && typeof obj[SHADOW_ROOT_ID_KEY] === 'string'
3103
}
3104
3105
/**
3106
* @return {!Object} Returns the serialized representation of this ShadowRoot.
3107
*/
3108
[Symbols.serialize]() {
3109
return this.getId()
3110
}
3111
3112
/**
3113
* Schedules a command that targets this element with the parent WebDriver
3114
* instance. Will ensure this element's ID is included in the command
3115
* parameters under the "id" key.
3116
*
3117
* @param {!command.Command} command The command to schedule.
3118
* @return {!Promise<T>} A promise that will be resolved with the result.
3119
* @template T
3120
* @see WebDriver#schedule
3121
* @private
3122
*/
3123
execute_(command) {
3124
command.setParameter('id', this)
3125
return this.driver_.execute(command)
3126
}
3127
3128
/**
3129
* Schedule a command to find a descendant of this ShadowROot. If the element
3130
* cannot be found, the returned promise will be rejected with a
3131
* {@linkplain error.NoSuchElementError NoSuchElementError}.
3132
*
3133
* The search criteria for an element may be defined using one of the static
3134
* factories on the {@link by.By} class, or as a short-hand
3135
* {@link ./by.ByHash} object. For example, the following two statements
3136
* are equivalent:
3137
*
3138
* var e1 = shadowroot.findElement(By.id('foo'));
3139
* var e2 = shadowroot.findElement({id:'foo'});
3140
*
3141
* You may also provide a custom locator function, which takes as input this
3142
* instance and returns a {@link WebElement}, or a promise that will resolve
3143
* to a WebElement. If the returned promise resolves to an array of
3144
* WebElements, WebDriver will use the first element. For example, to find the
3145
* first visible link on a page, you could write:
3146
*
3147
* var link = element.findElement(firstVisibleLink);
3148
*
3149
* function firstVisibleLink(shadowRoot) {
3150
* var links = shadowRoot.findElements(By.tagName('a'));
3151
* return promise.filter(links, function(link) {
3152
* return link.isDisplayed();
3153
* });
3154
* }
3155
*
3156
* @param {!(by.By|Function)} locator The locator strategy to use when
3157
* searching for the element.
3158
* @return {!WebElementPromise} A WebElement that can be used to issue
3159
* commands against the located element. If the element is not found, the
3160
* element will be invalidated and all scheduled commands aborted.
3161
*/
3162
findElement(locator) {
3163
locator = by.checkedLocator(locator)
3164
let id
3165
if (typeof locator === 'function') {
3166
id = this.driver_.findElementInternal_(locator, this)
3167
} else {
3168
let cmd = new command.Command(command.Name.FIND_ELEMENT_FROM_SHADOWROOT)
3169
.setParameter('using', locator.using)
3170
.setParameter('value', locator.value)
3171
id = this.execute_(cmd)
3172
}
3173
return new ShadowRootPromise(this.driver_, id)
3174
}
3175
3176
/**
3177
* Locates all the descendants of this element that match the given search
3178
* criteria.
3179
*
3180
* @param {!(by.By|Function)} locator The locator strategy to use when
3181
* searching for the element.
3182
* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an
3183
* array of WebElements.
3184
*/
3185
async findElements(locator) {
3186
locator = by.checkedLocator(locator)
3187
if (typeof locator === 'function') {
3188
return this.driver_.findElementsInternal_(locator, this)
3189
} else {
3190
let cmd = new command.Command(command.Name.FIND_ELEMENTS_FROM_SHADOWROOT)
3191
.setParameter('using', locator.using)
3192
.setParameter('value', locator.value)
3193
let result = await this.execute_(cmd)
3194
return Array.isArray(result) ? result : []
3195
}
3196
}
3197
3198
getId() {
3199
return this.id_
3200
}
3201
}
3202
3203
/**
3204
* ShadowRootPromise is a promise that will be fulfilled with a WebElement.
3205
* This serves as a forward proxy on ShadowRoot, allowing calls to be
3206
* scheduled without directly on this instance before the underlying
3207
* ShadowRoot has been fulfilled.
3208
*
3209
* @implements { IThenable<!ShadowRoot>}
3210
* @final
3211
*/
3212
class ShadowRootPromise extends ShadowRoot {
3213
/**
3214
* @param {!WebDriver} driver The parent WebDriver instance for this
3215
* element.
3216
* @param {!Promise<!ShadowRoot>} shadow A promise
3217
* that will resolve to the promised element.
3218
*/
3219
constructor(driver, shadow) {
3220
super(driver, 'unused')
3221
3222
/** @override */
3223
this.then = shadow.then.bind(shadow)
3224
3225
/** @override */
3226
this.catch = shadow.catch.bind(shadow)
3227
3228
/**
3229
* Defers returning the ShadowRoot ID until the wrapped WebElement has been
3230
* resolved.
3231
* @override
3232
*/
3233
this.getId = function () {
3234
return shadow.then(function (shadow) {
3235
return shadow.getId()
3236
})
3237
}
3238
}
3239
}
3240
3241
//////////////////////////////////////////////////////////////////////////////
3242
//
3243
// Alert
3244
//
3245
//////////////////////////////////////////////////////////////////////////////
3246
3247
/**
3248
* Represents a modal dialog such as {@code alert}, {@code confirm}, or
3249
* {@code prompt}. Provides functions to retrieve the message displayed with
3250
* the alert, accept or dismiss the alert, and set the response text (in the
3251
* case of {@code prompt}).
3252
*/
3253
class Alert {
3254
/**
3255
* @param {!WebDriver} driver The driver controlling the browser this alert
3256
* is attached to.
3257
* @param {string} text The message text displayed with this alert.
3258
*/
3259
constructor(driver, text) {
3260
/** @private {!WebDriver} */
3261
this.driver_ = driver
3262
3263
/** @private {!Promise<string>} */
3264
this.text_ = Promise.resolve(text)
3265
}
3266
3267
/**
3268
* Retrieves the message text displayed with this alert. For instance, if the
3269
* alert were opened with alert("hello"), then this would return "hello".
3270
*
3271
* @return {!Promise<string>} A promise that will be
3272
* resolved to the text displayed with this alert.
3273
*/
3274
getText() {
3275
return this.text_
3276
}
3277
3278
/**
3279
* Accepts this alert.
3280
*
3281
* @return {!Promise<void>} A promise that will be resolved
3282
* when this command has completed.
3283
*/
3284
accept() {
3285
return this.driver_.execute(new command.Command(command.Name.ACCEPT_ALERT))
3286
}
3287
3288
/**
3289
* Dismisses this alert.
3290
*
3291
* @return {!Promise<void>} A promise that will be resolved
3292
* when this command has completed.
3293
*/
3294
dismiss() {
3295
return this.driver_.execute(new command.Command(command.Name.DISMISS_ALERT))
3296
}
3297
3298
/**
3299
* Sets the response text on this alert. This command will return an error if
3300
* the underlying alert does not support response text (e.g. window.alert and
3301
* window.confirm).
3302
*
3303
* @param {string} text The text to set.
3304
* @return {!Promise<void>} A promise that will be resolved
3305
* when this command has completed.
3306
*/
3307
sendKeys(text) {
3308
return this.driver_.execute(new command.Command(command.Name.SET_ALERT_TEXT).setParameter('text', text))
3309
}
3310
}
3311
3312
/**
3313
* AlertPromise is a promise that will be fulfilled with an Alert. This promise
3314
* serves as a forward proxy on an Alert, allowing calls to be scheduled
3315
* directly on this instance before the underlying Alert has been fulfilled. In
3316
* other words, the following two statements are equivalent:
3317
*
3318
* driver.switchTo().alert().dismiss();
3319
* driver.switchTo().alert().then(function(alert) {
3320
* return alert.dismiss();
3321
* });
3322
*
3323
* @implements {IThenable<!Alert>}
3324
* @final
3325
*/
3326
class AlertPromise extends Alert {
3327
/**
3328
* @param {!WebDriver} driver The driver controlling the browser this
3329
* alert is attached to.
3330
* @param {!Promise<!Alert>} alert A thenable
3331
* that will be fulfilled with the promised alert.
3332
*/
3333
constructor(driver, alert) {
3334
super(driver, 'unused')
3335
3336
/** @override */
3337
this.then = alert.then.bind(alert)
3338
3339
/** @override */
3340
this.catch = alert.catch.bind(alert)
3341
3342
/**
3343
* Defer returning text until the promised alert has been resolved.
3344
* @override
3345
*/
3346
this.getText = function () {
3347
return alert.then(function (alert) {
3348
return alert.getText()
3349
})
3350
}
3351
3352
/**
3353
* Defers action until the alert has been located.
3354
* @override
3355
*/
3356
this.accept = function () {
3357
return alert.then(function (alert) {
3358
return alert.accept()
3359
})
3360
}
3361
3362
/**
3363
* Defers action until the alert has been located.
3364
* @override
3365
*/
3366
this.dismiss = function () {
3367
return alert.then(function (alert) {
3368
return alert.dismiss()
3369
})
3370
}
3371
3372
/**
3373
* Defers action until the alert has been located.
3374
* @override
3375
*/
3376
this.sendKeys = function (text) {
3377
return alert.then(function (alert) {
3378
return alert.sendKeys(text)
3379
})
3380
}
3381
}
3382
}
3383
3384
// PUBLIC API
3385
3386
module.exports = {
3387
Alert,
3388
AlertPromise,
3389
Condition,
3390
Logs,
3391
Navigation,
3392
Options,
3393
ShadowRoot,
3394
TargetLocator,
3395
IWebDriver,
3396
WebDriver,
3397
WebElement,
3398
WebElementCondition,
3399
WebElementPromise,
3400
Window,
3401
}
3402
3403