Path: blob/trunk/javascript/selenium-webdriver/lib/webdriver.js
4010 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.send('Fetch.enable', {1383handleAuthRequests: true,1384})1385await connection.send('Network.setCacheDisabled', {1386cacheDisabled: true,1387})1388}13891390/**1391* Handle Network interception requests1392* @param connection WebSocket connection to the browser1393* @param httpResponse Object representing what we are intercepting1394* as well as what should be returned.1395* @param callback callback called when we intercept requests.1396*/1397async onIntercept(connection, httpResponse, callback) {1398this._cdpWsConnection.on('message', (message) => {1399const params = JSON.parse(message)1400if (params.method === 'Fetch.requestPaused') {1401const requestPausedParams = params['params']1402if (requestPausedParams.request.url == httpResponse.urlToIntercept) {1403connection.execute('Fetch.fulfillRequest', {1404requestId: requestPausedParams['requestId'],1405responseCode: httpResponse.status,1406responseHeaders: httpResponse.headers,1407body: httpResponse.body,1408})1409callback()1410} else {1411connection.execute('Fetch.continueRequest', {1412requestId: requestPausedParams['requestId'],1413})1414}1415}1416})14171418await connection.execute('Fetch.enable', {}, null)1419await connection.execute(1420'Network.setCacheDisabled',1421{1422cacheDisabled: true,1423},1424null,1425)1426}14271428/**1429*1430* @param connection1431* @param callback1432* @returns {Promise<void>}1433*/1434async onLogEvent(connection, callback) {1435this._cdpWsConnection.on('message', (message) => {1436const params = JSON.parse(message)1437if (params.method === 'Runtime.consoleAPICalled') {1438const consoleEventParams = params['params']1439let event = {1440type: consoleEventParams['type'],1441timestamp: new Date(consoleEventParams['timestamp']),1442args: consoleEventParams['args'],1443}14441445callback(event)1446}14471448if (params.method === 'Log.entryAdded') {1449const logEventParams = params['params']1450const logEntry = logEventParams['entry']1451let event = {1452level: logEntry['level'],1453timestamp: new Date(logEntry['timestamp']),1454message: logEntry['text'],1455}14561457callback(event)1458}1459})1460await connection.execute('Runtime.enable', {}, null)1461}14621463/**1464*1465* @param connection1466* @param callback1467* @returns {Promise<void>}1468*/1469async onLogException(connection, callback) {1470await connection.execute('Runtime.enable', {}, null)14711472this._cdpWsConnection.on('message', (message) => {1473const params = JSON.parse(message)14741475if (params.method === 'Runtime.exceptionThrown') {1476const exceptionEventParams = params['params']1477let event = {1478exceptionDetails: exceptionEventParams['exceptionDetails'],1479timestamp: new Date(exceptionEventParams['timestamp']),1480}14811482callback(event)1483}1484})1485}14861487/**1488* @param connection1489* @param callback1490* @returns {Promise<void>}1491*/1492async logMutationEvents(connection, callback) {1493await connection.execute('Runtime.enable', {}, null)1494await connection.execute('Page.enable', {}, null)14951496await connection.execute(1497'Runtime.addBinding',1498{1499name: '__webdriver_attribute',1500},1501null,1502)15031504let mutationListener = ''1505try {1506// Depending on what is running the code it could appear in 2 different places which is why we try1507// here and then the other location1508mutationListener = fs1509.readFileSync('./javascript/selenium-webdriver/lib/atoms/mutation-listener.js', 'utf-8')1510.toString()1511} catch {1512mutationListener = fs.readFileSync(path.resolve(__dirname, './atoms/mutation-listener.js'), 'utf-8').toString()1513}15141515this.executeScript(mutationListener)15161517await connection.execute(1518'Page.addScriptToEvaluateOnNewDocument',1519{1520source: mutationListener,1521},1522null,1523)15241525this._cdpWsConnection.on('message', async (message) => {1526const params = JSON.parse(message)1527if (params.method === 'Runtime.bindingCalled') {1528let payload = JSON.parse(params['params']['payload'])1529let elements = await this.findElements({1530css: '*[data-__webdriver_id=' + by.escapeCss(payload['target']) + ']',1531})15321533if (elements.length === 0) {1534return1535}15361537let event = {1538element: elements[0],1539attribute_name: payload['name'],1540current_value: payload['value'],1541old_value: payload['oldValue'],1542}1543callback(event)1544}1545})1546}15471548async pinScript(script) {1549let pinnedScript = new PinnedScript(script)1550let connection1551if (Object.is(this._cdpConnection, undefined)) {1552connection = await this.createCDPConnection('page')1553} else {1554connection = this._cdpConnection1555}15561557await connection.send('Page.enable', {})15581559await connection.send('Runtime.evaluate', {1560expression: pinnedScript.creationScript(),1561})15621563let result = await connection.send('Page.addScriptToEvaluateOnNewDocument', {1564source: pinnedScript.creationScript(),1565})15661567pinnedScript.scriptId = result['result']['identifier']15681569this.pinnedScripts_[pinnedScript.handle] = pinnedScript15701571return pinnedScript1572}15731574async unpinScript(script) {1575if (script && !(script instanceof PinnedScript)) {1576throw Error(`Pass valid PinnedScript object. Received: ${script}`)1577}15781579if (script.handle in this.pinnedScripts_) {1580let connection1581if (Object.is(this._cdpConnection, undefined)) {1582connection = this.createCDPConnection('page')1583} else {1584connection = this._cdpConnection1585}15861587await connection.send('Page.enable', {})15881589await connection.send('Runtime.evaluate', {1590expression: script.removalScript(),1591})15921593await connection.send('Page.removeScriptToEvaluateOnLoad', {1594identifier: script.scriptId,1595})15961597delete this.pinnedScripts_[script.handle]1598}1599}16001601/**1602*1603* @returns The value of authenticator ID added1604*/1605virtualAuthenticatorId() {1606return this.authenticatorId_1607}16081609/**1610* Adds a virtual authenticator with the given options.1611* @param options VirtualAuthenticatorOptions object to set authenticator options.1612*/1613async addVirtualAuthenticator(options) {1614this.authenticatorId_ = await this.execute(1615new command.Command(command.Name.ADD_VIRTUAL_AUTHENTICATOR).setParameters(options.toDict()),1616)1617}16181619/**1620* Removes a previously added virtual authenticator. The authenticator is no1621* longer valid after removal, so no methods may be called.1622*/1623async removeVirtualAuthenticator() {1624await this.execute(1625new command.Command(command.Name.REMOVE_VIRTUAL_AUTHENTICATOR).setParameter(1626'authenticatorId',1627this.authenticatorId_,1628),1629)1630this.authenticatorId_ = null1631}16321633/**1634* Injects a credential into the authenticator.1635* @param credential Credential to be added1636*/1637async addCredential(credential) {1638credential = credential.toDict()1639credential['authenticatorId'] = this.authenticatorId_1640await this.execute(new command.Command(command.Name.ADD_CREDENTIAL).setParameters(credential))1641}16421643/**1644*1645* @returns The list of credentials owned by the authenticator.1646*/1647async getCredentials() {1648let credential_data = await this.execute(1649new command.Command(command.Name.GET_CREDENTIALS).setParameter('authenticatorId', this.virtualAuthenticatorId()),1650)1651var credential_list = []1652for (var i = 0; i < credential_data.length; i++) {1653credential_list.push(new Credential().fromDict(credential_data[i]))1654}1655return credential_list1656}16571658/**1659* Removes a credential from the authenticator.1660* @param credential_id The ID of the credential to be removed.1661*/1662async removeCredential(credential_id) {1663// If credential_id is not a base64url, then convert it to base64url.1664if (Array.isArray(credential_id)) {1665credential_id = Buffer.from(credential_id).toString('base64url')1666}16671668await this.execute(1669new command.Command(command.Name.REMOVE_CREDENTIAL)1670.setParameter('credentialId', credential_id)1671.setParameter('authenticatorId', this.authenticatorId_),1672)1673}16741675/**1676* Removes all the credentials from the authenticator.1677*/1678async removeAllCredentials() {1679await this.execute(1680new command.Command(command.Name.REMOVE_ALL_CREDENTIALS).setParameter('authenticatorId', this.authenticatorId_),1681)1682}16831684/**1685* Sets whether the authenticator will simulate success or fail on user verification.1686* @param verified true if the authenticator will pass user verification, false otherwise.1687*/1688async setUserVerified(verified) {1689await this.execute(1690new command.Command(command.Name.SET_USER_VERIFIED)1691.setParameter('authenticatorId', this.authenticatorId_)1692.setParameter('isUserVerified', verified),1693)1694}16951696async getDownloadableFiles() {1697const caps = await this.getCapabilities()1698if (!caps['map_'].get('se:downloadsEnabled')) {1699throw new error.WebDriverError('Downloads must be enabled in options')1700}17011702return (await this.execute(new command.Command(command.Name.GET_DOWNLOADABLE_FILES))).names1703}17041705async downloadFile(fileName, targetDirectory) {1706const caps = await this.getCapabilities()1707if (!caps['map_'].get('se:downloadsEnabled')) {1708throw new Error('Downloads must be enabled in options')1709}17101711const response = await this.execute(new command.Command(command.Name.DOWNLOAD_FILE).setParameter('name', fileName))17121713const base64Content = response.contents17141715if (!targetDirectory.endsWith('/')) {1716targetDirectory += '/'1717}17181719fs.mkdirSync(targetDirectory, { recursive: true })1720const zipFilePath = path.join(targetDirectory, `${fileName}.zip`)1721fs.writeFileSync(zipFilePath, Buffer.from(base64Content, 'base64'))17221723const zipData = fs.readFileSync(zipFilePath)1724await JSZip.loadAsync(zipData)1725.then((zip) => {1726// Iterate through each file in the zip archive1727Object.keys(zip.files).forEach(async (fileName) => {1728const fileData = await zip.files[fileName].async('nodebuffer')1729fs.writeFileSync(`${targetDirectory}/${fileName}`, fileData)1730console.log(`File extracted: ${fileName}`)1731})1732})1733.catch((error) => {1734console.error('Error unzipping file:', error)1735})1736}17371738async deleteDownloadableFiles() {1739const caps = await this.getCapabilities()1740if (!caps['map_'].get('se:downloadsEnabled')) {1741throw new error.WebDriverError('Downloads must be enabled in options')1742}17431744return await this.execute(new command.Command(command.Name.DELETE_DOWNLOADABLE_FILES))1745}17461747/**1748* Fires a custom session event to the remote server event bus.1749*1750* This allows test code to trigger server-side utilities that subscribe to the event bus.1751*1752* @param {string} eventType The type of event (e.g., "test:failed", "log:collect").1753* @param {Object=} payload Optional data to include with the event.1754* @return {!Promise<Object>} A promise that resolves to the response containing1755* success status, event type, and timestamp.1756*1757* @example1758* // Fire a simple event1759* await driver.fireSessionEvent('test:started');1760*1761* @example1762* // Fire an event with payload1763* await driver.fireSessionEvent('test:failed', {1764* testName: 'LoginTest',1765* error: 'Element not found'1766* });1767*/1768async fireSessionEvent(eventType, payload = null) {1769if (!eventType || typeof eventType !== 'string') {1770throw new error.InvalidArgumentError('eventType must be a non-empty string')1771}1772const cmd = new command.Command(command.Name.FIRE_SESSION_EVENT).setParameter('eventType', eventType)1773if (payload) {1774cmd.setParameter('payload', payload)1775}1776return await this.execute(cmd)1777}1778}17791780/**1781* Interface for navigating back and forth in the browser history.1782*1783* This class should never be instantiated directly. Instead, obtain an instance1784* with1785*1786* webdriver.navigate()1787*1788* @see WebDriver#navigate()1789*/1790class Navigation {1791/**1792* @param {!WebDriver} driver The parent driver.1793* @private1794*/1795constructor(driver) {1796/** @private {!WebDriver} */1797this.driver_ = driver1798}17991800/**1801* Navigates to a new URL.1802*1803* @param {string} url The URL to navigate to.1804* @return {!Promise<void>} A promise that will be resolved when the URL1805* has been loaded.1806*/1807to(url) {1808return this.driver_.execute(new command.Command(command.Name.GET).setParameter('url', url))1809}18101811/**1812* Moves backwards in the browser history.1813*1814* @return {!Promise<void>} A promise that will be resolved when the1815* navigation event has completed.1816*/1817back() {1818return this.driver_.execute(new command.Command(command.Name.GO_BACK))1819}18201821/**1822* Moves forwards in the browser history.1823*1824* @return {!Promise<void>} A promise that will be resolved when the1825* navigation event has completed.1826*/1827forward() {1828return this.driver_.execute(new command.Command(command.Name.GO_FORWARD))1829}18301831/**1832* Refreshes the current page.1833*1834* @return {!Promise<void>} A promise that will be resolved when the1835* navigation event has completed.1836*/1837refresh() {1838return this.driver_.execute(new command.Command(command.Name.REFRESH))1839}1840}18411842/**1843* Provides methods for managing browser and driver state.1844*1845* This class should never be instantiated directly. Instead, obtain an instance1846* with {@linkplain WebDriver#manage() webdriver.manage()}.1847*/1848class Options {1849/**1850* @param {!WebDriver} driver The parent driver.1851* @private1852*/1853constructor(driver) {1854/** @private {!WebDriver} */1855this.driver_ = driver1856}18571858/**1859* Adds a cookie.1860*1861* __Sample Usage:__1862*1863* // Set a basic cookie.1864* driver.manage().addCookie({name: 'foo', value: 'bar'});1865*1866* // Set a cookie that expires in 10 minutes.1867* let expiry = new Date(Date.now() + (10 * 60 * 1000));1868* driver.manage().addCookie({name: 'foo', value: 'bar', expiry});1869*1870* // The cookie expiration may also be specified in seconds since epoch.1871* driver.manage().addCookie({1872* name: 'foo',1873* value: 'bar',1874* expiry: Math.floor(Date.now() / 1000)1875* });1876*1877* @param {!Options.Cookie} spec Defines the cookie to add.1878* @return {!Promise<void>} A promise that will be resolved1879* when the cookie has been added to the page.1880* @throws {error.InvalidArgumentError} if any of the cookie parameters are1881* invalid.1882* @throws {TypeError} if `spec` is not a cookie object.1883*/1884addCookie({ name, value, path, domain, secure, httpOnly, expiry, sameSite }) {1885// We do not allow '=' or ';' in the name.1886if (/[;=]/.test(name)) {1887throw new error.InvalidArgumentError('Invalid cookie name "' + name + '"')1888}18891890// We do not allow ';' in value.1891if (/;/.test(value)) {1892throw new error.InvalidArgumentError('Invalid cookie value "' + value + '"')1893}18941895if (typeof expiry === 'number') {1896expiry = Math.floor(expiry)1897} else if (expiry instanceof Date) {1898let date = /** @type {!Date} */ (expiry)1899expiry = Math.floor(date.getTime() / 1000)1900}19011902if (sameSite && !['Strict', 'Lax', 'None'].includes(sameSite)) {1903throw new error.InvalidArgumentError(1904`Invalid sameSite cookie value '${sameSite}'. It should be one of "Lax", "Strict" or "None"`,1905)1906}19071908if (sameSite === 'None' && !secure) {1909throw new error.InvalidArgumentError('Invalid cookie configuration: SameSite=None must be Secure')1910}19111912return this.driver_.execute(1913new command.Command(command.Name.ADD_COOKIE).setParameter('cookie', {1914name: name,1915value: value,1916path: path,1917domain: domain,1918secure: !!secure,1919httpOnly: !!httpOnly,1920expiry: expiry,1921sameSite: sameSite,1922}),1923)1924}19251926/**1927* Deletes all cookies visible to the current page.1928*1929* @return {!Promise<void>} A promise that will be resolved1930* when all cookies have been deleted.1931*/1932deleteAllCookies() {1933return this.driver_.execute(new command.Command(command.Name.DELETE_ALL_COOKIES))1934}19351936/**1937* Deletes the cookie with the given name. This command is a no-op if there is1938* no cookie with the given name visible to the current page.1939*1940* @param {string} name The name of the cookie to delete.1941* @return {!Promise<void>} A promise that will be resolved1942* when the cookie has been deleted.1943*/1944deleteCookie(name) {1945// Validate the cookie name is non-empty and properly trimmed.1946if (!name?.trim()) {1947throw new error.InvalidArgumentError('Cookie name cannot be empty')1948}19491950return this.driver_.execute(new command.Command(command.Name.DELETE_COOKIE).setParameter('name', name))1951}19521953/**1954* Retrieves all cookies visible to the current page. Each cookie will be1955* returned as a JSON object as described by the WebDriver wire protocol.1956*1957* @return {!Promise<!Array<!Options.Cookie>>} A promise that will be1958* resolved with the cookies visible to the current browsing context.1959*/1960getCookies() {1961return this.driver_.execute(new command.Command(command.Name.GET_ALL_COOKIES))1962}19631964/**1965* Retrieves the cookie with the given name. Returns null if there is no such1966* cookie. The cookie will be returned as a JSON object as described by the1967* WebDriver wire protocol.1968*1969* @param {string} name The name of the cookie to retrieve.1970* @throws {InvalidArgumentError} - If the cookie name is empty or invalid.1971* @return {!Promise<?Options.Cookie>} A promise that will be resolved1972* with the named cookie1973* @throws {error.NoSuchCookieError} if there is no such cookie.1974*/1975async getCookie(name) {1976// Validate the cookie name is non-empty and properly trimmed.1977if (!name?.trim()) {1978throw new error.InvalidArgumentError('Cookie name cannot be empty')1979}19801981try {1982const cookie = await this.driver_.execute(new command.Command(command.Name.GET_COOKIE).setParameter('name', name))1983return cookie1984} catch (err) {1985if (!(err instanceof error.UnknownCommandError) && !(err instanceof error.UnsupportedOperationError)) {1986throw err1987}1988return null1989}1990}19911992/**1993* Fetches the timeouts currently configured for the current session.1994*1995* @return {!Promise<{script: number,1996* pageLoad: number,1997* implicit: number}>} A promise that will be1998* resolved with the timeouts currently configured for the current1999* session.2000* @see #setTimeouts()2001*/2002getTimeouts() {2003return this.driver_.execute(new command.Command(command.Name.GET_TIMEOUT))2004}20052006/**2007* Sets the timeout durations associated with the current session.2008*2009* The following timeouts are supported (all timeouts are specified in2010* milliseconds):2011*2012* - `implicit` specifies the maximum amount of time to wait for an element2013* locator to succeed when {@linkplain WebDriver#findElement locating}2014* {@linkplain WebDriver#findElements elements} on the page.2015* Defaults to 0 milliseconds.2016*2017* - `pageLoad` specifies the maximum amount of time to wait for a page to2018* finishing loading. Defaults to 300000 milliseconds.2019*2020* - `script` specifies the maximum amount of time to wait for an2021* {@linkplain WebDriver#executeScript evaluated script} to run. If set to2022* `null`, the script timeout will be indefinite.2023* Defaults to 30000 milliseconds.2024*2025* @param {{script: (number|null|undefined),2026* pageLoad: (number|null|undefined),2027* implicit: (number|null|undefined)}} conf2028* The desired timeout configuration.2029* @return {!Promise<void>} A promise that will be resolved when the timeouts2030* have been set.2031* @throws {!TypeError} if an invalid options object is provided.2032* @see #getTimeouts()2033* @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>2034*/2035setTimeouts({ script, pageLoad, implicit } = {}) {2036let cmd = new command.Command(command.Name.SET_TIMEOUT)20372038let valid = false20392040function setParam(key, value) {2041if (value === null || typeof value === 'number') {2042valid = true2043cmd.setParameter(key, value)2044} else if (typeof value !== 'undefined') {2045throw TypeError('invalid timeouts configuration:' + ` expected "${key}" to be a number, got ${typeof value}`)2046}2047}20482049setParam('implicit', implicit)2050setParam('pageLoad', pageLoad)2051setParam('script', script)20522053if (valid) {2054return this.driver_.execute(cmd).catch(() => {2055// Fallback to the legacy method.2056let cmds = []2057if (typeof script === 'number') {2058cmds.push(legacyTimeout(this.driver_, 'script', script))2059}2060if (typeof implicit === 'number') {2061cmds.push(legacyTimeout(this.driver_, 'implicit', implicit))2062}2063if (typeof pageLoad === 'number') {2064cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad))2065}2066return Promise.all(cmds)2067})2068}2069throw TypeError('no timeouts specified')2070}20712072/**2073* @return {!Logs} The interface for managing driver logs.2074*/2075logs() {2076return new Logs(this.driver_)2077}20782079/**2080* @return {!Window} The interface for managing the current window.2081*/2082window() {2083return new Window(this.driver_)2084}2085}20862087/**2088* @param {!WebDriver} driver2089* @param {string} type2090* @param {number} ms2091* @return {!Promise<void>}2092*/2093function legacyTimeout(driver, type, ms) {2094return driver.execute(new command.Command(command.Name.SET_TIMEOUT).setParameter('type', type).setParameter('ms', ms))2095}20962097/**2098* A record object describing a browser cookie.2099*2100* @record2101*/2102Options.Cookie = function () {}21032104/**2105* The name of the cookie.2106*2107* @type {string}2108*/2109Options.Cookie.prototype.name21102111/**2112* The cookie value.2113*2114* @type {string}2115*/2116Options.Cookie.prototype.value21172118/**2119* The cookie path. Defaults to "/" when adding a cookie.2120*2121* @type {(string|undefined)}2122*/2123Options.Cookie.prototype.path21242125/**2126* The domain the cookie is visible to. Defaults to the current browsing2127* context's document's URL when adding a cookie.2128*2129* @type {(string|undefined)}2130*/2131Options.Cookie.prototype.domain21322133/**2134* Whether the cookie is a secure cookie. Defaults to false when adding a new2135* cookie.2136*2137* @type {(boolean|undefined)}2138*/2139Options.Cookie.prototype.secure21402141/**2142* Whether the cookie is an HTTP only cookie. Defaults to false when adding a2143* new cookie.2144*2145* @type {(boolean|undefined)}2146*/2147Options.Cookie.prototype.httpOnly21482149/**2150* When the cookie expires.2151*2152* When {@linkplain Options#addCookie() adding a cookie}, this may be specified2153* as a {@link Date} object, or in _seconds_ since Unix epoch (January 1, 1970).2154*2155* The expiry is always returned in seconds since epoch when2156* {@linkplain Options#getCookies() retrieving cookies} from the browser.2157*2158* @type {(!Date|number|undefined)}2159*/2160Options.Cookie.prototype.expiry21612162/**2163* When the cookie applies to a SameSite policy.2164*2165* When {@linkplain Options#addCookie() adding a cookie}, this may be specified2166* as a {@link string} object which is one of 'Lax', 'Strict' or 'None'.2167*2168*2169* @type {(string|undefined)}2170*/2171Options.Cookie.prototype.sameSite21722173/**2174* An interface for managing the current window.2175*2176* This class should never be instantiated directly. Instead, obtain an instance2177* with2178*2179* webdriver.manage().window()2180*2181* @see WebDriver#manage()2182* @see Options#window()2183*/2184class Window {2185/**2186* @param {!WebDriver} driver The parent driver.2187* @private2188*/2189constructor(driver) {2190/** @private {!WebDriver} */2191this.driver_ = driver2192/** @private {!Logger} */2193this.log_ = logging.getLogger(logging.Type.DRIVER)2194}21952196/**2197* Retrieves a rect describing the current top-level window's size and2198* position.2199*2200* @return {!Promise<{x: number, y: number, width: number, height: number}>}2201* A promise that will resolve to the window rect of the current window.2202*/2203getRect() {2204return this.driver_.execute(new command.Command(command.Name.GET_WINDOW_RECT))2205}22062207/**2208* Sets the current top-level window's size and position. You may update just2209* the size by omitting `x` & `y`, or just the position by omitting2210* `width` & `height` options.2211*2212* @param {{x: (number|undefined),2213* y: (number|undefined),2214* width: (number|undefined),2215* height: (number|undefined)}} options2216* The desired window size and position.2217* @return {!Promise<{x: number, y: number, width: number, height: number}>}2218* A promise that will resolve to the current window's updated window2219* rect.2220*/2221setRect({ x, y, width, height }) {2222return this.driver_.execute(2223new command.Command(command.Name.SET_WINDOW_RECT).setParameters({2224x,2225y,2226width,2227height,2228}),2229)2230}22312232/**2233* Maximizes the current window. The exact behavior of this command is2234* specific to individual window managers, but typically involves increasing2235* the window to the maximum available size without going full-screen.2236*2237* @return {!Promise<void>} A promise that will be resolved when the command2238* has completed.2239*/2240maximize() {2241return this.driver_.execute(2242new command.Command(command.Name.MAXIMIZE_WINDOW).setParameter('windowHandle', 'current'),2243)2244}22452246/**2247* Minimizes the current window. The exact behavior of this command is2248* specific to individual window managers, but typically involves hiding2249* the window in the system tray.2250*2251* @return {!Promise<void>} A promise that will be resolved when the command2252* has completed.2253*/2254minimize() {2255return this.driver_.execute(new command.Command(command.Name.MINIMIZE_WINDOW))2256}22572258/**2259* Invokes the "full screen" operation on the current window. The exact2260* behavior of this command is specific to individual window managers, but2261* this will typically increase the window size to the size of the physical2262* display and hide the browser chrome.2263*2264* @return {!Promise<void>} A promise that will be resolved when the command2265* has completed.2266* @see <https://fullscreen.spec.whatwg.org/#fullscreen-an-element>2267*/2268fullscreen() {2269return this.driver_.execute(new command.Command(command.Name.FULLSCREEN_WINDOW))2270}22712272/**2273* Gets the width and height of the current window2274* @param windowHandle2275* @returns {Promise<{width: *, height: *}>}2276*/2277async getSize(windowHandle = 'current') {2278if (windowHandle !== 'current') {2279this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)2280}22812282const rect = await this.getRect()2283return { height: rect.height, width: rect.width }2284}22852286/**2287* Sets the width and height of the current window. (window.resizeTo)2288* @param x2289* @param y2290* @param width2291* @param height2292* @param windowHandle2293* @returns {Promise<void>}2294*/2295async setSize({ x = 0, y = 0, width = 0, height = 0 }, windowHandle = 'current') {2296if (windowHandle !== 'current') {2297this.log_.warning(`Only 'current' window is supported for W3C compatible browsers.`)2298}22992300await this.setRect({ x, y, width, height })2301}2302}23032304/**2305* Interface for managing WebDriver log records.2306*2307* This class should never be instantiated directly. Instead, obtain an2308* instance with2309*2310* webdriver.manage().logs()2311*2312* @see WebDriver#manage()2313* @see Options#logs()2314*/2315class Logs {2316/**2317* @param {!WebDriver} driver The parent driver.2318* @private2319*/2320constructor(driver) {2321/** @private {!WebDriver} */2322this.driver_ = driver2323}23242325/**2326* Fetches available log entries for the given type.2327*2328* Note that log buffers are reset after each call, meaning that available2329* log entries correspond to those entries not yet returned for a given log2330* type. In practice, this means that this call will return the available log2331* entries since the last call, or from the start of the session.2332*2333* @param {!logging.Type} type The desired log type.2334* @return {!Promise<!Array.<!logging.Entry>>} A2335* promise that will resolve to a list of log entries for the specified2336* type.2337*/2338get(type) {2339let cmd = new command.Command(command.Name.GET_LOG).setParameter('type', type)2340return this.driver_.execute(cmd).then(function (entries) {2341return entries.map(function (entry) {2342if (!(entry instanceof logging.Entry)) {2343return new logging.Entry(entry['level'], entry['message'], entry['timestamp'], entry['type'])2344}2345return entry2346})2347})2348}23492350/**2351* Retrieves the log types available to this driver.2352* @return {!Promise<!Array<!logging.Type>>} A2353* promise that will resolve to a list of available log types.2354*/2355getAvailableLogTypes() {2356return this.driver_.execute(new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES))2357}2358}23592360/**2361* An interface for changing the focus of the driver to another frame or window.2362*2363* This class should never be instantiated directly. Instead, obtain an2364* instance with2365*2366* webdriver.switchTo()2367*2368* @see WebDriver#switchTo()2369*/2370class TargetLocator {2371/**2372* @param {!WebDriver} driver The parent driver.2373* @private2374*/2375constructor(driver) {2376/** @private {!WebDriver} */2377this.driver_ = driver2378}23792380/**2381* Locates the DOM element on the current page that corresponds to2382* `document.activeElement` or `document.body` if the active element is not2383* available.2384*2385* @return {!WebElementPromise} The active element.2386*/2387activeElement() {2388const id = this.driver_.execute(new command.Command(command.Name.GET_ACTIVE_ELEMENT))2389return new WebElementPromise(this.driver_, id)2390}23912392/**2393* Switches focus of all future commands to the topmost frame in the current2394* window.2395*2396* @return {!Promise<void>} A promise that will be resolved2397* when the driver has changed focus to the default content.2398*/2399defaultContent() {2400return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', null))2401}24022403/**2404* Changes the focus of all future commands to another frame on the page. The2405* target frame may be specified as one of the following:2406*2407* - A number that specifies a (zero-based) index into [window.frames](2408* https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).2409* - A {@link WebElement} reference, which correspond to a `frame` or `iframe`2410* DOM element.2411* - The `null` value, to select the topmost frame on the page. Passing `null`2412* is the same as calling {@link #defaultContent defaultContent()}.2413*2414* If the specified frame can not be found, the returned promise will be2415* rejected with a {@linkplain error.NoSuchFrameError}.2416*2417* @param {(number|string|WebElement|null)} id The frame locator.2418* @return {!Promise<void>} A promise that will be resolved2419* when the driver has changed focus to the specified frame.2420*/2421frame(id) {2422let frameReference = id2423if (typeof id === 'string') {2424frameReference = this.driver_.findElement({ id }).catch((_) => this.driver_.findElement({ name: id }))2425}24262427return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME).setParameter('id', frameReference))2428}24292430/**2431* Changes the focus of all future commands to the parent frame of the2432* currently selected frame. This command has no effect if the driver is2433* already focused on the top-level browsing context.2434*2435* @return {!Promise<void>} A promise that will be resolved when the command2436* has completed.2437*/2438parentFrame() {2439return this.driver_.execute(new command.Command(command.Name.SWITCH_TO_FRAME_PARENT))2440}24412442/**2443* Changes the focus of all future commands to another window. Windows may be2444* specified by their {@code window.name} attribute or by its handle2445* (as returned by {@link WebDriver#getWindowHandles}).2446*2447* If the specified window cannot be found, the returned promise will be2448* rejected with a {@linkplain error.NoSuchWindowError}.2449*2450* @param {string} nameOrHandle The name or window handle of the window to2451* switch focus to.2452* @return {!Promise<void>} A promise that will be resolved2453* when the driver has changed focus to the specified window.2454*/2455window(nameOrHandle) {2456return this.driver_.execute(2457new command.Command(command.Name.SWITCH_TO_WINDOW)2458// "name" supports the legacy drivers. "handle" is the W3C2459// compliant parameter.2460.setParameter('name', nameOrHandle)2461.setParameter('handle', nameOrHandle),2462)2463}24642465/**2466* Creates a new browser window and switches the focus for future2467* commands of this driver to the new window.2468*2469* @param {string} typeHint 'window' or 'tab'. The created window is not2470* guaranteed to be of the requested type; if the driver does not support2471* the requested type, a new browser window will be created of whatever type2472* the driver does support.2473* @return {!Promise<void>} A promise that will be resolved2474* when the driver has changed focus to the new window.2475*/2476newWindow(typeHint) {2477const driver = this.driver_2478return this.driver_2479.execute(new command.Command(command.Name.SWITCH_TO_NEW_WINDOW).setParameter('type', typeHint))2480.then(function (response) {2481return driver.switchTo().window(response.handle)2482})2483}24842485/**2486* Changes focus to the active modal dialog, such as those opened by2487* `window.alert()`, `window.confirm()`, and `window.prompt()`. The returned2488* promise will be rejected with a2489* {@linkplain error.NoSuchAlertError} if there are no open alerts.2490*2491* @return {!AlertPromise} The open alert.2492*/2493alert() {2494const text = this.driver_.execute(new command.Command(command.Name.GET_ALERT_TEXT))2495const driver = this.driver_2496return new AlertPromise(2497driver,2498text.then(function (text) {2499return new Alert(driver, text)2500}),2501)2502}2503}25042505//////////////////////////////////////////////////////////////////////////////2506//2507// WebElement2508//2509//////////////////////////////////////////////////////////////////////////////25102511const LEGACY_ELEMENT_ID_KEY = 'ELEMENT'2512const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf'2513const SHADOW_ROOT_ID_KEY = 'shadow-6066-11e4-a52e-4f735466cecf'25142515/**2516* Represents a DOM element. WebElements can be found by searching from the2517* document root using a {@link WebDriver} instance, or by searching2518* under another WebElement:2519*2520* driver.get('http://www.google.com');2521* var searchForm = driver.findElement(By.tagName('form'));2522* var searchBox = searchForm.findElement(By.name('q'));2523* searchBox.sendKeys('webdriver');2524*/2525class WebElement {2526/**2527* @param {!WebDriver} driver the parent WebDriver instance for this element.2528* @param {(!IThenable<string>|string)} id The server-assigned opaque ID for2529* the underlying DOM element.2530*/2531constructor(driver, id) {2532/** @private {!WebDriver} */2533this.driver_ = driver25342535/** @private {!Promise<string>} */2536this.id_ = Promise.resolve(id)25372538/** @private {!Logger} */2539this.log_ = logging.getLogger(logging.Type.DRIVER)2540}25412542/**2543* @param {string} id The raw ID.2544* @param {boolean=} noLegacy Whether to exclude the legacy element key.2545* @return {!Object} The element ID for use with WebDriver's wire protocol.2546*/2547static buildId(id, noLegacy = false) {2548return noLegacy ? { [ELEMENT_ID_KEY]: id } : { [ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id }2549}25502551/**2552* Extracts the encoded WebElement ID from the object.2553*2554* @param {?} obj The object to extract the ID from.2555* @return {string} the extracted ID.2556* @throws {TypeError} if the object is not a valid encoded ID.2557*/2558static extractId(obj) {2559return webElement.extractId(obj)2560}25612562/**2563* @param {?} obj the object to test.2564* @return {boolean} whether the object is a valid encoded WebElement ID.2565*/2566static isId(obj) {2567return webElement.isId(obj)2568}25692570/**2571* Compares two WebElements for equality.2572*2573* @param {!WebElement} a A WebElement.2574* @param {!WebElement} b A WebElement.2575* @return {!Promise<boolean>} A promise that will be2576* resolved to whether the two WebElements are equal.2577*/2578static async equals(a, b) {2579if (a === b) {2580return true2581}2582return a.driver_.executeScript('return arguments[0] === arguments[1]', a, b)2583}25842585/** @return {!WebDriver} The parent driver for this instance. */2586getDriver() {2587return this.driver_2588}25892590/**2591* @return {!Promise<string>} A promise that resolves to2592* the server-assigned opaque ID assigned to this element.2593*/2594getId() {2595return this.id_2596}25972598/**2599* @return {!Object} Returns the serialized representation of this WebElement.2600*/2601[Symbols.serialize]() {2602return this.getId().then(WebElement.buildId)2603}26042605/**2606* Schedules a command that targets this element with the parent WebDriver2607* instance. Will ensure this element's ID is included in the command2608* parameters under the "id" key.2609*2610* @param {!command.Command} command The command to schedule.2611* @return {!Promise<T>} A promise that will be resolved with the result.2612* @template T2613* @see WebDriver#schedule2614* @private2615*/2616execute_(command) {2617command.setParameter('id', this)2618return this.driver_.execute(command)2619}26202621/**2622* Schedule a command to find a descendant of this element. If the element2623* cannot be found, the returned promise will be rejected with a2624* {@linkplain error.NoSuchElementError NoSuchElementError}.2625*2626* The search criteria for an element may be defined using one of the static2627* factories on the {@link by.By} class, or as a short-hand2628* {@link ./by.ByHash} object. For example, the following two statements2629* are equivalent:2630*2631* var e1 = element.findElement(By.id('foo'));2632* var e2 = element.findElement({id:'foo'});2633*2634* You may also provide a custom locator function, which takes as input this2635* instance and returns a {@link WebElement}, or a promise that will resolve2636* to a WebElement. If the returned promise resolves to an array of2637* WebElements, WebDriver will use the first element. For example, to find the2638* first visible link on a page, you could write:2639*2640* var link = element.findElement(firstVisibleLink);2641*2642* function firstVisibleLink(element) {2643* var links = element.findElements(By.tagName('a'));2644* return promise.filter(links, function(link) {2645* return link.isDisplayed();2646* });2647* }2648*2649* @param {!(by.By|Function)} locator The locator strategy to use when2650* searching for the element.2651* @return {!WebElementPromise} A WebElement that can be used to issue2652* commands against the located element. If the element is not found, the2653* element will be invalidated and all scheduled commands aborted.2654*/2655findElement(locator) {2656locator = by.checkedLocator(locator)2657let id2658if (typeof locator === 'function') {2659id = this.driver_.findElementInternal_(locator, this)2660} else {2661let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENT)2662.setParameter('using', locator.using)2663.setParameter('value', locator.value)2664id = this.execute_(cmd)2665}2666return new WebElementPromise(this.driver_, id)2667}26682669/**2670* Locates all the descendants of this element that match the given search2671* criteria.2672*2673* @param {!(by.By|Function)} locator The locator strategy to use when2674* searching for the element.2675* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an2676* array of WebElements.2677*/2678async findElements(locator) {2679locator = by.checkedLocator(locator)2680if (typeof locator === 'function') {2681return this.driver_.findElementsInternal_(locator, this)2682} else {2683let cmd = new command.Command(command.Name.FIND_CHILD_ELEMENTS)2684.setParameter('using', locator.using)2685.setParameter('value', locator.value)2686let result = await this.execute_(cmd)2687return Array.isArray(result) ? result : []2688}2689}26902691/**2692* Clicks on this element.2693*2694* @return {!Promise<void>} A promise that will be resolved when the click2695* command has completed.2696*/2697click() {2698return this.execute_(new command.Command(command.Name.CLICK_ELEMENT))2699}27002701/**2702* Types a key sequence on the DOM element represented by this instance.2703*2704* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is2705* processed in the key sequence, that key state is toggled until one of the2706* following occurs:2707*2708* - The modifier key is encountered again in the sequence. At this point the2709* state of the key is toggled (along with the appropriate keyup/down2710* events).2711* - The {@link input.Key.NULL} key is encountered in the sequence. When2712* this key is encountered, all modifier keys current in the down state are2713* released (with accompanying keyup events). The NULL key can be used to2714* simulate common keyboard shortcuts:2715*2716* element.sendKeys("text was",2717* Key.CONTROL, "a", Key.NULL,2718* "now text is");2719* // Alternatively:2720* element.sendKeys("text was",2721* Key.chord(Key.CONTROL, "a"),2722* "now text is");2723*2724* - The end of the key sequence is encountered. When there are no more keys2725* to type, all depressed modifier keys are released (with accompanying2726* keyup events).2727*2728* If this element is a file input ({@code <input type="file">}), the2729* specified key sequence should specify the path to the file to attach to2730* the element. This is analogous to the user clicking "Browse..." and entering2731* the path into the file select dialog.2732*2733* var form = driver.findElement(By.css('form'));2734* var element = form.findElement(By.css('input[type=file]'));2735* element.sendKeys('/path/to/file.txt');2736* form.submit();2737*2738* For uploads to function correctly, the entered path must reference a file2739* on the _browser's_ machine, not the local machine running this script. When2740* running against a remote Selenium server, a {@link input.FileDetector}2741* may be used to transparently copy files to the remote machine before2742* attempting to upload them in the browser.2743*2744* __Note:__ On browsers where native keyboard events are not supported2745* (e.g. Firefox on OS X), key events will be synthesized. Special2746* punctuation keys will be synthesized according to a standard QWERTY en-us2747* keyboard layout.2748*2749* @param {...(number|string|!IThenable<(number|string)>)} args The2750* sequence of keys to type. Number keys may be referenced numerically or2751* by string (1 or '1'). All arguments will be joined into a single2752* sequence.2753* @return {!Promise<void>} A promise that will be resolved when all keys2754* have been typed.2755*/2756async sendKeys(...args) {2757let keys = []2758;(await Promise.all(args)).forEach((key) => {2759let type = typeof key2760if (type === 'number') {2761key = String(key)2762} else if (type !== 'string') {2763throw TypeError('each key must be a number or string; got ' + type)2764}27652766// The W3C protocol requires keys to be specified as an array where2767// each element is a single key.2768keys.push(...key)2769})27702771if (!this.driver_.fileDetector_) {2772return this.execute_(2773new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)2774.setParameter('text', keys.join(''))2775.setParameter('value', keys),2776)2777}27782779try {2780keys = await this.driver_.fileDetector_.handleFile(this.driver_, keys.join(''))2781} catch (ex) {2782this.log_.severe('Error trying parse string as a file with file detector; sending keys instead' + ex)2783keys = keys.join('')2784}27852786return this.execute_(2787new command.Command(command.Name.SEND_KEYS_TO_ELEMENT)2788.setParameter('text', keys)2789.setParameter('value', keys.split('')),2790)2791}27922793/**2794* Retrieves the element's tag name.2795*2796* @return {!Promise<string>} A promise that will be resolved with the2797* element's tag name.2798*/2799getTagName() {2800return this.execute_(new command.Command(command.Name.GET_ELEMENT_TAG_NAME))2801}28022803/**2804* Retrieves the value of a computed style property for this instance. If2805* the element inherits the named style from its parent, the parent will be2806* queried for its value. Where possible, color values will be converted to2807* their hex representation (e.g. #00ff00 instead of rgb(0, 255, 0)).2808*2809* _Warning:_ the value returned will be as the browser interprets it, so2810* it may be tricky to form a proper assertion.2811*2812* @param {string} cssStyleProperty The name of the CSS style property to look2813* up.2814* @return {!Promise<string>} A promise that will be resolved with the2815* requested CSS value.2816*/2817getCssValue(cssStyleProperty) {2818const name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY2819return this.execute_(new command.Command(name).setParameter('propertyName', cssStyleProperty))2820}28212822/**2823* Retrieves the current value of the given attribute of this element.2824* Will return the current value, even if it has been modified after the page2825* has been loaded. More exactly, this method will return the value2826* of the given attribute, unless that attribute is not present, in which case2827* the value of the property with the same name is returned. If neither value2828* is set, null is returned (for example, the "value" property of a textarea2829* element). The "style" attribute is converted as best can be to a2830* text representation with a trailing semicolon. The following are deemed to2831* be "boolean" attributes and will return either "true" or null:2832*2833* async, autofocus, autoplay, checked, compact, complete, controls, declare,2834* defaultchecked, defaultselected, defer, disabled, draggable, ended,2835* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,2836* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,2837* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,2838* selected, spellcheck, truespeed, willvalidate2839*2840* Finally, the following commonly mis-capitalized attribute/property names2841* are evaluated as expected:2842*2843* - "class"2844* - "readonly"2845*2846* @param {string} attributeName The name of the attribute to query.2847* @return {!Promise<?string>} A promise that will be2848* resolved with the attribute's value. The returned value will always be2849* either a string or null.2850*/2851getAttribute(attributeName) {2852return this.execute_(new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).setParameter('name', attributeName))2853}28542855/**2856* Get the value of the given attribute of the element.2857* <p>2858* This method, unlike {@link #getAttribute(String)}, returns the value of the attribute with the2859* given name but not the property with the same name.2860* <p>2861* The following are deemed to be "boolean" attributes, and will return either "true" or null:2862* <p>2863* async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked,2864* defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate,2865* iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade,2866* novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless,2867* seeking, selected, truespeed, willvalidate2868* <p>2869* See <a href="https://w3c.github.io/webdriver/#get-element-attribute">W3C WebDriver specification</a>2870* for more details.2871*2872* @param attributeName The name of the attribute.2873* @return The attribute's value or null if the value is not set.2874*/28752876getDomAttribute(attributeName) {2877return this.execute_(new command.Command(command.Name.GET_DOM_ATTRIBUTE).setParameter('name', attributeName))2878}28792880/**2881* Get the given property of the referenced web element2882* @param {string} propertyName The name of the attribute to query.2883* @return {!Promise<string>} A promise that will be2884* resolved with the element's property value2885*/2886getProperty(propertyName) {2887return this.execute_(new command.Command(command.Name.GET_ELEMENT_PROPERTY).setParameter('name', propertyName))2888}28892890/**2891* Get the shadow root of the current web element.2892* @returns {!Promise<ShadowRoot>} A promise that will be2893* resolved with the elements shadow root or rejected2894* with {@link NoSuchShadowRootError}2895*/2896getShadowRoot() {2897return this.execute_(new command.Command(command.Name.GET_SHADOW_ROOT))2898}28992900/**2901* Get the visible (i.e. not hidden by CSS) innerText of this element,2902* including sub-elements, without any leading or trailing whitespace.2903*2904* @return {!Promise<string>} A promise that will be2905* resolved with the element's visible text.2906*/2907getText() {2908return this.execute_(new command.Command(command.Name.GET_ELEMENT_TEXT))2909}29102911/**2912* Get the computed WAI-ARIA role of element.2913*2914* @return {!Promise<string>} A promise that will be2915* resolved with the element's computed role.2916*/2917getAriaRole() {2918return this.execute_(new command.Command(command.Name.GET_COMPUTED_ROLE))2919}29202921/**2922* Get the computed WAI-ARIA label of element.2923*2924* @return {!Promise<string>} A promise that will be2925* resolved with the element's computed label.2926*/2927getAccessibleName() {2928return this.execute_(new command.Command(command.Name.GET_COMPUTED_LABEL))2929}29302931/**2932* Returns an object describing an element's location, in pixels relative to2933* the document element, and the element's size in pixels.2934*2935* @return {!Promise<{width: number, height: number, x: number, y: number}>}2936* A promise that will resolve with the element's rect.2937*/2938getRect() {2939return this.execute_(new command.Command(command.Name.GET_ELEMENT_RECT))2940}29412942/**2943* Tests whether this element is enabled, as dictated by the `disabled`2944* attribute.2945*2946* @return {!Promise<boolean>} A promise that will be2947* resolved with whether this element is currently enabled.2948*/2949isEnabled() {2950return this.execute_(new command.Command(command.Name.IS_ELEMENT_ENABLED))2951}29522953/**2954* Tests whether this element is selected.2955*2956* @return {!Promise<boolean>} A promise that will be2957* resolved with whether this element is currently selected.2958*/2959isSelected() {2960return this.execute_(new command.Command(command.Name.IS_ELEMENT_SELECTED))2961}29622963/**2964* Submits the form containing this element (or this element if it is itself2965* a FORM element). his command is a no-op if the element is not contained in2966* a form.2967*2968* @return {!Promise<void>} A promise that will be resolved2969* when the form has been submitted.2970*/2971submit() {2972const script =2973'/* submitForm */var form = arguments[0];\n' +2974'while (form.nodeName != "FORM" && form.parentNode) {\n' +2975' form = form.parentNode;\n' +2976'}\n' +2977"if (!form) { throw Error('Unable to find containing form element'); }\n" +2978"if (!form.ownerDocument) { throw Error('Unable to find owning document'); }\n" +2979"var e = form.ownerDocument.createEvent('Event');\n" +2980"e.initEvent('submit', true, true);\n" +2981'if (form.dispatchEvent(e)) { HTMLFormElement.prototype.submit.call(form) }\n'29822983return this.driver_.executeScript(script, this)2984}29852986/**2987* Clear the `value` of this element. This command has no effect if the2988* underlying DOM element is neither a text INPUT element nor a TEXTAREA2989* element.2990*2991* @return {!Promise<void>} A promise that will be resolved2992* when the element has been cleared.2993*/2994clear() {2995return this.execute_(new command.Command(command.Name.CLEAR_ELEMENT))2996}29972998/**2999* Test whether this element is currently displayed.3000*3001* @return {!Promise<boolean>} A promise that will be3002* resolved with whether this element is currently visible on the page.3003*/3004isDisplayed() {3005return this.execute_(new command.Command(command.Name.IS_ELEMENT_DISPLAYED))3006}30073008/**3009* Take a screenshot of the visible region encompassed by this element's3010* bounding rectangle.3011*3012* @return {!Promise<string>} A promise that will be3013* resolved to the screenshot as a base-64 encoded PNG.3014*/3015takeScreenshot() {3016return this.execute_(new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT))3017}3018}30193020/**3021* WebElementPromise is a promise that will be fulfilled with a WebElement.3022* This serves as a forward proxy on WebElement, allowing calls to be3023* scheduled without directly on this instance before the underlying3024* WebElement has been fulfilled. In other words, the following two statements3025* are equivalent:3026*3027* driver.findElement({id: 'my-button'}).click();3028* driver.findElement({id: 'my-button'}).then(function(el) {3029* return el.click();3030* });3031*3032* @implements {IThenable<!WebElement>}3033* @final3034*/3035class WebElementPromise extends WebElement {3036/**3037* @param {!WebDriver} driver The parent WebDriver instance for this3038* element.3039* @param {!Promise<!WebElement>} el A promise3040* that will resolve to the promised element.3041*/3042constructor(driver, el) {3043super(driver, 'unused')30443045/** @override */3046this.then = el.then.bind(el)30473048/** @override */3049this.catch = el.catch.bind(el)30503051/**3052* Defers returning the element ID until the wrapped WebElement has been3053* resolved.3054* @override3055*/3056this.getId = function () {3057return el.then(function (el) {3058return el.getId()3059})3060}3061}3062}30633064//////////////////////////////////////////////////////////////////////////////3065//3066// ShadowRoot3067//3068//////////////////////////////////////////////////////////////////////////////30693070/**3071* Represents a ShadowRoot of a {@link WebElement}. Provides functions to3072* retrieve elements that live in the DOM below the ShadowRoot.3073*/3074class ShadowRoot {3075constructor(driver, id) {3076this.driver_ = driver3077this.id_ = id3078}30793080/**3081* Extracts the encoded ShadowRoot ID from the object.3082*3083* @param {?} obj The object to extract the ID from.3084* @return {string} the extracted ID.3085* @throws {TypeError} if the object is not a valid encoded ID.3086*/3087static extractId(obj) {3088if (obj && typeof obj === 'object') {3089if (typeof obj[SHADOW_ROOT_ID_KEY] === 'string') {3090return obj[SHADOW_ROOT_ID_KEY]3091}3092}3093throw new TypeError('object is not a ShadowRoot ID')3094}30953096/**3097* @param {?} obj the object to test.3098* @return {boolean} whether the object is a valid encoded WebElement ID.3099*/3100static isId(obj) {3101return obj && typeof obj === 'object' && typeof obj[SHADOW_ROOT_ID_KEY] === 'string'3102}31033104/**3105* @return {!Object} Returns the serialized representation of this ShadowRoot.3106*/3107[Symbols.serialize]() {3108return this.getId()3109}31103111/**3112* Schedules a command that targets this element with the parent WebDriver3113* instance. Will ensure this element's ID is included in the command3114* parameters under the "id" key.3115*3116* @param {!command.Command} command The command to schedule.3117* @return {!Promise<T>} A promise that will be resolved with the result.3118* @template T3119* @see WebDriver#schedule3120* @private3121*/3122execute_(command) {3123command.setParameter('id', this)3124return this.driver_.execute(command)3125}31263127/**3128* Schedule a command to find a descendant of this ShadowROot. If the element3129* cannot be found, the returned promise will be rejected with a3130* {@linkplain error.NoSuchElementError NoSuchElementError}.3131*3132* The search criteria for an element may be defined using one of the static3133* factories on the {@link by.By} class, or as a short-hand3134* {@link ./by.ByHash} object. For example, the following two statements3135* are equivalent:3136*3137* var e1 = shadowroot.findElement(By.id('foo'));3138* var e2 = shadowroot.findElement({id:'foo'});3139*3140* You may also provide a custom locator function, which takes as input this3141* instance and returns a {@link WebElement}, or a promise that will resolve3142* to a WebElement. If the returned promise resolves to an array of3143* WebElements, WebDriver will use the first element. For example, to find the3144* first visible link on a page, you could write:3145*3146* var link = element.findElement(firstVisibleLink);3147*3148* function firstVisibleLink(shadowRoot) {3149* var links = shadowRoot.findElements(By.tagName('a'));3150* return promise.filter(links, function(link) {3151* return link.isDisplayed();3152* });3153* }3154*3155* @param {!(by.By|Function)} locator The locator strategy to use when3156* searching for the element.3157* @return {!WebElementPromise} A WebElement that can be used to issue3158* commands against the located element. If the element is not found, the3159* element will be invalidated and all scheduled commands aborted.3160*/3161findElement(locator) {3162locator = by.checkedLocator(locator)3163let id3164if (typeof locator === 'function') {3165id = this.driver_.findElementInternal_(locator, this)3166} else {3167let cmd = new command.Command(command.Name.FIND_ELEMENT_FROM_SHADOWROOT)3168.setParameter('using', locator.using)3169.setParameter('value', locator.value)3170id = this.execute_(cmd)3171}3172return new ShadowRootPromise(this.driver_, id)3173}31743175/**3176* Locates all the descendants of this element that match the given search3177* criteria.3178*3179* @param {!(by.By|Function)} locator The locator strategy to use when3180* searching for the element.3181* @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an3182* array of WebElements.3183*/3184async findElements(locator) {3185locator = by.checkedLocator(locator)3186if (typeof locator === 'function') {3187return this.driver_.findElementsInternal_(locator, this)3188} else {3189let cmd = new command.Command(command.Name.FIND_ELEMENTS_FROM_SHADOWROOT)3190.setParameter('using', locator.using)3191.setParameter('value', locator.value)3192let result = await this.execute_(cmd)3193return Array.isArray(result) ? result : []3194}3195}31963197getId() {3198return this.id_3199}3200}32013202/**3203* ShadowRootPromise is a promise that will be fulfilled with a WebElement.3204* This serves as a forward proxy on ShadowRoot, allowing calls to be3205* scheduled without directly on this instance before the underlying3206* ShadowRoot has been fulfilled.3207*3208* @implements { IThenable<!ShadowRoot>}3209* @final3210*/3211class ShadowRootPromise extends ShadowRoot {3212/**3213* @param {!WebDriver} driver The parent WebDriver instance for this3214* element.3215* @param {!Promise<!ShadowRoot>} shadow A promise3216* that will resolve to the promised element.3217*/3218constructor(driver, shadow) {3219super(driver, 'unused')32203221/** @override */3222this.then = shadow.then.bind(shadow)32233224/** @override */3225this.catch = shadow.catch.bind(shadow)32263227/**3228* Defers returning the ShadowRoot ID until the wrapped WebElement has been3229* resolved.3230* @override3231*/3232this.getId = function () {3233return shadow.then(function (shadow) {3234return shadow.getId()3235})3236}3237}3238}32393240//////////////////////////////////////////////////////////////////////////////3241//3242// Alert3243//3244//////////////////////////////////////////////////////////////////////////////32453246/**3247* Represents a modal dialog such as {@code alert}, {@code confirm}, or3248* {@code prompt}. Provides functions to retrieve the message displayed with3249* the alert, accept or dismiss the alert, and set the response text (in the3250* case of {@code prompt}).3251*/3252class Alert {3253/**3254* @param {!WebDriver} driver The driver controlling the browser this alert3255* is attached to.3256* @param {string} text The message text displayed with this alert.3257*/3258constructor(driver, text) {3259/** @private {!WebDriver} */3260this.driver_ = driver32613262/** @private {!Promise<string>} */3263this.text_ = Promise.resolve(text)3264}32653266/**3267* Retrieves the message text displayed with this alert. For instance, if the3268* alert were opened with alert("hello"), then this would return "hello".3269*3270* @return {!Promise<string>} A promise that will be3271* resolved to the text displayed with this alert.3272*/3273getText() {3274return this.text_3275}32763277/**3278* Accepts this alert.3279*3280* @return {!Promise<void>} A promise that will be resolved3281* when this command has completed.3282*/3283accept() {3284return this.driver_.execute(new command.Command(command.Name.ACCEPT_ALERT))3285}32863287/**3288* Dismisses this alert.3289*3290* @return {!Promise<void>} A promise that will be resolved3291* when this command has completed.3292*/3293dismiss() {3294return this.driver_.execute(new command.Command(command.Name.DISMISS_ALERT))3295}32963297/**3298* Sets the response text on this alert. This command will return an error if3299* the underlying alert does not support response text (e.g. window.alert and3300* window.confirm).3301*3302* @param {string} text The text to set.3303* @return {!Promise<void>} A promise that will be resolved3304* when this command has completed.3305*/3306sendKeys(text) {3307return this.driver_.execute(new command.Command(command.Name.SET_ALERT_TEXT).setParameter('text', text))3308}3309}33103311/**3312* AlertPromise is a promise that will be fulfilled with an Alert. This promise3313* serves as a forward proxy on an Alert, allowing calls to be scheduled3314* directly on this instance before the underlying Alert has been fulfilled. In3315* other words, the following two statements are equivalent:3316*3317* driver.switchTo().alert().dismiss();3318* driver.switchTo().alert().then(function(alert) {3319* return alert.dismiss();3320* });3321*3322* @implements {IThenable<!Alert>}3323* @final3324*/3325class AlertPromise extends Alert {3326/**3327* @param {!WebDriver} driver The driver controlling the browser this3328* alert is attached to.3329* @param {!Promise<!Alert>} alert A thenable3330* that will be fulfilled with the promised alert.3331*/3332constructor(driver, alert) {3333super(driver, 'unused')33343335/** @override */3336this.then = alert.then.bind(alert)33373338/** @override */3339this.catch = alert.catch.bind(alert)33403341/**3342* Defer returning text until the promised alert has been resolved.3343* @override3344*/3345this.getText = function () {3346return alert.then(function (alert) {3347return alert.getText()3348})3349}33503351/**3352* Defers action until the alert has been located.3353* @override3354*/3355this.accept = function () {3356return alert.then(function (alert) {3357return alert.accept()3358})3359}33603361/**3362* Defers action until the alert has been located.3363* @override3364*/3365this.dismiss = function () {3366return alert.then(function (alert) {3367return alert.dismiss()3368})3369}33703371/**3372* Defers action until the alert has been located.3373* @override3374*/3375this.sendKeys = function (text) {3376return alert.then(function (alert) {3377return alert.sendKeys(text)3378})3379}3380}3381}33823383// PUBLIC API33843385module.exports = {3386Alert,3387AlertPromise,3388Condition,3389Logs,3390Navigation,3391Options,3392ShadowRoot,3393TargetLocator,3394IWebDriver,3395WebDriver,3396WebElement,3397WebElementCondition,3398WebElementPromise,3399Window,3400}340134023403