Path: blob/trunk/javascript/selenium-webdriver/lib/webdriver.js
2884 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617/**18* @fileoverview The heart of the WebDriver JavaScript API.19*/2021'use strict'2223const by = require('./by')24const { RelativeBy } = require('./by')25const command = require('./command')26const error = require('./error')27const input = require('./input')28const logging = require('./logging')29const promise = require('./promise')30const Symbols = require('./symbols')31const cdp = require('../devtools/CDPConnection')32const WebSocket = require('ws')33const http = require('../http/index')34const fs = require('node:fs')35const { Capabilities } = require('./capabilities')36const path = require('node:path')37const { NoSuchElementError } = require('./error')38const cdpTargets = ['page', 'browser']39const { Credential } = require('./virtual_authenticator')40const webElement = require('./webelement')41const { isObject } = require('./util')42const BIDI = require('../bidi')43const { PinnedScript } = require('./pinnedScript')44const JSZip = require('jszip')45const Script = require('./script')46const Network = require('./network')47const Dialog = require('./fedcm/dialog')4849// Capability names that are defined in the W3C spec.50const W3C_CAPABILITY_NAMES = new Set([51'acceptInsecureCerts',52'browserName',53'browserVersion',54'pageLoadStrategy',55'platformName',56'proxy',57'setWindowRect',58'strictFileInteractability',59'timeouts',60'unhandledPromptBehavior',61'webSocketUrl',62])6364/**65* Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait66* command}.67*68* @template OUT69*/70class Condition {71/**72* @param {string} message A descriptive error message. Should complete the73* sentence "Waiting [...]"74* @param {function(!WebDriver): OUT} fn The condition function to75* evaluate on each iteration of the wait loop.76*/77constructor(message, fn) {78/** @private {string} */79this.description_ = 'Waiting ' + message8081/** @type {function(!WebDriver): OUT} */82this.fn = fn83}8485/** @return {string} A description of this condition. */86description() {87return this.description_88}89}9091/**92* Defines a condition that will result in a {@link WebElement}.93*94* @extends {Condition<!(WebElement|IThenable<!WebElement>)>}95*/96class WebElementCondition extends Condition {97/**98* @param {string} message A descriptive error message. Should complete the99* sentence "Waiting [...]"100* @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}101* fn The condition function to evaluate on each iteration of the wait102* loop.103*/104constructor(message, fn) {105super(message, fn)106}107}108109//////////////////////////////////////////////////////////////////////////////110//111// WebDriver112//113//////////////////////////////////////////////////////////////////////////////114115/**116* Translates a command to its wire-protocol representation before passing it117* to the given `executor` for execution.118* @param {!command.Executor} executor The executor to use.119* @param {!command.Command} command The command to execute.120* @return {!Promise} A promise that will resolve with the command response.121*/122function executeCommand(executor, command) {123return toWireValue(command.getParameters()).then(function (parameters) {124command.setParameters(parameters)125return executor.execute(command)126})127}128129/**130* Converts an object to its JSON representation in the WebDriver wire protocol.131* When converting values of type object, the following steps will be taken:132* <ol>133* <li>if the object is a WebElement, the return value will be the element's134* server ID135* <li>if the object defines a {@link Symbols.serialize} method, this algorithm136* will be recursively applied to the object's serialized representation137* <li>if the object provides a "toJSON" function, this algorithm will138* recursively be applied to the result of that function139* <li>otherwise, the value of each key will be recursively converted according140* to the rules above.141* </ol>142*143* @param {*} obj The object to convert.144* @return {!Promise<?>} A promise that will resolve to the input value's JSON145* representation.146*/147async function toWireValue(obj) {148let value = await Promise.resolve(obj)149if (value === void 0 || value === null) {150return value151}152153if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {154return value155}156157if (Array.isArray(value)) {158return convertKeys(value)159}160161if (typeof value === 'function') {162return '' + value163}164165if (typeof value[Symbols.serialize] === 'function') {166return toWireValue(value[Symbols.serialize]())167} else if (typeof value.toJSON === 'function') {168return toWireValue(value.toJSON())169}170return convertKeys(value)171}172173async function convertKeys(obj) {174const isArray = Array.isArray(obj)175const numKeys = isArray ? obj.length : Object.keys(obj).length176const ret = isArray ? new Array(numKeys) : {}177if (!numKeys) {178return ret179}180181async function forEachKey(obj, fn) {182if (Array.isArray(obj)) {183for (let i = 0, n = obj.length; i < n; i++) {184await fn(obj[i], i)185}186} else {187for (let key in obj) {188await fn(obj[key], key)189}190}191}192193await forEachKey(obj, async function (value, key) {194ret[key] = await toWireValue(value)195})196197return ret198}199200/**201* Converts a value from its JSON representation according to the WebDriver wire202* protocol. Any JSON object that defines a WebElement ID will be decoded to a203* {@link WebElement} object. All other values will be passed through as is.204*205* @param {!WebDriver} driver The driver to use as the parent of any unwrapped206* {@link WebElement} values.207* @param {*} value The value to convert.208* @return {*} The converted value.209*/210function fromWireValue(driver, value) {211if (Array.isArray(value)) {212value = value.map((v) => fromWireValue(driver, v))213} else if (WebElement.isId(value)) {214let id = WebElement.extractId(value)215value = new WebElement(driver, id)216} else if (ShadowRoot.isId(value)) {217let id = ShadowRoot.extractId(value)218value = new ShadowRoot(driver, id)219} else if (isObject(value)) {220let result = {}221for (let key in value) {222if (Object.prototype.hasOwnProperty.call(value, key)) {223result[key] = fromWireValue(driver, value[key])224}225}226value = result227}228return value229}230231/**232* Resolves a wait message from either a function or a string.233* @param {(string|Function)=} message An optional message to use if the wait times out.234* @return {string} The resolved message235*/236function resolveWaitMessage(message) {237return message ? `${typeof message === 'function' ? message() : message}\n` : ''238}239240/**241* Structural interface for a WebDriver client.242*243* @record244*/245class IWebDriver {246/**247* Executes the provided {@link command.Command} using this driver's248* {@link command.Executor}.249*250* @param {!command.Command} command The command to schedule.251* @return {!Promise<T>} A promise that will be resolved with the command252* result.253* @template T254*/255execute(command) {} // eslint-disable-line256257/**258* Sets the {@linkplain input.FileDetector file detector} that should be259* used with this instance.260* @param {input.FileDetector} detector The detector to use or `null`.261*/262setFileDetector(detector) {} // eslint-disable-line263264/**265* @return {!command.Executor} The command executor used by this instance.266*/267getExecutor() {}268269/**270* @return {!Promise<!Session>} A promise for this client's session.271*/272getSession() {}273274/**275* @return {!Promise<!Capabilities>} A promise that will resolve with276* the instance's capabilities.277*/278getCapabilities() {}279280/**281* Terminates the browser session. After calling quit, this instance will be282* invalidated and may no longer be used to issue commands against the283* browser.284*285* @return {!Promise<void>} A promise that will be resolved when the286* command has completed.287*/288quit() {}289290/**291* Creates a new action sequence using this driver. The sequence will not be292* submitted for execution until293* {@link ./input.Actions#perform Actions.perform()} is called.294*295* @param {{async: (boolean|undefined),296* bridge: (boolean|undefined)}=} options Configuration options for297* the action sequence (see {@link ./input.Actions Actions} documentation298* for details).299* @return {!input.Actions} A new action sequence for this instance.300*/301actions(options) {} // eslint-disable-line302303/**304* Executes a snippet of JavaScript in the context of the currently selected305* frame or window. The script fragment will be executed as the body of an306* anonymous function. If the script is provided as a function object, that307* function will be converted to a string for injection into the target308* window.309*310* Any arguments provided in addition to the script will be included as script311* arguments and may be referenced using the `arguments` object. Arguments may312* be a boolean, number, string, or {@linkplain WebElement}. Arrays and313* objects may also be used as script arguments as long as each item adheres314* to the types previously mentioned.315*316* The script may refer to any variables accessible from the current window.317* Furthermore, the script will execute in the window's context, thus318* `document` may be used to refer to the current document. Any local319* variables will not be available once the script has finished executing,320* though global variables will persist.321*322* If the script has a return value (i.e. if the script contains a return323* statement), then the following steps will be taken for resolving this324* functions return value:325*326* - For a HTML element, the value will resolve to a {@linkplain WebElement}327* - Null and undefined return values will resolve to null</li>328* - Booleans, numbers, and strings will resolve as is</li>329* - Functions will resolve to their string representation</li>330* - For arrays and objects, each member item will be converted according to331* the rules above332*333* @param {!(string|Function)} script The script to execute.334* @param {...*} args The arguments to pass to the script.335* @return {!IThenable<T>} A promise that will resolve to the336* scripts return value.337* @template T338*/339executeScript(script, ...args) {} // eslint-disable-line340341/**342* Executes a snippet of asynchronous JavaScript in the context of the343* currently selected frame or window. The script fragment will be executed as344* the body of an anonymous function. If the script is provided as a function345* object, that function will be converted to a string for injection into the346* target window.347*348* Any arguments provided in addition to the script will be included as script349* arguments and may be referenced using the `arguments` object. Arguments may350* be a boolean, number, string, or {@linkplain WebElement}. Arrays and351* objects may also be used as script arguments as long as each item adheres352* to the types previously mentioned.353*354* Unlike executing synchronous JavaScript with {@link #executeScript},355* scripts executed with this function must explicitly signal they are356* finished by invoking the provided callback. This callback will always be357* injected into the executed function as the last argument, and thus may be358* referenced with `arguments[arguments.length - 1]`. The following steps359* will be taken for resolving this functions return value against the first360* argument to the script's callback function:361*362* - For a HTML element, the value will resolve to a {@link WebElement}363* - Null and undefined return values will resolve to null364* - Booleans, numbers, and strings will resolve as is365* - Functions will resolve to their string representation366* - For arrays and objects, each member item will be converted according to367* the rules above368*369* __Example #1:__ Performing a sleep that is synchronized with the currently370* selected window:371*372* var start = new Date().getTime();373* driver.executeAsyncScript(374* 'window.setTimeout(arguments[arguments.length - 1], 500);').375* then(function() {376* console.log(377* 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');378* });379*380* __Example #2:__ Synchronizing a test with an AJAX application:381*382* var button = driver.findElement(By.id('compose-button'));383* button.click();384* driver.executeAsyncScript(385* 'var callback = arguments[arguments.length - 1];' +386* 'mailClient.getComposeWindowWidget().onload(callback);');387* driver.switchTo().frame('composeWidget');388* driver.findElement(By.id('to')).sendKeys('[email protected]');389*390* __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In391* this example, the inject script is specified with a function literal. When392* using this format, the function is converted to a string for injection, so393* it should not reference any symbols not defined in the scope of the page394* under test.395*396* driver.executeAsyncScript(function() {397* var callback = arguments[arguments.length - 1];398* var xhr = new XMLHttpRequest();399* xhr.open("GET", "/resource/data.json", true);400* xhr.onreadystatechange = function() {401* if (xhr.readyState == 4) {402* callback(xhr.responseText);403* }404* };405* xhr.send('');406* }).then(function(str) {407* console.log(JSON.parse(str)['food']);408* });409*410* @param {!(string|Function)} script The script to execute.411* @param {...*} args The arguments to pass to the script.412* @return {!IThenable<T>} A promise that will resolve to the scripts return413* value.414* @template T415*/416executeAsyncScript(script, ...args) {} // eslint-disable-line417418/**419* Waits for a condition to evaluate to a "truthy" value. The condition may be420* specified by a {@link Condition}, as a custom function, or as any421* promise-like thenable.422*423* For a {@link Condition} or function, the wait will repeatedly424* evaluate the condition until it returns a truthy value. If any errors occur425* while evaluating the condition, they will be allowed to propagate. In the426* event a condition returns a {@linkplain Promise}, the polling loop will427* wait for it to be resolved and use the resolved value for whether the428* condition has been satisfied. The resolution time for a promise is always429* factored into whether a wait has timed out.430*431* If the provided condition is a {@link WebElementCondition}, then432* the wait will return a {@link WebElementPromise} that will resolve to the433* element that satisfied the condition.434*435* _Example:_ waiting up to 10 seconds for an element to be present on the436* page.437*438* async function example() {439* let button =440* await driver.wait(until.elementLocated(By.id('foo')), 10000);441* await button.click();442* }443*444* @param {!(IThenable<T>|445* Condition<T>|446* function(!WebDriver): T)} condition The condition to447* wait on, defined as a promise, condition object, or a function to448* evaluate as a condition.449* @param {number=} timeout The duration in milliseconds, how long to wait450* for the condition to be true.451* @param {(string|Function)=} message An optional message to use if the wait times out.452* @param {number=} pollTimeout The duration in milliseconds, how long to453* wait between polling the condition.454* @return {!(IThenable<T>|WebElementPromise)} A promise that will be455* resolved with the first truthy value returned by the condition456* function, or rejected if the condition times out. If the input457* condition is an instance of a {@link WebElementCondition},458* the returned value will be a {@link WebElementPromise}.459* @throws {TypeError} if the provided `condition` is not a valid type.460* @template T461*/462wait(463condition, // eslint-disable-line464timeout = undefined, // eslint-disable-line465message = undefined, // eslint-disable-line466pollTimeout = undefined, // eslint-disable-line467) {}468469/**470* Makes the driver sleep for the given amount of time.471*472* @param {number} ms The amount of time, in milliseconds, to sleep.473* @return {!Promise<void>} A promise that will be resolved when the sleep has474* finished.475*/476sleep(ms) {} // eslint-disable-line477478/**479* Retrieves the current window handle.480*481* @return {!Promise<string>} A promise that will be resolved with the current482* window handle.483*/484getWindowHandle() {}485486/**487* Retrieves a list of all available window handles.488*489* @return {!Promise<!Array<string>>} A promise that will be resolved with an490* array of window handles.491*/492getAllWindowHandles() {}493494/**495* Retrieves the current page's source. The returned source is a representation496* of the underlying DOM: do not expect it to be formatted or escaped in the497* same way as the raw response sent from the web server.498*499* @return {!Promise<string>} A promise that will be resolved with the current500* page source.501*/502getPageSource() {}503504/**505* Closes the current window.506*507* @return {!Promise<void>} A promise that will be resolved when this command508* has completed.509*/510close() {}511512/**513* Navigates to the given URL.514*515* @param {string} url The fully qualified URL to open.516* @return {!Promise<void>} A promise that will be resolved when the document517* has finished loading.518*/519get(url) {} // eslint-disable-line520521/**522* Retrieves the URL for the current page.523*524* @return {!Promise<string>} A promise that will be resolved with the525* current URL.526*/527getCurrentUrl() {}528529/**530* Retrieves the current page title.531*532* @return {!Promise<string>} A promise that will be resolved with the current533* page's title.534*/535getTitle() {}536537/**538* Locates an element on the page. If the element cannot be found, a539* {@link error.NoSuchElementError} will be returned by the driver.540*541* This function should not be used to test whether an element is present on542* the page. Rather, you should use {@link #findElements}:543*544* driver.findElements(By.id('foo'))545* .then(found => console.log('Element found? %s', !!found.length));546*547* The search criteria for an element may be defined using one of the548* factories in the {@link webdriver.By} namespace, or as a short-hand549* {@link webdriver.By.Hash} object. For example, the following two statements550* are equivalent:551*552* var e1 = driver.findElement(By.id('foo'));553* var e2 = driver.findElement({id:'foo'});554*555* You may also provide a custom locator function, which takes as input this556* instance and returns a {@link WebElement}, or a promise that will resolve557* to a WebElement. If the returned promise resolves to an array of558* WebElements, WebDriver will use the first element. For example, to find the559* first visible link on a page, you could write:560*561* var link = driver.findElement(firstVisibleLink);562*563* function firstVisibleLink(driver) {564* var links = driver.findElements(By.tagName('a'));565* return promise.filter(links, function(link) {566* return link.isDisplayed();567* });568* }569*570* @param {!(by.By|Function)} locator The locator to use.571* @return {!WebElementPromise} A WebElement that can be used to issue572* commands against the located element. If the element is not found, the573* element will be invalidated and all scheduled commands aborted.574*/575findElement(locator) {} // eslint-disable-line576577/**578* Search for multiple elements on the page. Refer to the documentation on579* {@link #findElement(by)} for information on element locator strategies.580*581* @param {!(by.By|Function)} locator The locator to use.582* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an583* array of WebElements.584*/585findElements(locator) {} // eslint-disable-line586587/**588* Takes a screenshot of the current page. The driver makes the best effort to589* return a screenshot of the following, in order of preference:590*591* 1. Entire page592* 2. Current window593* 3. Visible portion of the current frame594* 4. The entire display containing the browser595*596* @return {!Promise<string>} A promise that will be resolved to the597* screenshot as a base-64 encoded PNG.598*/599takeScreenshot() {}600601/**602* @return {!Options} The options interface for this instance.603*/604manage() {}605606/**607* @return {!Navigation} The navigation interface for this instance.608*/609navigate() {}610611/**612* @return {!TargetLocator} The target locator interface for this613* instance.614*/615switchTo() {}616617/**618*619* Takes a PDF of the current page. The driver makes a best effort to620* return a PDF based on the provided parameters.621*622* @param {{orientation:(string|undefined),623* scale:(number|undefined),624* background:(boolean|undefined),625* width:(number|undefined),626* height:(number|undefined),627* top:(number|undefined),628* bottom:(number|undefined),629* left:(number|undefined),630* right:(number|undefined),631* shrinkToFit:(boolean|undefined),632* pageRanges:(Array|undefined)}} options633*/634printPage(options) {} // eslint-disable-line635}636637/**638* @param {!Capabilities} capabilities A capabilities object.639* @return {!Capabilities} A copy of the parameter capabilities, omitting640* capability names that are not valid W3C names.641*/642function filterNonW3CCaps(capabilities) {643let newCaps = new Capabilities(capabilities)644for (let k of newCaps.keys()) {645// Any key containing a colon is a vendor-prefixed capability.646if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) {647newCaps.delete(k)648}649}650return newCaps651}652653/**654* Each WebDriver instance provides automated control over a browser session.655*656* @implements {IWebDriver}657*/658class WebDriver {659#script = undefined660#network = undefined661/**662* @param {!(./session.Session|IThenable<!./session.Session>)} session Either663* a known session or a promise that will be resolved to a session.664* @param {!command.Executor} executor The executor to use when sending665* commands to the browser.666* @param {(function(this: void): ?)=} onQuit A function to call, if any,667* when the session is terminated.668*/669constructor(session, executor, onQuit = undefined) {670/** @private {!Promise<!Session>} */671this.session_ = Promise.resolve(session)672673// If session is a rejected promise, add a no-op rejection handler.674// This effectively hides setup errors until users attempt to interact675// with the session.676this.session_.catch(function () {})677678/** @private {!command.Executor} */679this.executor_ = executor680681/** @private {input.FileDetector} */682this.fileDetector_ = null683684/** @private @const {(function(this: void): ?|undefined)} */685this.onQuit_ = onQuit686687/** @private {./virtual_authenticator}*/688this.authenticatorId_ = null689690this.pinnedScripts_ = {}691}692693/**694* Creates a new WebDriver session.695*696* This function will always return a WebDriver instance. If there is an error697* creating the session, such as the aforementioned SessionNotCreatedError,698* the driver will have a rejected {@linkplain #getSession session} promise.699* This rejection will propagate through any subsequent commands scheduled700* on the returned WebDriver instance.701*702* let required = Capabilities.firefox();703* let driver = WebDriver.createSession(executor, {required});704*705* // If the createSession operation failed, then this command will also706* // also fail, propagating the creation failure.707* driver.get('http://www.google.com').catch(e => console.log(e));708*709* @param {!command.Executor} executor The executor to create the new session710* with.711* @param {!Capabilities} capabilities The desired capabilities for the new712* session.713* @param {(function(this: void): ?)=} onQuit A callback to invoke when714* the newly created session is terminated. This should be used to clean715* up any resources associated with the session.716* @return {!WebDriver} The driver for the newly created session.717*/718static createSession(executor, capabilities, onQuit = undefined) {719let cmd = new command.Command(command.Name.NEW_SESSION)720721// For W3C remote ends.722cmd.setParameter('capabilities', {723firstMatch: [{}],724alwaysMatch: filterNonW3CCaps(capabilities),725})726727let session = executeCommand(executor, cmd)728if (typeof onQuit === 'function') {729session = session.catch((err) => {730return Promise.resolve(onQuit.call(void 0)).then((_) => {731throw err732})733})734}735return new this(session, executor, onQuit)736}737738/** @override */739async execute(command) {740command.setParameter('sessionId', this.session_)741742let parameters = await toWireValue(command.getParameters())743command.setParameters(parameters)744let value = await this.executor_.execute(command)745return fromWireValue(this, value)746}747748/** @override */749setFileDetector(detector) {750this.fileDetector_ = detector751}752753/** @override */754getExecutor() {755return this.executor_756}757758/** @override */759getSession() {760return this.session_761}762763/** @override */764getCapabilities() {765return this.session_.then((s) => s.getCapabilities())766}767768/** @override */769quit() {770let result = this.execute(new command.Command(command.Name.QUIT))771// Delete our session ID when the quit command finishes; this will allow us772// to throw an error when attempting to use a driver post-quit.773return promise.finally(result, () => {774this.session_ = Promise.reject(775new error.NoSuchSessionError(776'This driver instance does not have a valid session ID ' +777'(did you call WebDriver.quit()?) and may no longer be used.',778),779)780781// Only want the session rejection to bubble if accessed.782this.session_.catch(function () {})783784if (this.onQuit_) {785return this.onQuit_.call(void 0)786}787788// Close the websocket connection on quit789// If the websocket connection is not closed,790// and we are running CDP sessions against the Selenium Grid,791// the node process never exits since the websocket connection is open until the Grid is shutdown.792if (this._cdpWsConnection !== undefined) {793this._cdpWsConnection.close()794}795796// Close the BiDi websocket connection797if (this._bidiConnection !== undefined) {798this._bidiConnection.close()799}800})801}802803/** @override */804actions(options) {805return new input.Actions(this, options || undefined)806}807808/** @override */809executeScript(script, ...args) {810if (typeof script === 'function') {811script = 'return (' + script + ').apply(null, arguments);'812}813814if (script && script instanceof PinnedScript) {815return this.execute(816new command.Command(command.Name.EXECUTE_SCRIPT)817.setParameter('script', script.executionScript())818.setParameter('args', args),819)820}821822return this.execute(823new command.Command(command.Name.EXECUTE_SCRIPT).setParameter('script', script).setParameter('args', args),824)825}826827/** @override */828executeAsyncScript(script, ...args) {829if (typeof script === 'function') {830script = 'return (' + script + ').apply(null, arguments);'831}832833if (script && script instanceof PinnedScript) {834return this.execute(835new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT)836.setParameter('script', script.executionScript())837.setParameter('args', args),838)839}840841return this.execute(842new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).setParameter('script', script).setParameter('args', args),843)844}845846/** @override */847wait(condition, timeout = 0, message = undefined, pollTimeout = 200) {848if (typeof timeout !== 'number' || timeout < 0) {849throw TypeError('timeout must be a number >= 0: ' + timeout)850}851852if (typeof pollTimeout !== 'number' || pollTimeout < 0) {853throw TypeError('pollTimeout must be a number >= 0: ' + pollTimeout)854}855856if (promise.isPromise(condition)) {857return new Promise((resolve, reject) => {858if (!timeout) {859resolve(condition)860return861}862863let start = Date.now()864let timer = setTimeout(function () {865timer = null866try {867let timeoutMessage = resolveWaitMessage(message)868reject(869new error.TimeoutError(870`${timeoutMessage}Timed out waiting for promise to resolve after ${Date.now() - start}ms`,871),872)873} catch (ex) {874reject(875new error.TimeoutError(876`${ex.message}\nTimed out waiting for promise to resolve after ${Date.now() - start}ms`,877),878)879}880}, timeout)881const clearTimer = () => timer && clearTimeout(timer)882883/** @type {!IThenable} */ condition.then(884function (value) {885clearTimer()886resolve(value)887},888function (error) {889clearTimer()890reject(error)891},892)893})894}895896let fn = /** @type {!Function} */ (condition)897if (condition instanceof Condition) {898message = message || condition.description()899fn = condition.fn900}901902if (typeof fn !== 'function') {903throw TypeError('Wait condition must be a promise-like object, function, or a ' + 'Condition object')904}905906const driver = this907908function evaluateCondition() {909return new Promise((resolve, reject) => {910try {911resolve(fn(driver))912} catch (ex) {913reject(ex)914}915})916}917918let result = new Promise((resolve, reject) => {919const startTime = Date.now()920const pollCondition = async () => {921evaluateCondition().then(function (value) {922const elapsed = Date.now() - startTime923if (value) {924resolve(value)925} else if (timeout && elapsed >= timeout) {926try {927let timeoutMessage = resolveWaitMessage(message)928reject(new error.TimeoutError(`${timeoutMessage}Wait timed out after ${elapsed}ms`))929} catch (ex) {930reject(new error.TimeoutError(`${ex.message}\nWait timed out after ${elapsed}ms`))931}932} else {933setTimeout(pollCondition, pollTimeout)934}935}, reject)936}937pollCondition()938})939940if (condition instanceof WebElementCondition) {941result = new WebElementPromise(942this,943result.then(function (value) {944if (!(value instanceof WebElement)) {945throw TypeError(946'WebElementCondition did not resolve to a WebElement: ' + Object.prototype.toString.call(value),947)948}949return value950}),951)952}953return result954}955956/** @override */957sleep(ms) {958return new Promise((resolve) => setTimeout(resolve, ms))959}960961/** @override */962getWindowHandle() {963return this.execute(new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE))964}965966/** @override */967getAllWindowHandles() {968return this.execute(new command.Command(command.Name.GET_WINDOW_HANDLES))969}970971/** @override */972getPageSource() {973return this.execute(new command.Command(command.Name.GET_PAGE_SOURCE))974}975976/** @override */977close() {978return this.execute(new command.Command(command.Name.CLOSE))979}980981/** @override */982get(url) {983return this.navigate().to(url)984}985986/** @override */987getCurrentUrl() {988return this.execute(new command.Command(command.Name.GET_CURRENT_URL))989}990991/** @override */992getTitle() {993return this.execute(new command.Command(command.Name.GET_TITLE))994}995996/** @override */997findElement(locator) {998let id999let cmd = null10001001if (locator instanceof RelativeBy) {1002cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall())1003} else {1004locator = by.checkedLocator(locator)1005}10061007if (typeof locator === 'function') {1008id = this.findElementInternal_(locator, this)1009return new WebElementPromise(this, id)1010} else if (cmd === null) {1011cmd = new command.Command(command.Name.FIND_ELEMENT)1012.setParameter('using', locator.using)1013.setParameter('value', locator.value)1014}10151016id = this.execute(cmd)1017if (locator instanceof RelativeBy) {1018return this.normalize_(id)1019} else {1020return new WebElementPromise(this, id)1021}1022}10231024/**1025* @param {!Function} webElementPromise The webElement in unresolved state1026* @return {!Promise<!WebElement>} First single WebElement from array of resolved promises1027*/1028async normalize_(webElementPromise) {1029let result = await webElementPromise1030if (result.length === 0) {1031throw new NoSuchElementError('Cannot locate an element with provided parameters')1032} else {1033return result[0]1034}1035}10361037/**1038* @param {!Function} locatorFn The locator function to use.1039* @param {!(WebDriver|WebElement)} context The search context.1040* @return {!Promise<!WebElement>} A promise that will resolve to a list of1041* WebElements.1042* @private1043*/1044async findElementInternal_(locatorFn, context) {1045let result = await locatorFn(context)1046if (Array.isArray(result)) {1047result = result[0]1048}1049if (!(result instanceof WebElement)) {1050throw new TypeError('Custom locator did not return a WebElement')1051}1052return result1053}10541055/** @override */1056async findElements(locator) {1057let cmd = null1058if (locator instanceof RelativeBy) {1059cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall())1060} else {1061locator = by.checkedLocator(locator)1062}10631064if (typeof locator === 'function') {1065return this.findElementsInternal_(locator, this)1066} else if (cmd === null) {1067cmd = new command.Command(command.Name.FIND_ELEMENTS)1068.setParameter('using', locator.using)1069.setParameter('value', locator.value)1070}1071try {1072let res = await this.execute(cmd)1073return Array.isArray(res) ? res : []1074} catch (ex) {1075if (ex instanceof error.NoSuchElementError) {1076return []1077}1078throw ex1079}1080}10811082/**1083* @param {!Function} locatorFn The locator function to use.1084* @param {!(WebDriver|WebElement)} context The search context.1085* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an1086* array of WebElements.1087* @private1088*/1089async findElementsInternal_(locatorFn, context) {1090const result = await locatorFn(context)1091if (result instanceof WebElement) {1092return [result]1093}10941095if (!Array.isArray(result)) {1096return []1097}10981099return result.filter(function (item) {1100return item instanceof WebElement1101})1102}11031104/** @override */1105takeScreenshot() {1106return this.execute(new command.Command(command.Name.SCREENSHOT))1107}11081109setDelayEnabled(enabled) {1110return this.execute(new command.Command(command.Name.SET_DELAY_ENABLED).setParameter('enabled', enabled))1111}11121113resetCooldown() {1114return this.execute(new command.Command(command.Name.RESET_COOLDOWN))1115}11161117getFederalCredentialManagementDialog() {1118return new Dialog(this)1119}11201121/** @override */1122manage() {1123return new Options(this)1124}11251126/** @override */1127navigate() {1128return new Navigation(this)1129}11301131/** @override */1132switchTo() {1133return new TargetLocator(this)1134}11351136script() {1137// The Script calls the LogInspector which maintains state of the callbacks.1138// Returning a new instance of the same driver will not work while removing callbacks.1139if (this.#script === undefined) {1140this.#script = new Script(this)1141}11421143return this.#script1144}11451146network() {1147// The Network maintains state of the callbacks.1148// Returning a new instance of the same driver will not work while removing callbacks.1149if (this.#network === undefined) {1150this.#network = new Network(this)1151}11521153return this.#network1154}11551156validatePrintPageParams(keys, object) {1157let page = {}1158let margin = {}1159let data1160Object.keys(keys).forEach(function (key) {1161data = keys[key]1162let obj = {1163orientation: function () {1164object.orientation = data1165},11661167scale: function () {1168object.scale = data1169},11701171background: function () {1172object.background = data1173},11741175width: function () {1176page.width = data1177object.page = page1178},11791180height: function () {1181page.height = data1182object.page = page1183},11841185top: function () {1186margin.top = data1187object.margin = margin1188},11891190left: function () {1191margin.left = data1192object.margin = margin1193},11941195bottom: function () {1196margin.bottom = data1197object.margin = margin1198},11991200right: function () {1201margin.right = data1202object.margin = margin1203},12041205shrinkToFit: function () {1206object.shrinkToFit = data1207},12081209pageRanges: function () {1210object.pageRanges = data1211},1212}12131214if (!Object.prototype.hasOwnProperty.call(obj, key)) {1215throw new error.InvalidArgumentError(`Invalid Argument '${key}'`)1216} else {1217obj[key]()1218}1219})12201221return object1222}12231224/** @override */1225printPage(options = {}) {1226let keys = options1227let params = {}1228let resultObj12291230let self = this1231resultObj = self.validatePrintPageParams(keys, params)12321233return this.execute(new command.Command(command.Name.PRINT_PAGE).setParameters(resultObj))1234}12351236/**1237* Creates a new WebSocket connection.1238* @return {!Promise<resolved>} A new CDP instance.1239*/1240async createCDPConnection(target) {1241let debuggerUrl = null12421243const caps = await this.getCapabilities()12441245if (caps['map_'].get('browserName') === 'firefox') {1246throw new Error('CDP support for Firefox is removed. Please switch to WebDriver BiDi.')1247}12481249if (process.env.SELENIUM_REMOTE_URL) {1250const host = new URL(process.env.SELENIUM_REMOTE_URL).host1251const sessionId = await this.getSession().then((session) => session.getId())1252debuggerUrl = `ws://${host}/session/${sessionId}/se/cdp`1253} else {1254const seCdp = caps['map_'].get('se:cdp')1255const vendorInfo = caps['map_'].get('goog:chromeOptions') || caps['map_'].get('ms:edgeOptions') || new Map()1256debuggerUrl = seCdp || vendorInfo['debuggerAddress'] || vendorInfo1257}1258this._wsUrl = await this.getWsUrl(debuggerUrl, target, caps)1259return new Promise((resolve, reject) => {1260try {1261this._cdpWsConnection = new WebSocket(this._wsUrl.replace('localhost', '127.0.0.1'))1262this._cdpConnection = new cdp.CdpConnection(this._cdpWsConnection)1263} catch (err) {1264reject(err)1265return1266}12671268this._cdpWsConnection.on('open', async () => {1269await this.getCdpTargets()1270})12711272this._cdpWsConnection.on('message', async (message) => {1273const params = JSON.parse(message)1274if (params.result) {1275if (params.result.targetInfos) {1276const targets = params.result.targetInfos1277const page = targets.find((info) => info.type === 'page')1278if (page) {1279this.targetID = page.targetId1280this._cdpConnection.execute('Target.attachToTarget', { targetId: this.targetID, flatten: true }, null)1281} else {1282reject('Unable to find Page target.')1283}1284}1285if (params.result.sessionId) {1286this.sessionId = params.result.sessionId1287this._cdpConnection.sessionId = this.sessionId1288resolve(this._cdpConnection)1289}1290}1291})12921293this._cdpWsConnection.on('error', (error) => {1294reject(error)1295})1296})1297}12981299async getCdpTargets() {1300this._cdpConnection.execute('Target.getTargets')1301}13021303/**1304* Initiates bidi connection using 'webSocketUrl'1305* @returns {BIDI}1306*/1307async getBidi() {1308if (this._bidiConnection === undefined) {1309const caps = await this.getCapabilities()1310let WebSocketUrl = caps['map_'].get('webSocketUrl')1311this._bidiConnection = new BIDI(WebSocketUrl.replace('localhost', '127.0.0.1'))1312}1313return this._bidiConnection1314}13151316/**1317* Retrieves 'webSocketDebuggerUrl' by sending a http request using debugger address1318* @param {string} debuggerAddress1319* @param target1320* @param caps1321* @return {string} Returns parsed webSocketDebuggerUrl obtained from the http request1322*/1323async getWsUrl(debuggerAddress, target, caps) {1324if (target && cdpTargets.indexOf(target.toLowerCase()) === -1) {1325throw new error.InvalidArgumentError('invalid target value')1326}13271328if (debuggerAddress.match(/\/se\/cdp/)) {1329return debuggerAddress1330}13311332let path1333if (target === 'page' && caps['map_'].get('browserName') !== 'firefox') {1334path = '/json'1335} else if (target === 'page' && caps['map_'].get('browserName') === 'firefox') {1336path = '/json/list'1337} else {1338path = '/json/version'1339}13401341let request = new http.Request('GET', path)1342let client = new http.HttpClient('http://' + debuggerAddress)1343let response = await client.send(request)13441345if (target.toLowerCase() === 'page') {1346return JSON.parse(response.body)[0]['webSocketDebuggerUrl']1347} else {1348return JSON.parse(response.body)['webSocketDebuggerUrl']1349}1350}13511352/**1353* Sets a listener for Fetch.authRequired event from CDP1354* If event is triggered, it enters username and password1355* and allows the test to move forward1356* @param {string} username1357* @param {string} password1358* @param connection CDP Connection1359*/1360async register(username, password, connection) {1361this._cdpWsConnection.on('message', (message) => {1362const params = JSON.parse(message)13631364if (params.method === 'Fetch.authRequired') {1365const requestParams = params['params']1366connection.execute('Fetch.continueWithAuth', {1367requestId: requestParams['requestId'],1368authChallengeResponse: {1369response: 'ProvideCredentials',1370username: username,1371password: password,1372},1373})1374} else if (params.method === 'Fetch.requestPaused') {1375const requestPausedParams = params['params']1376connection.execute('Fetch.continueRequest', {1377requestId: requestPausedParams['requestId'],1378})1379}1380})13811382await connection.execute(1383'Fetch.enable',1384{1385handleAuthRequests: true,1386},1387null,1388)1389await connection.execute(1390'Network.setCacheDisabled',1391{1392cacheDisabled: true,1393},1394null,1395)1396}13971398/**1399* Handle Network interception requests1400* @param connection WebSocket connection to the browser1401* @param httpResponse Object representing what we are intercepting1402* as well as what should be returned.1403* @param callback callback called when we intercept requests.1404*/1405async onIntercept(connection, httpResponse, callback) {1406this._cdpWsConnection.on('message', (message) => {1407const params = JSON.parse(message)1408if (params.method === 'Fetch.requestPaused') {1409const requestPausedParams = params['params']1410if (requestPausedParams.request.url == httpResponse.urlToIntercept) {1411connection.execute('Fetch.fulfillRequest', {1412requestId: requestPausedParams['requestId'],1413responseCode: httpResponse.status,1414responseHeaders: httpResponse.headers,1415body: httpResponse.body,1416})1417callback()1418} else {1419connection.execute('Fetch.continueRequest', {1420requestId: requestPausedParams['requestId'],1421})1422}1423}1424})14251426await connection.execute('Fetch.enable', {}, null)1427await connection.execute(1428'Network.setCacheDisabled',1429{1430cacheDisabled: true,1431},1432null,1433)1434}14351436/**1437*1438* @param connection1439* @param callback1440* @returns {Promise<void>}1441*/1442async onLogEvent(connection, callback) {1443this._cdpWsConnection.on('message', (message) => {1444const params = JSON.parse(message)1445if (params.method === 'Runtime.consoleAPICalled') {1446const consoleEventParams = params['params']1447let event = {1448type: consoleEventParams['type'],1449timestamp: new Date(consoleEventParams['timestamp']),1450args: consoleEventParams['args'],1451}14521453callback(event)1454}14551456if (params.method === 'Log.entryAdded') {1457const logEventParams = params['params']1458const logEntry = logEventParams['entry']1459let event = {1460level: logEntry['level'],1461timestamp: new Date(logEntry['timestamp']),1462message: logEntry['text'],1463}14641465callback(event)1466}1467})1468await connection.execute('Runtime.enable', {}, null)1469}14701471/**1472*1473* @param connection1474* @param callback1475* @returns {Promise<void>}1476*/1477async onLogException(connection, callback) {1478await connection.execute('Runtime.enable', {}, null)14791480this._cdpWsConnection.on('message', (message) => {1481const params = JSON.parse(message)14821483if (params.method === 'Runtime.exceptionThrown') {1484const exceptionEventParams = params['params']1485let event = {1486exceptionDetails: exceptionEventParams['exceptionDetails'],1487timestamp: new Date(exceptionEventParams['timestamp']),1488}14891490callback(event)1491}1492})1493}14941495/**1496* @param connection1497* @param callback1498* @returns {Promise<void>}1499*/1500async logMutationEvents(connection, callback) {1501await connection.execute('Runtime.enable', {}, null)1502await connection.execute('Page.enable', {}, null)15031504await connection.execute(1505'Runtime.addBinding',1506{1507name: '__webdriver_attribute',1508},1509null,1510)15111512let mutationListener = ''1513try {1514// Depending on what is running the code it could appear in 2 different places which is why we try1515// here and then the other location1516mutationListener = fs1517.readFileSync('./javascript/selenium-webdriver/lib/atoms/mutation-listener.js', 'utf-8')1518.toString()1519} catch {1520mutationListener = fs.readFileSync(path.resolve(__dirname, './atoms/mutation-listener.js'), 'utf-8').toString()1521}15221523this.executeScript(mutationListener)15241525await connection.execute(1526'Page.addScriptToEvaluateOnNewDocument',1527{1528source: mutationListener,1529},1530null,1531)15321533this._cdpWsConnection.on('message', async (message) => {1534const params = JSON.parse(message)1535if (params.method === 'Runtime.bindingCalled') {1536let payload = JSON.parse(params['params']['payload'])1537let elements = await this.findElements({1538css: '*[data-__webdriver_id=' + by.escapeCss(payload['target']) + ']',1539})15401541if (elements.length === 0) {1542return1543}15441545let event = {1546element: elements[0],1547attribute_name: payload['name'],1548current_value: payload['value'],1549old_value: payload['oldValue'],1550}1551callback(event)1552}1553})1554}15551556async pinScript(script) {1557let pinnedScript = new PinnedScript(script)1558let connection1559if (Object.is(this._cdpConnection, undefined)) {1560connection = await this.createCDPConnection('page')1561} else {1562connection = this._cdpConnection1563}15641565await connection.execute('Page.enable', {}, null)15661567await connection.execute(1568'Runtime.evaluate',1569{1570expression: pinnedScript.creationScript(),1571},1572null,1573)15741575let result = await connection.send('Page.addScriptToEvaluateOnNewDocument', {1576source: pinnedScript.creationScript(),1577})15781579pinnedScript.scriptId = result['result']['identifier']15801581this.pinnedScripts_[pinnedScript.handle] = pinnedScript15821583return pinnedScript1584}15851586async unpinScript(script) {1587if (script && !(script instanceof PinnedScript)) {1588throw Error(`Pass valid PinnedScript object. Received: ${script}`)1589}15901591if (script.handle in this.pinnedScripts_) {1592let connection1593if (Object.is(this._cdpConnection, undefined)) {1594connection = this.createCDPConnection('page')1595} else {1596connection = this._cdpConnection1597}15981599await connection.execute('Page.enable', {}, null)16001601await connection.execute(1602'Runtime.evaluate',1603{1604expression: script.removalScript(),1605},1606null,1607)16081609await connection.execute(1610'Page.removeScriptToEvaluateOnLoad',1611{1612identifier: script.scriptId,1613},1614null,1615)16161617delete this.pinnedScripts_[script.handle]1618}1619}16201621/**1622*1623* @returns The value of authenticator ID added1624*/1625virtualAuthenticatorId() {1626return this.authenticatorId_1627}16281629/**1630* Adds a virtual authenticator with the given options.1631* @param options VirtualAuthenticatorOptions object to set authenticator options.1632*/1633async addVirtualAuthenticator(options) {1634this.authenticatorId_ = await this.execute(1635new command.Command(command.Name.ADD_VIRTUAL_AUTHENTICATOR).setParameters(options.toDict()),1636)1637}16381639/**1640* Removes a previously added virtual authenticator. The authenticator is no1641* longer valid after removal, so no methods may be called.1642*/1643async removeVirtualAuthenticator() {1644await this.execute(1645new command.Command(command.Name.REMOVE_VIRTUAL_AUTHENTICATOR).setParameter(1646'authenticatorId',1647this.authenticatorId_,1648),1649)1650this.authenticatorId_ = null1651}16521653/**1654* Injects a credential into the authenticator.1655* @param credential Credential to be added1656*/1657async addCredential(credential) {1658credential = credential.toDict()1659credential['authenticatorId'] = this.authenticatorId_1660await this.execute(new command.Command(command.Name.ADD_CREDENTIAL).setParameters(credential))1661}16621663/**1664*1665* @returns The list of credentials owned by the authenticator.1666*/1667async getCredentials() {1668let credential_data = await this.execute(1669new command.Command(command.Name.GET_CREDENTIALS).setParameter('authenticatorId', this.virtualAuthenticatorId()),1670)1671var credential_list = []1672for (var i = 0; i < credential_data.length; i++) {1673credential_list.push(new Credential().fromDict(credential_data[i]))1674}1675return credential_list1676}16771678/**1679* Removes a credential from the authenticator.1680* @param credential_id The ID of the credential to be removed.1681*/1682async removeCredential(credential_id) {1683// If credential_id is not a base64url, then convert it to base64url.1684if (Array.isArray(credential_id)) {1685credential_id = Buffer.from(credential_id).toString('base64url')1686}16871688await this.execute(1689new command.Command(command.Name.REMOVE_CREDENTIAL)1690.setParameter('credentialId', credential_id)1691.setParameter('authenticatorId', this.authenticatorId_),1692)1693}16941695/**1696* Removes all the credentials from the authenticator.1697*/1698async removeAllCredentials() {1699await this.execute(1700new command.Command(command.Name.REMOVE_ALL_CREDENTIALS).setParameter('authenticatorId', this.authenticatorId_),1701)1702}17031704/**1705* Sets whether the authenticator will simulate success or fail on user verification.1706* @param verified true if the authenticator will pass user verification, false otherwise.1707*/1708async setUserVerified(verified) {1709await this.execute(1710new command.Command(command.Name.SET_USER_VERIFIED)1711.setParameter('authenticatorId', this.authenticatorId_)1712.setParameter('isUserVerified', verified),1713)1714}17151716async getDownloadableFiles() {1717const caps = await this.getCapabilities()1718if (!caps['map_'].get('se:downloadsEnabled')) {1719throw new error.WebDriverError('Downloads must be enabled in options')1720}17211722return (await this.execute(new command.Command(command.Name.GET_DOWNLOADABLE_FILES))).names1723}17241725async downloadFile(fileName, targetDirectory) {1726const caps = await this.getCapabilities()1727if (!caps['map_'].get('se:downloadsEnabled')) {1728throw new Error('Downloads must be enabled in options')1729}17301731const response = await this.execute(new command.Command(command.Name.DOWNLOAD_FILE).setParameter('name', fileName))17321733const base64Content = response.contents17341735if (!targetDirectory.endsWith('/')) {1736targetDirectory += '/'1737}17381739fs.mkdirSync(targetDirectory, { recursive: true })1740const zipFilePath = path.join(targetDirectory, `${fileName}.zip`)1741fs.writeFileSync(zipFilePath, Buffer.from(base64Content, 'base64'))17421743const zipData = fs.readFileSync(zipFilePath)1744await JSZip.loadAsync(zipData)1745.then((zip) => {1746// Iterate through each file in the zip archive1747Object.keys(zip.files).forEach(async (fileName) => {1748const fileData = await zip.files[fileName].async('nodebuffer')1749fs.writeFileSync(`${targetDirectory}/${fileName}`, fileData)1750console.log(`File extracted: ${fileName}`)1751})1752})1753.catch((error) => {1754console.error('Error unzipping file:', error)1755})1756}17571758async deleteDownloadableFiles() {1759const caps = await this.getCapabilities()1760if (!caps['map_'].get('se:downloadsEnabled')) {1761throw new error.WebDriverError('Downloads must be enabled in options')1762}17631764return await this.execute(new command.Command(command.Name.DELETE_DOWNLOADABLE_FILES))1765}1766}17671768/**1769* Interface for navigating back and forth in the browser history.1770*1771* This class should never be instantiated directly. Instead, obtain an instance1772* with1773*1774* webdriver.navigate()1775*1776* @see WebDriver#navigate()1777*/1778class Navigation {1779/**1780* @param {!WebDriver} driver The parent driver.1781* @private1782*/1783constructor(driver) {1784/** @private {!WebDriver} */1785this.driver_ = driver1786}17871788/**1789* Navigates to a new URL.1790*1791* @param {string} url The URL to navigate to.1792* @return {!Promise<void>} A promise that will be resolved when the URL1793* has been loaded.1794*/1795to(url) {1796return this.driver_.execute(new command.Command(command.Name.GET).setParameter('url', url))1797}17981799/**1800* Moves backwards in the browser history.1801*1802* @return {!Promise<void>} A promise that will be resolved when the1803* navigation event has completed.1804*/1805back() {1806return this.driver_.execute(new command.Command(command.Name.GO_BACK))1807}18081809/**1810* Moves forwards in the browser history.1811*1812* @return {!Promise<void>} A promise that will be resolved when the1813* navigation event has completed.1814*/1815forward() {1816return this.driver_.execute(new command.Command(command.Name.GO_FORWARD))1817}18181819/**1820* Refreshes the current page.1821*1822* @return {!Promise<void>} A promise that will be resolved when the1823* navigation event has completed.1824*/1825refresh() {1826return this.driver_.execute(new command.Command(command.Name.REFRESH))1827}1828}18291830/**1831* Provides methods for managing browser and driver state.1832*1833* This class should never be instantiated directly. Instead, obtain an instance1834* with {@linkplain WebDriver#manage() webdriver.manage()}.1835*/1836class Options {1837/**1838* @param {!WebDriver} driver The parent driver.1839* @private1840*/1841constructor(driver) {1842/** @private {!WebDriver} */1843this.driver_ = driver1844}18451846/**1847* Adds a cookie.1848*1849* __Sample Usage:__1850*1851* // Set a basic cookie.1852* driver.manage().addCookie({name: 'foo', value: 'bar'});1853*1854* // Set a cookie that expires in 10 minutes.1855* let expiry = new Date(Date.now() + (10 * 60 * 1000));1856* driver.manage().addCookie({name: 'foo', value: 'bar', expiry});1857*1858* // The cookie expiration may also be specified in seconds since epoch.1859* driver.manage().addCookie({1860* name: 'foo',1861* value: 'bar',1862* expiry: Math.floor(Date.now() / 1000)1863* });1864*1865* @param {!Options.Cookie} spec Defines the cookie to add.1866* @return {!Promise<void>} A promise that will be resolved1867* when the cookie has been added to the page.1868* @throws {error.InvalidArgumentError} if any of the cookie parameters are1869* invalid.1870* @throws {TypeError} if `spec` is not a cookie object.1871*/1872addCookie({ name, value, path, domain, secure, httpOnly, expiry, sameSite }) {1873// We do not allow '=' or ';' in the name.1874if (/[;=]/.test(name)) {1875throw new error.InvalidArgumentError('Invalid cookie name "' + name + '"')1876}18771878// We do not allow ';' in value.1879if (/;/.test(value)) {1880throw new error.InvalidArgumentError('Invalid cookie value "' + value + '"')1881}18821883if (typeof expiry === 'number') {1884expiry = Math.floor(expiry)1885} else if (expiry instanceof Date) {1886let date = /** @type {!Date} */ (expiry)1887expiry = Math.floor(date.getTime() / 1000)1888}18891890if (sameSite && !['Strict', 'Lax', 'None'].includes(sameSite)) {1891throw new error.InvalidArgumentError(1892`Invalid sameSite cookie value '${sameSite}'. It should be one of "Lax", "Strict" or "None"`,1893)1894}18951896if (sameSite === 'None' && !secure) {1897throw new error.InvalidArgumentError('Invalid cookie configuration: SameSite=None must be Secure')1898}18991900return this.driver_.execute(1901new command.Command(command.Name.ADD_COOKIE).setParameter('cookie', {1902name: name,1903value: value,1904path: path,1905domain: domain,1906secure: !!secure,1907httpOnly: !!httpOnly,1908expiry: expiry,1909sameSite: sameSite,1910}),1911)1912}19131914/**1915* Deletes all cookies visible to the current page.1916*1917* @return {!Promise<void>} A promise that will be resolved1918* when all cookies have been deleted.1919*/1920deleteAllCookies() {1921return this.driver_.execute(new command.Command(command.Name.DELETE_ALL_COOKIES))1922}19231924/**1925* Deletes the cookie with the given name. This command is a no-op if there is1926* no cookie with the given name visible to the current page.1927*1928* @param {string} name The name of the cookie to delete.1929* @return {!Promise<void>} A promise that will be resolved1930* when the cookie has been deleted.1931*/1932deleteCookie(name) {1933// Validate the cookie name is non-empty and properly trimmed.1934if (!name?.trim()) {1935throw new error.InvalidArgumentError('Cookie name cannot be empty')1936}19371938return this.driver_.execute(new command.Command(command.Name.DELETE_COOKIE).setParameter('name', name))1939}19401941/**1942* Retrieves all cookies visible to the current page. Each cookie will be1943* returned as a JSON object as described by the WebDriver wire protocol.1944*1945* @return {!Promise<!Array<!Options.Cookie>>} A promise that will be1946* resolved with the cookies visible to the current browsing context.1947*/1948getCookies() {1949return this.driver_.execute(new command.Command(command.Name.GET_ALL_COOKIES))1950}19511952/**1953* Retrieves the cookie with the given name. Returns null if there is no such1954* cookie. The cookie will be returned as a JSON object as described by the1955* WebDriver wire protocol.1956*1957* @param {string} name The name of the cookie to retrieve.1958* @throws {InvalidArgumentError} - If the cookie name is empty or invalid.1959* @return {!Promise<?Options.Cookie>} A promise that will be resolved1960* with the named cookie1961* @throws {error.NoSuchCookieError} if there is no such cookie.1962*/1963async getCookie(name) {1964// Validate the cookie name is non-empty and properly trimmed.1965if (!name?.trim()) {1966throw new error.InvalidArgumentError('Cookie name cannot be empty')1967}19681969try {1970const cookie = await this.driver_.execute(new command.Command(command.Name.GET_COOKIE).setParameter('name', name))1971return cookie1972} catch (err) {1973if (!(err instanceof error.UnknownCommandError) && !(err instanceof error.UnsupportedOperationError)) {1974throw err1975}1976return null1977}1978}19791980/**1981* Fetches the timeouts currently configured for the current session.1982*1983* @return {!Promise<{script: number,1984* pageLoad: number,1985* implicit: number}>} A promise that will be1986* resolved with the timeouts currently configured for the current1987* session.1988* @see #setTimeouts()1989*/1990getTimeouts() {1991return this.driver_.execute(new command.Command(command.Name.GET_TIMEOUT))1992}19931994/**1995* Sets the timeout durations associated with the current session.1996*1997* The following timeouts are supported (all timeouts are specified in1998* milliseconds):1999*2000* - `implicit` specifies the maximum amount of time to wait for an element2001* locator to succeed when {@linkplain WebDriver#findElement locating}2002* {@linkplain WebDriver#findElements elements} on the page.2003* Defaults to 0 milliseconds.2004*2005* - `pageLoad` specifies the maximum amount of time to wait for a page to2006* finishing loading. Defaults to 300000 milliseconds.2007*2008* - `script` specifies the maximum amount of time to wait for an2009* {@linkplain WebDriver#executeScript evaluated script} to run. If set to2010* `null`, the script timeout will be indefinite.2011* Defaults to 30000 milliseconds.2012*2013* @param {{script: (number|null|undefined),2014* pageLoad: (number|null|undefined),2015* implicit: (number|null|undefined)}} conf2016* The desired timeout configuration.2017* @return {!Promise<void>} A promise that will be resolved when the timeouts2018* have been set.2019* @throws {!TypeError} if an invalid options object is provided.2020* @see #getTimeouts()2021* @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>2022*/2023setTimeouts({ script, pageLoad, implicit } = {}) {2024let cmd = new command.Command(command.Name.SET_TIMEOUT)20252026let valid = false20272028function setParam(key, value) {2029if (value === null || typeof value === 'number') {2030valid = true2031cmd.setParameter(key, value)2032} else if (typeof value !== 'undefined') {2033throw TypeError('invalid timeouts configuration:' + ` expected "${key}" to be a number, got ${typeof value}`)2034}2035}20362037setParam('implicit', implicit)2038setParam('pageLoad', pageLoad)2039setParam('script', script)20402041if (valid) {2042return this.driver_.execute(cmd).catch(() => {2043// Fallback to the legacy method.2044let cmds = []2045if (typeof script === 'number') {2046cmds.push(legacyTimeout(this.driver_, 'script', script))2047}2048if (typeof implicit === 'number') {2049cmds.push(legacyTimeout(this.driver_, 'implicit', implicit))2050}2051if (typeof pageLoad === 'number') {2052cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad))2053}2054return Promise.all(cmds)2055})2056}2057throw TypeError('no timeouts specified')2058}20592060/**2061* @return {!Logs} The interface for managing driver logs.2062*/2063logs() {2064return new Logs(this.driver_)2065}20662067/**2068* @return {!Window} The interface for managing the current window.2069*/2070window() {2071return new Window(this.driver_)2072}2073}20742075/**2076* @param {!WebDriver} driver2077* @param {string} type2078* @param {number} ms2079* @return {!Promise<void>}2080*/2081function legacyTimeout(driver, type, ms) {2082return driver.execute(new command.Command(command.Name.SET_TIMEOUT).setParameter('type', type).setParameter('ms', ms))2083}20842085/**2086* A record object describing a browser cookie.2087*2088* @record2089*/2090Options.Cookie = function () {}20912092/**2093* The name of the cookie.2094*2095* @type {string}2096*/2097Options.Cookie.prototype.name20982099/**2100* The cookie value.2101*2102* @type {string}2103*/2104Options.Cookie.prototype.value21052106/**2107* The cookie path. Defaults to "/" when adding a cookie.2108*2109* @type {(string|undefined)}2110*/2111Options.Cookie.prototype.path21122113/**2114* The domain the cookie is visible to. Defaults to the current browsing2115* context's document's URL when adding a cookie.2116*2117* @type {(string|undefined)}2118*/2119Options.Cookie.prototype.domain21202121/**2122* Whether the cookie is a secure cookie. Defaults to false when adding a new2123* cookie.2124*2125* @type {(boolean|undefined)}2126*/2127Options.Cookie.prototype.secure21282129/**2130* Whether the cookie is an HTTP only cookie. Defaults to false when adding a2131* new cookie.2132*2133* @type {(boolean|undefined)}2134*/2135Options.Cookie.prototype.httpOnly21362137/**2138* When the cookie expires.2139*2140* When {@linkplain Options#addCookie() adding a cookie}, this may be specified2141* as a {@link Date} object, or in _seconds_ since Unix epoch (January 1, 1970).2142*2143* The expiry is always returned in seconds since epoch when2144* {@linkplain Options#getCookies() retrieving cookies} from the browser.2145*2146* @type {(!Date|number|undefined)}2147*/2148Options.Cookie.prototype.expiry21492150/**2151* When the cookie applies to a SameSite policy.2152*2153* When {@linkplain Options#addCookie() adding a cookie}, this may be specified2154* as a {@link string} object which is one of 'Lax', 'Strict' or 'None'.2155*2156*2157* @type {(string|undefined)}2158*/2159Options.Cookie.prototype.sameSite21602161/**2162* An interface for managing the current window.2163*2164* This class should never be instantiated directly. Instead, obtain an instance2165* with2166*2167* webdriver.manage().window()2168*2169* @see WebDriver#manage()2170* @see Options#window()2171*/2172class Window {2173/**2174* @param {!WebDriver} driver The parent driver.2175* @private2176*/2177constructor(driver) {2178/** @private {!WebDriver} */2179this.driver_ = driver2180/** @private {!Logger} */2181this.log_ = logging.getLogger(logging.Type.DRIVER)2182}21832184/**2185* Retrieves a rect describing the current top-level window's size and2186* position.2187*2188* @return {!Promise<{x: number, y: number, width: number, height: number}>}2189* A promise that will resolve to the window rect of the current window.2190*/2191getRect() {2192return this.driver_.execute(new command.Command(command.Name.GET_WINDOW_RECT))2193}21942195/**2196* Sets the current top-level window's size and position. You may update just2197* the size by omitting `x` & `y`, or just the position by omitting2198* `width` & `height` options.2199*2200* @param {{x: (number|undefined),2201* y: (number|undefined),2202* width: (number|undefined),2203* height: (number|undefined)}} options2204* The desired window size and position.2205* @return {!Promise<{x: number, y: number, width: number, height: number}>}2206* A promise that will resolve to the current window's updated window2207* rect.2208*/2209setRect({ x, y, width, height }) {2210return this.driver_.execute(2211new command.Command(command.Name.SET_WINDOW_RECT).setParameters({2212x,2213y,2214width,2215height,2216}),2217)2218}22192220/**2221* Maximizes the current window. The exact behavior of this command is2222* specific to individual window managers, but typically involves increasing2223* the window to the maximum available size without going full-screen.2224*2225* @return {!Promise<void>} A promise that will be resolved when the command2226* has completed.2227*/2228maximize() {2229return this.driver_.execute(2230new command.Command(command.Name.MAXIMIZE_WINDOW).setParameter('windowHandle', 'current'),2231)2232}22332234/**2235* Minimizes the current window. The exact behavior of this command is2236* specific to individual window managers, but typically involves hiding2237* the window in the system tray.2238*2239* @return {!Promise<void>} A promise that will be resolved when the command2240* has completed.2241*/2242minimize() {2243return this.driver_.execute(new command.Command(command.Name.MINIMIZE_WINDOW))2244}22452246/**2247* Invokes the "full screen" operation on the current window. The exact2248* behavior of this command is specific to individual window managers, but2249* this will typically increase the window size to the size of the physical2250* display and hide the browser chrome.2251*2252* @return {!Promise<void>} A promise that will be resolved when the command2253* has completed.2254* @see <https://fullscreen.spec.whatwg.org/#fullscreen-an-element>2255*/2256fullscreen() {2257return this.driver_.execute(new command.Command(command.Name.FULLSCREEN_WINDOW))2258}22592260/**2261* Gets the width and height of the current window2262* @param windowHandle2263* @returns {Promise<{width: *, height: *}>}2264*/2265async getSize(windowHandle = 'current') {2266if (windowHandle !== 'current') {2267this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)2268}22692270const rect = await this.getRect()2271return { height: rect.height, width: rect.width }2272}22732274/**2275* Sets the width and height of the current window. (window.resizeTo)2276* @param x2277* @param y2278* @param width2279* @param height2280* @param windowHandle2281* @returns {Promise<void>}2282*/2283async setSize({ x = 0, y = 0, width = 0, height = 0 }, windowHandle = 'current') {2284if (windowHandle !== 'current') {2285this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)2286}22872288await this.setRect({ x, y, width, height })2289}2290}22912292/**2293* Interface for managing WebDriver log records.2294*2295* This class should never be instantiated directly. Instead, obtain an2296* instance with2297*2298* webdriver.manage().logs()2299*2300* @see WebDriver#manage()2301* @see Options#logs()2302*/2303class Logs {2304/**2305* @param {!WebDriver} driver The parent driver.2306* @private2307*/2308constructor(driver) {2309/** @private {!WebDriver} */2310this.driver_ = driver2311}23122313/**2314* Fetches available log entries for the given type.2315*2316* Note that log buffers are reset after each call, meaning that available2317* log entries correspond to those entries not yet returned for a given log2318* type. In practice, this means that this call will return the available log2319* entries since the last call, or from the start of the session.2320*2321* @param {!logging.Type} type The desired log type.2322* @return {!Promise<!Array.<!logging.Entry>>} A2323* promise that will resolve to a list of log entries for the specified2324* type.2325*/2326get(type) {2327let cmd = new command.Command(command.Name.GET_LOG).setParameter('type', type)2328return this.driver_.execute(cmd).then(function (entries) {2329return entries.map(function (entry) {2330if (!(entry instanceof logging.Entry)) {2331return new logging.Entry(entry['level'], entry['message'], entry['timestamp'], entry['type'])2332}2333return entry2334})2335})2336}23372338/**2339* Retrieves the log types available to this driver.2340* @return {!Promise<!Array<!logging.Type>>} A2341* promise that will resolve to a list of available log types.2342*/2343getAvailableLogTypes() {2344return this.driver_.execute(new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES))2345}2346}23472348/**2349* An interface for changing the focus of the driver to another frame or window.2350*2351* This class should never be instantiated directly. Instead, obtain an2352* instance with2353*2354* webdriver.switchTo()2355*2356* @see WebDriver#switchTo()2357*/2358class TargetLocator {2359/**2360* @param {!WebDriver} driver The parent driver.2361* @private2362*/2363constructor(driver) {2364/** @private {!WebDriver} */2365this.driver_ = driver2366}23672368/**2369* Locates the DOM element on the current page that corresponds to2370* `document.activeElement` or `document.body` if the active element is not2371* available.2372*2373* @return {!WebElementPromise} The active element.2374*/2375activeElement() {2376const id = this.driver_.execute(new command.Command(command.Name.GET_ACTIVE_ELEMENT))2377return new WebElementPromise(this.driver_, id)2378}23792380/**2381* Switches focus of all future commands to the topmost frame in the current2382* window.2383*2384* @return {!Promise<void>} A promise that will be resolved2385* when the driver has changed focus to the default content.2386*/2387defaultContent() {2388return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', null))2389}23902391/**2392* Changes the focus of all future commands to another frame on the page. The2393* target frame may be specified as one of the following:2394*2395* - A number that specifies a (zero-based) index into [window.frames](2396* https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).2397* - A {@link WebElement} reference, which correspond to a `frame` or `iframe`2398* DOM element.2399* - The `null` value, to select the topmost frame on the page. Passing `null`2400* is the same as calling {@link #defaultContent defaultContent()}.2401*2402* If the specified frame can not be found, the returned promise will be2403* rejected with a {@linkplain error.NoSuchFrameError}.2404*2405* @param {(number|string|WebElement|null)} id The frame locator.2406* @return {!Promise<void>} A promise that will be resolved2407* when the driver has changed focus to the specified frame.2408*/2409frame(id) {2410let frameReference = id2411if (typeof id === 'string') {2412frameReference = this.driver_.findElement({ id }).catch((_) => this.driver_.findElement({ name: id }))2413}24142415return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', frameReference))2416}24172418/**2419* Changes the focus of all future commands to the parent frame of the2420* currently selected frame. This command has no effect if the driver is2421* already focused on the top-level browsing context.2422*2423* @return {!Promise<void>} A promise that will be resolved when the command2424* has completed.2425*/2426parentFrame() {2427return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME_PARENT))2428}24292430/**2431* Changes the focus of all future commands to another window. Windows may be2432* specified by their {@code window.name} attribute or by its handle2433* (as returned by {@link WebDriver#getWindowHandles}).2434*2435* If the specified window cannot be found, the returned promise will be2436* rejected with a {@linkplain error.NoSuchWindowError}.2437*2438* @param {string} nameOrHandle The name or window handle of the window to2439* switch focus to.2440* @return {!Promise<void>} A promise that will be resolved2441* when the driver has changed focus to the specified window.2442*/2443window(nameOrHandle) {2444return this.driver_.execute(2445new command.Command(command.Name.SWITCH_TO_WINDOW)2446// "name" supports the legacy drivers. "handle" is the W3C2447// compliant parameter.2448.setParameter('name', nameOrHandle)2449.setParameter('handle', nameOrHandle),2450)2451}24522453/**2454* Creates a new browser window and switches the focus for future2455* commands of this driver to the new window.2456*2457* @param {string} typeHint 'window' or 'tab'. The created window is not2458* guaranteed to be of the requested type; if the driver does not support2459* the requested type, a new browser window will be created of whatever type2460* the driver does support.2461* @return {!Promise<void>} A promise that will be resolved2462* when the driver has changed focus to the new window.2463*/2464newWindow(typeHint) {2465const driver = this.driver_2466return this.driver_2467.execute(new command.Command(command.Name.SWITCH_TO_NEW_WINDOW).setParameter('type', typeHint))2468.then(function (response) {2469return driver.switchTo().window(response.handle)2470})2471}24722473/**2474* Changes focus to the active modal dialog, such as those opened by2475* `window.alert()`, `window.confirm()`, and `window.prompt()`. The returned2476* promise will be rejected with a2477* {@linkplain error.NoSuchAlertError} if there are no open alerts.2478*2479* @return {!AlertPromise} The open alert.2480*/2481alert() {2482const text = this.driver_.execute(new command.Command(command.Name.GET_ALERT_TEXT))2483const driver = this.driver_2484return new AlertPromise(2485driver,2486text.then(function (text) {2487return new Alert(driver, text)2488}),2489)2490}2491}24922493//////////////////////////////////////////////////////////////////////////////2494//2495// WebElement2496//2497//////////////////////////////////////////////////////////////////////////////24982499const LEGACY_ELEMENT_ID_KEY = 'ELEMENT'2500const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf'2501const SHADOW_ROOT_ID_KEY = 'shadow-6066-11e4-a52e-4f735466cecf'25022503/**2504* Represents a DOM element. WebElements can be found by searching from the2505* document root using a {@link WebDriver} instance, or by searching2506* under another WebElement:2507*2508* driver.get('http://www.google.com');2509* var searchForm = driver.findElement(By.tagName('form'));2510* var searchBox = searchForm.findElement(By.name('q'));2511* searchBox.sendKeys('webdriver');2512*/2513class WebElement {2514/**2515* @param {!WebDriver} driver the parent WebDriver instance for this element.2516* @param {(!IThenable<string>|string)} id The server-assigned opaque ID for2517* the underlying DOM element.2518*/2519constructor(driver, id) {2520/** @private {!WebDriver} */2521this.driver_ = driver25222523/** @private {!Promise<string>} */2524this.id_ = Promise.resolve(id)25252526/** @private {!Logger} */2527this.log_ = logging.getLogger(logging.Type.DRIVER)2528}25292530/**2531* @param {string} id The raw ID.2532* @param {boolean=} noLegacy Whether to exclude the legacy element key.2533* @return {!Object} The element ID for use with WebDriver's wire protocol.2534*/2535static buildId(id, noLegacy = false) {2536return noLegacy ? { [ELEMENT_ID_KEY]: id } : { [ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id }2537}25382539/**2540* Extracts the encoded WebElement ID from the object.2541*2542* @param {?} obj The object to extract the ID from.2543* @return {string} the extracted ID.2544* @throws {TypeError} if the object is not a valid encoded ID.2545*/2546static extractId(obj) {2547return webElement.extractId(obj)2548}25492550/**2551* @param {?} obj the object to test.2552* @return {boolean} whether the object is a valid encoded WebElement ID.2553*/2554static isId(obj) {2555return webElement.isId(obj)2556}25572558/**2559* Compares two WebElements for equality.2560*2561* @param {!WebElement} a A WebElement.2562* @param {!WebElement} b A WebElement.2563* @return {!Promise<boolean>} A promise that will be2564* resolved to whether the two WebElements are equal.2565*/2566static async equals(a, b) {2567if (a === b) {2568return true2569}2570return a.driver_.executeScript('return arguments[0] === arguments[1]', a, b)2571}25722573/** @return {!WebDriver} The parent driver for this instance. */2574getDriver() {2575return this.driver_2576}25772578/**2579* @return {!Promise<string>} A promise that resolves to2580* the server-assigned opaque ID assigned to this element.2581*/2582getId() {2583return this.id_2584}25852586/**2587* @return {!Object} Returns the serialized representation of this WebElement.2588*/2589[Symbols.serialize]() {2590return this.getId().then(WebElement.buildId)2591}25922593/**2594* Schedules a command that targets this element with the parent WebDriver2595* instance. Will ensure this element's ID is included in the command2596* parameters under the "id" key.2597*2598* @param {!command.Command} command The command to schedule.2599* @return {!Promise<T>} A promise that will be resolved with the result.2600* @template T2601* @see WebDriver#schedule2602* @private2603*/2604execute_(command) {2605command.setParameter('id', this)2606return this.driver_.execute(command)2607}26082609/**2610* Schedule a command to find a descendant of this element. If the element2611* cannot be found, the returned promise will be rejected with a2612* {@linkplain error.NoSuchElementError NoSuchElementError}.2613*2614* The search criteria for an element may be defined using one of the static2615* factories on the {@link by.By} class, or as a short-hand2616* {@link ./by.ByHash} object. For example, the following two statements2617* are equivalent:2618*2619* var e1 = element.findElement(By.id('foo'));2620* var e2 = element.findElement({id:'foo'});2621*2622* You may also provide a custom locator function, which takes as input this2623* instance and returns a {@link WebElement}, or a promise that will resolve2624* to a WebElement. If the returned promise resolves to an array of2625* WebElements, WebDriver will use the first element. For example, to find the2626* first visible link on a page, you could write:2627*2628* var link = element.findElement(firstVisibleLink);2629*2630* function firstVisibleLink(element) {2631* var links = element.findElements(By.tagName('a'));2632* return promise.filter(links, function(link) {2633* return link.isDisplayed();2634* });2635* }2636*2637* @param {!(by.By|Function)} locator The locator strategy to use when2638* searching for the element.2639* @return {!WebElementPromise} A WebElement that can be used to issue2640* commands against the located element. If the element is not found, the2641* element will be invalidated and all scheduled commands aborted.2642*/2643findElement(locator) {2644locator = by.checkedLocator(locator)2645let id2646if (typeof locator === 'function') {2647id = this.driver_.findElementInternal_(locator, this)2648} else {2649let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENT)2650.setParameter('using', locator.using)2651.setParameter('value', locator.value)2652id = this.execute_(cmd)2653}2654return new WebElementPromise(this.driver_, id)2655}26562657/**2658* Locates all the descendants of this element that match the given search2659* criteria.2660*2661* @param {!(by.By|Function)} locator The locator strategy to use when2662* searching for the element.2663* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an2664* array of WebElements.2665*/2666async findElements(locator) {2667locator = by.checkedLocator(locator)2668if (typeof locator === 'function') {2669return this.driver_.findElementsInternal_(locator, this)2670} else {2671let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENTS)2672.setParameter('using', locator.using)2673.setParameter('value', locator.value)2674let result = await this.execute_(cmd)2675return Array.isArray(result) ? result : []2676}2677}26782679/**2680* Clicks on this element.2681*2682* @return {!Promise<void>} A promise that will be resolved when the click2683* command has completed.2684*/2685click() {2686return this.execute_(new command.Command(command.Name.CLICK_ELEMENT))2687}26882689/**2690* Types a key sequence on the DOM element represented by this instance.2691*2692* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is2693* processed in the key sequence, that key state is toggled until one of the2694* following occurs:2695*2696* - The modifier key is encountered again in the sequence. At this point the2697* state of the key is toggled (along with the appropriate keyup/down2698* events).2699* - The {@link input.Key.NULL} key is encountered in the sequence. When2700* this key is encountered, all modifier keys current in the down state are2701* released (with accompanying keyup events). The NULL key can be used to2702* simulate common keyboard shortcuts:2703*2704* element.sendKeys("text was",2705* Key.CONTROL, "a", Key.NULL,2706* "now text is");2707* // Alternatively:2708* element.sendKeys("text was",2709* Key.chord(Key.CONTROL, "a"),2710* "now text is");2711*2712* - The end of the key sequence is encountered. When there are no more keys2713* to type, all depressed modifier keys are released (with accompanying2714* keyup events).2715*2716* If this element is a file input ({@code <input type="file">}), the2717* specified key sequence should specify the path to the file to attach to2718* the element. This is analogous to the user clicking "Browse..." and entering2719* the path into the file select dialog.2720*2721* var form = driver.findElement(By.css('form'));2722* var element = form.findElement(By.css('input[type=file]'));2723* element.sendKeys('/path/to/file.txt');2724* form.submit();2725*2726* For uploads to function correctly, the entered path must reference a file2727* on the _browser's_ machine, not the local machine running this script. When2728* running against a remote Selenium server, a {@link input.FileDetector}2729* may be used to transparently copy files to the remote machine before2730* attempting to upload them in the browser.2731*2732* __Note:__ On browsers where native keyboard events are not supported2733* (e.g. Firefox on OS X), key events will be synthesized. Special2734* punctuation keys will be synthesized according to a standard QWERTY en-us2735* keyboard layout.2736*2737* @param {...(number|string|!IThenable<(number|string)>)} args The2738* sequence of keys to type. Number keys may be referenced numerically or2739* by string (1 or '1'). All arguments will be joined into a single2740* sequence.2741* @return {!Promise<void>} A promise that will be resolved when all keys2742* have been typed.2743*/2744async sendKeys(...args) {2745let keys = []2746;(await Promise.all(args)).forEach((key) => {2747let type = typeof key2748if (type === 'number') {2749key = String(key)2750} else if (type !== 'string') {2751throw TypeError('each key must be a number or string; got ' + type)2752}27532754// The W3C protocol requires keys to be specified as an array where2755// each element is a single key.2756keys.push(...key)2757})27582759if (!this.driver_.fileDetector_) {2760return this.execute_(2761new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)2762.setParameter('text', keys.join(''))2763.setParameter('value', keys),2764)2765}27662767try {2768keys = await this.driver_.fileDetector_.handleFile(this.driver_, keys.join(''))2769} catch (ex) {2770this.log_.severe('Error trying parse string as a file with file detector; sending keys instead' + ex)2771keys = keys.join('')2772}27732774return this.execute_(2775new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)2776.setParameter('text', keys)2777.setParameter('value', keys.split('')),2778)2779}27802781/**2782* Retrieves the element's tag name.2783*2784* @return {!Promise<string>} A promise that will be resolved with the2785* element's tag name.2786*/2787getTagName() {2788return this.execute_(new command.Command(command.Name.GET_ELEMENT_TAG_NAME))2789}27902791/**2792* Retrieves the value of a computed style property for this instance. If2793* the element inherits the named style from its parent, the parent will be2794* queried for its value. Where possible, color values will be converted to2795* their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)).2796*2797* _Warning:_ the value returned will be as the browser interprets it, so2798* it may be tricky to form a proper assertion.2799*2800* @param {string} cssStyleProperty The name of the CSS style property to look2801* up.2802* @return {!Promise<string>} A promise that will be resolved with the2803* requested CSS value.2804*/2805getCssValue(cssStyleProperty) {2806const name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY2807return this.execute_(new command.Command(name).setParameter('propertyName', cssStyleProperty))2808}28092810/**2811* Retrieves the current value of the given attribute of this element.2812* Will return the current value, even if it has been modified after the page2813* has been loaded. More exactly, this method will return the value2814* of the given attribute, unless that attribute is not present, in which case2815* the value of the property with the same name is returned. If neither value2816* is set, null is returned (for example, the "value" property of a textarea2817* element). The "style" attribute is converted as best can be to a2818* text representation with a trailing semicolon. The following are deemed to2819* be "boolean" attributes and will return either "true" or null:2820*2821* async, autofocus, autoplay, checked, compact, complete, controls, declare,2822* defaultchecked, defaultselected, defer, disabled, draggable, ended,2823* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,2824* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,2825* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,2826* selected, spellcheck, truespeed, willvalidate2827*2828* Finally, the following commonly mis-capitalized attribute/property names2829* are evaluated as expected:2830*2831* - "class"2832* - "readonly"2833*2834* @param {string} attributeName The name of the attribute to query.2835* @return {!Promise<?string>} A promise that will be2836* resolved with the attribute's value. The returned value will always be2837* either a string or null.2838*/2839getAttribute(attributeName) {2840return this.execute_(new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).setParameter('name', attributeName))2841}28422843/**2844* Get the value of the given attribute of the element.2845* <p>2846* This method, unlike {@link #getAttribute(String)}, returns the value of the attribute with the2847* given name but not the property with the same name.2848* <p>2849* The following are deemed to be "boolean" attributes, and will return either "true" or null:2850* <p>2851* async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked,2852* defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate,2853* iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade,2854* novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless,2855* seeking, selected, truespeed, willvalidate2856* <p>2857* See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver specification</a>2858* for more details.2859*2860* @param attributeName The name of the attribute.2861* @return The attribute's value or null if the value is not set.2862*/28632864getDomAttribute(attributeName) {2865return this.execute_(new command.Command(command.Name.GET_DOM_ATTRIBUTE).setParameter('name', attributeName))2866}28672868/**2869* Get the given property of the referenced web element2870* @param {string} propertyName The name of the attribute to query.2871* @return {!Promise<string>} A promise that will be2872* resolved with the element's property value2873*/2874getProperty(propertyName) {2875return this.execute_(new command.Command(command.Name.GET_ELEMENT_PROPERTY).setParameter('name', propertyName))2876}28772878/**2879* Get the shadow root of the current web element.2880* @returns {!Promise<ShadowRoot>} A promise that will be2881* resolved with the elements shadow root or rejected2882* with {@link NoSuchShadowRootError}2883*/2884getShadowRoot() {2885return this.execute_(new command.Command(command.Name.GET_SHADOW_ROOT))2886}28872888/**2889* Get the visible (i.e. not hidden by CSS) innerText of this element,2890* including sub-elements, without any leading or trailing whitespace.2891*2892* @return {!Promise<string>} A promise that will be2893* resolved with the element's visible text.2894*/2895getText() {2896return this.execute_(new command.Command(command.Name.GET_ELEMENT_TEXT))2897}28982899/**2900* Get the computed WAI-ARIA role of element.2901*2902* @return {!Promise<string>} A promise that will be2903* resolved with the element's computed role.2904*/2905getAriaRole() {2906return this.execute_(new command.Command(command.Name.GET_COMPUTED_ROLE))2907}29082909/**2910* Get the computed WAI-ARIA label of element.2911*2912* @return {!Promise<string>} A promise that will be2913* resolved with the element's computed label.2914*/2915getAccessibleName() {2916return this.execute_(new command.Command(command.Name.GET_COMPUTED_LABEL))2917}29182919/**2920* Returns an object describing an element's location, in pixels relative to2921* the document element, and the element's size in pixels.2922*2923* @return {!Promise<{width: number, height: number, x: number, y: number}>}2924* A promise that will resolve with the element's rect.2925*/2926getRect() {2927return this.execute_(new command.Command(command.Name.GET_ELEMENT_RECT))2928}29292930/**2931* Tests whether this element is enabled, as dictated by the `disabled`2932* attribute.2933*2934* @return {!Promise<boolean>} A promise that will be2935* resolved with whether this element is currently enabled.2936*/2937isEnabled() {2938return this.execute_(new command.Command(command.Name.IS_ELEMENT_ENABLED))2939}29402941/**2942* Tests whether this element is selected.2943*2944* @return {!Promise<boolean>} A promise that will be2945* resolved with whether this element is currently selected.2946*/2947isSelected() {2948return this.execute_(new command.Command(command.Name.IS_ELEMENT_SELECTED))2949}29502951/**2952* Submits the form containing this element (or this element if it is itself2953* a FORM element). his command is a no-op if the element is not contained in2954* a form.2955*2956* @return {!Promise<void>} A promise that will be resolved2957* when the form has been submitted.2958*/2959submit() {2960const script =2961'/* submitForm */var form = arguments[0];\n' +2962'while (form.nodeName != "FORM" && form.parentNode) {\n' +2963' form = form.parentNode;\n' +2964'}\n' +2965"if (!form) { throw Error('Unable to find containing form element'); }\n" +2966"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n" +2967"var e = form.ownerDocument.createEvent('Event');\n" +2968"e.initEvent('submit', true, true);\n" +2969'if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n'29702971return this.driver_.executeScript(script, this)2972}29732974/**2975* Clear the `value` of this element. This command has no effect if the2976* underlying DOM element is neither a text INPUT element nor a TEXTAREA2977* element.2978*2979* @return {!Promise<void>} A promise that will be resolved2980* when the element has been cleared.2981*/2982clear() {2983return this.execute_(new command.Command(command.Name.CLEAR_ELEMENT))2984}29852986/**2987* Test whether this element is currently displayed.2988*2989* @return {!Promise<boolean>} A promise that will be2990* resolved with whether this element is currently visible on the page.2991*/2992isDisplayed() {2993return this.execute_(new command.Command(command.Name.IS_ELEMENT_DISPLAYED))2994}29952996/**2997* Take a screenshot of the visible region encompassed by this element's2998* bounding rectangle.2999*3000* @return {!Promise<string>} A promise that will be3001* resolved to the screenshot as a base-64 encoded PNG.3002*/3003takeScreenshot() {3004return this.execute_(new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT))3005}3006}30073008/**3009* WebElementPromise is a promise that will be fulfilled with a WebElement.3010* This serves as a forward proxy on WebElement, allowing calls to be3011* scheduled without directly on this instance before the underlying3012* WebElement has been fulfilled. In other words, the following two statements3013* are equivalent:3014*3015* driver.findElement({id: 'my-button'}).click();3016* driver.findElement({id: 'my-button'}).then(function(el) {3017* return el.click();3018* });3019*3020* @implements {IThenable<!WebElement>}3021* @final3022*/3023class WebElementPromise extends WebElement {3024/**3025* @param {!WebDriver} driver The parent WebDriver instance for this3026* element.3027* @param {!Promise<!WebElement>} el A promise3028* that will resolve to the promised element.3029*/3030constructor(driver, el) {3031super(driver, 'unused')30323033/** @override */3034this.then = el.then.bind(el)30353036/** @override */3037this.catch = el.catch.bind(el)30383039/**3040* Defers returning the element ID until the wrapped WebElement has been3041* resolved.3042* @override3043*/3044this.getId = function () {3045return el.then(function (el) {3046return el.getId()3047})3048}3049}3050}30513052//////////////////////////////////////////////////////////////////////////////3053//3054// ShadowRoot3055//3056//////////////////////////////////////////////////////////////////////////////30573058/**3059* Represents a ShadowRoot of a {@link WebElement}. Provides functions to3060* retrieve elements that live in the DOM below the ShadowRoot.3061*/3062class ShadowRoot {3063constructor(driver, id) {3064this.driver_ = driver3065this.id_ = id3066}30673068/**3069* Extracts the encoded ShadowRoot ID from the object.3070*3071* @param {?} obj The object to extract the ID from.3072* @return {string} the extracted ID.3073* @throws {TypeError} if the object is not a valid encoded ID.3074*/3075static extractId(obj) {3076if (obj && typeof obj === 'object') {3077if (typeof obj[SHADOW_ROOT_ID_KEY] === 'string') {3078return obj[SHADOW_ROOT_ID_KEY]3079}3080}3081throw new TypeError('object is not a ShadowRoot ID')3082}30833084/**3085* @param {?} obj the object to test.3086* @return {boolean} whether the object is a valid encoded WebElement ID.3087*/3088static isId(obj) {3089return obj && typeof obj === 'object' && typeof obj[SHADOW_ROOT_ID_KEY] === 'string'3090}30913092/**3093* @return {!Object} Returns the serialized representation of this ShadowRoot.3094*/3095[Symbols.serialize]() {3096return this.getId()3097}30983099/**3100* Schedules a command that targets this element with the parent WebDriver3101* instance. Will ensure this element's ID is included in the command3102* parameters under the "id" key.3103*3104* @param {!command.Command} command The command to schedule.3105* @return {!Promise<T>} A promise that will be resolved with the result.3106* @template T3107* @see WebDriver#schedule3108* @private3109*/3110execute_(command) {3111command.setParameter('id', this)3112return this.driver_.execute(command)3113}31143115/**3116* Schedule a command to find a descendant of this ShadowROot. If the element3117* cannot be found, the returned promise will be rejected with a3118* {@linkplain error.NoSuchElementError NoSuchElementError}.3119*3120* The search criteria for an element may be defined using one of the static3121* factories on the {@link by.By} class, or as a short-hand3122* {@link ./by.ByHash} object. For example, the following two statements3123* are equivalent:3124*3125* var e1 = shadowroot.findElement(By.id('foo'));3126* var e2 = shadowroot.findElement({id:'foo'});3127*3128* You may also provide a custom locator function, which takes as input this3129* instance and returns a {@link WebElement}, or a promise that will resolve3130* to a WebElement. If the returned promise resolves to an array of3131* WebElements, WebDriver will use the first element. For example, to find the3132* first visible link on a page, you could write:3133*3134* var link = element.findElement(firstVisibleLink);3135*3136* function firstVisibleLink(shadowRoot) {3137* var links = shadowRoot.findElements(By.tagName('a'));3138* return promise.filter(links, function(link) {3139* return link.isDisplayed();3140* });3141* }3142*3143* @param {!(by.By|Function)} locator The locator strategy to use when3144* searching for the element.3145* @return {!WebElementPromise} A WebElement that can be used to issue3146* commands against the located element. If the element is not found, the3147* element will be invalidated and all scheduled commands aborted.3148*/3149findElement(locator) {3150locator = by.checkedLocator(locator)3151let id3152if (typeof locator === 'function') {3153id = this.driver_.findElementInternal_(locator, this)3154} else {3155let cmd = new command.Command(command.Name.FIND_ELEMENT_FROM_SHADOWROOT)3156.setParameter('using', locator.using)3157.setParameter('value', locator.value)3158id = this.execute_(cmd)3159}3160return new ShadowRootPromise(this.driver_, id)3161}31623163/**3164* Locates all the descendants of this element that match the given search3165* criteria.3166*3167* @param {!(by.By|Function)} locator The locator strategy to use when3168* searching for the element.3169* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an3170* array of WebElements.3171*/3172async findElements(locator) {3173locator = by.checkedLocator(locator)3174if (typeof locator === 'function') {3175return this.driver_.findElementsInternal_(locator, this)3176} else {3177let cmd = new command.Command(command.Name.FIND_ELEMENTS_FROM_SHADOWROOT)3178.setParameter('using', locator.using)3179.setParameter('value', locator.value)3180let result = await this.execute_(cmd)3181return Array.isArray(result) ? result : []3182}3183}31843185getId() {3186return this.id_3187}3188}31893190/**3191* ShadowRootPromise is a promise that will be fulfilled with a WebElement.3192* This serves as a forward proxy on ShadowRoot, allowing calls to be3193* scheduled without directly on this instance before the underlying3194* ShadowRoot has been fulfilled.3195*3196* @implements { IThenable<!ShadowRoot>}3197* @final3198*/3199class ShadowRootPromise extends ShadowRoot {3200/**3201* @param {!WebDriver} driver The parent WebDriver instance for this3202* element.3203* @param {!Promise<!ShadowRoot>} shadow A promise3204* that will resolve to the promised element.3205*/3206constructor(driver, shadow) {3207super(driver, 'unused')32083209/** @override */3210this.then = shadow.then.bind(shadow)32113212/** @override */3213this.catch = shadow.catch.bind(shadow)32143215/**3216* Defers returning the ShadowRoot ID until the wrapped WebElement has been3217* resolved.3218* @override3219*/3220this.getId = function () {3221return shadow.then(function (shadow) {3222return shadow.getId()3223})3224}3225}3226}32273228//////////////////////////////////////////////////////////////////////////////3229//3230// Alert3231//3232//////////////////////////////////////////////////////////////////////////////32333234/**3235* Represents a modal dialog such as {@code alert}, {@code confirm}, or3236* {@code prompt}. Provides functions to retrieve the message displayed with3237* the alert, accept or dismiss the alert, and set the response text (in the3238* case of {@code prompt}).3239*/3240class Alert {3241/**3242* @param {!WebDriver} driver The driver controlling the browser this alert3243* is attached to.3244* @param {string} text The message text displayed with this alert.3245*/3246constructor(driver, text) {3247/** @private {!WebDriver} */3248this.driver_ = driver32493250/** @private {!Promise<string>} */3251this.text_ = Promise.resolve(text)3252}32533254/**3255* Retrieves the message text displayed with this alert. For instance, if the3256* alert were opened with alert("hello"), then this would return "hello".3257*3258* @return {!Promise<string>} A promise that will be3259* resolved to the text displayed with this alert.3260*/3261getText() {3262return this.text_3263}32643265/**3266* Accepts this alert.3267*3268* @return {!Promise<void>} A promise that will be resolved3269* when this command has completed.3270*/3271accept() {3272return this.driver_.execute(new command.Command(command.Name.ACCEPT_ALERT))3273}32743275/**3276* Dismisses this alert.3277*3278* @return {!Promise<void>} A promise that will be resolved3279* when this command has completed.3280*/3281dismiss() {3282return this.driver_.execute(new command.Command(command.Name.DISMISS_ALERT))3283}32843285/**3286* Sets the response text on this alert. This command will return an error if3287* the underlying alert does not support response text (e.g. window.alert and3288* window.confirm).3289*3290* @param {string} text The text to set.3291* @return {!Promise<void>} A promise that will be resolved3292* when this command has completed.3293*/3294sendKeys(text) {3295return this.driver_.execute(new command.Command(command.Name.SET_ALERT_TEXT).setParameter('text', text))3296}3297}32983299/**3300* AlertPromise is a promise that will be fulfilled with an Alert. This promise3301* serves as a forward proxy on an Alert, allowing calls to be scheduled3302* directly on this instance before the underlying Alert has been fulfilled. In3303* other words, the following two statements are equivalent:3304*3305* driver.switchTo().alert().dismiss();3306* driver.switchTo().alert().then(function(alert) {3307* return alert.dismiss();3308* });3309*3310* @implements {IThenable<!Alert>}3311* @final3312*/3313class AlertPromise extends Alert {3314/**3315* @param {!WebDriver} driver The driver controlling the browser this3316* alert is attached to.3317* @param {!Promise<!Alert>} alert A thenable3318* that will be fulfilled with the promised alert.3319*/3320constructor(driver, alert) {3321super(driver, 'unused')33223323/** @override */3324this.then = alert.then.bind(alert)33253326/** @override */3327this.catch = alert.catch.bind(alert)33283329/**3330* Defer returning text until the promised alert has been resolved.3331* @override3332*/3333this.getText = function () {3334return alert.then(function (alert) {3335return alert.getText()3336})3337}33383339/**3340* Defers action until the alert has been located.3341* @override3342*/3343this.accept = function () {3344return alert.then(function (alert) {3345return alert.accept()3346})3347}33483349/**3350* Defers action until the alert has been located.3351* @override3352*/3353this.dismiss = function () {3354return alert.then(function (alert) {3355return alert.dismiss()3356})3357}33583359/**3360* Defers action until the alert has been located.3361* @override3362*/3363this.sendKeys = function (text) {3364return alert.then(function (alert) {3365return alert.sendKeys(text)3366})3367}3368}3369}33703371// PUBLIC API33723373module.exports = {3374Alert,3375AlertPromise,3376Condition,3377Logs,3378Navigation,3379Options,3380ShadowRoot,3381TargetLocator,3382IWebDriver,3383WebDriver,3384WebElement,3385WebElementCondition,3386WebElementPromise,3387Window,3388}338933903391