UNPKG

selenium-webdriver

Version:

The official WebDriver JavaScript bindings from the Selenium project

1,582 lines (1,409 loc) 108 kB
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview The heart of the WebDriver JavaScript API. */ 'use strict' const by = require('./by') const { RelativeBy } = require('./by') const command = require('./command') const error = require('./error') const input = require('./input') const logging = require('./logging') const promise = require('./promise') const Symbols = require('./symbols') const cdp = require('../devtools/CDPConnection') const WebSocket = require('ws') const http = require('../http/index') const fs = require('node:fs') const { Capabilities } = require('./capabilities') const path = require('node:path') const { NoSuchElementError } = require('./error') const cdpTargets = ['page', 'browser'] const { Credential } = require('./virtual_authenticator') const webElement = require('./webelement') const { isObject } = require('./util') const BIDI = require('../bidi') const { PinnedScript } = require('./pinnedScript') const JSZip = require('jszip') const Script = require('./script') const Network = require('./network') const Dialog = require('./fedcm/dialog') // Capability names that are defined in the W3C spec. const W3C_CAPABILITY_NAMES = new Set([ 'acceptInsecureCerts', 'browserName', 'browserVersion', 'pageLoadStrategy', 'platformName', 'proxy', 'setWindowRect', 'strictFileInteractability', 'timeouts', 'unhandledPromptBehavior', 'webSocketUrl', ]) /** * Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait * command}. * * @template OUT */ class Condition { /** * @param {string} message A descriptive error message. Should complete the * sentence "Waiting [...]" * @param {function(!WebDriver): OUT} fn The condition function to * evaluate on each iteration of the wait loop. */ constructor(message, fn) { /** @private {string} */ this.description_ = 'Waiting ' + message /** @type {function(!WebDriver): OUT} */ this.fn = fn } /** @return {string} A description of this condition. */ description() { return this.description_ } } /** * Defines a condition that will result in a {@link WebElement}. * * @extends {Condition<!(WebElement|IThenable<!WebElement>)>} */ class WebElementCondition extends Condition { /** * @param {string} message A descriptive error message. Should complete the * sentence "Waiting [...]" * @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)} * fn The condition function to evaluate on each iteration of the wait * loop. */ constructor(message, fn) { super(message, fn) } } ////////////////////////////////////////////////////////////////////////////// // // WebDriver // ////////////////////////////////////////////////////////////////////////////// /** * Translates a command to its wire-protocol representation before passing it * to the given `executor` for execution. * @param {!command.Executor} executor The executor to use. * @param {!command.Command} command The command to execute. * @return {!Promise} A promise that will resolve with the command response. */ function executeCommand(executor, command) { return toWireValue(command.getParameters()).then(function (parameters) { command.setParameters(parameters) return executor.execute(command) }) } /** * Converts an object to its JSON representation in the WebDriver wire protocol. * When converting values of type object, the following steps will be taken: * <ol> * <li>if the object is a WebElement, the return value will be the element's * server ID * <li>if the object defines a {@link Symbols.serialize} method, this algorithm * will be recursively applied to the object's serialized representation * <li>if the object provides a "toJSON" function, this algorithm will * recursively be applied to the result of that function * <li>otherwise, the value of each key will be recursively converted according * to the rules above. * </ol> * * @param {*} obj The object to convert. * @return {!Promise<?>} A promise that will resolve to the input value's JSON * representation. */ async function toWireValue(obj) { let value = await Promise.resolve(obj) if (value === void 0 || value === null) { return value } if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') { return value } if (Array.isArray(value)) { return convertKeys(value) } if (typeof value === 'function') { return '' + value } if (typeof value[Symbols.serialize] === 'function') { return toWireValue(value[Symbols.serialize]()) } else if (typeof value.toJSON === 'function') { return toWireValue(value.toJSON()) } return convertKeys(value) } async function convertKeys(obj) { const isArray = Array.isArray(obj) const numKeys = isArray ? obj.length : Object.keys(obj).length const ret = isArray ? new Array(numKeys) : {} if (!numKeys) { return ret } async function forEachKey(obj, fn) { if (Array.isArray(obj)) { for (let i = 0, n = obj.length; i < n; i++) { await fn(obj[i], i) } } else { for (let key in obj) { await fn(obj[key], key) } } } await forEachKey(obj, async function (value, key) { ret[key] = await toWireValue(value) }) return ret } /** * Converts a value from its JSON representation according to the WebDriver wire * protocol. Any JSON object that defines a WebElement ID will be decoded to a * {@link WebElement} object. All other values will be passed through as is. * * @param {!WebDriver} driver The driver to use as the parent of any unwrapped * {@link WebElement} values. * @param {*} value The value to convert. * @return {*} The converted value. */ function fromWireValue(driver, value) { if (Array.isArray(value)) { value = value.map((v) => fromWireValue(driver, v)) } else if (WebElement.isId(value)) { let id = WebElement.extractId(value) value = new WebElement(driver, id) } else if (ShadowRoot.isId(value)) { let id = ShadowRoot.extractId(value) value = new ShadowRoot(driver, id) } else if (isObject(value)) { let result = {} for (let key in value) { if (Object.prototype.hasOwnProperty.call(value, key)) { result[key] = fromWireValue(driver, value[key]) } } value = result } return value } /** * Resolves a wait message from either a function or a string. * @param {(string|Function)=} message An optional message to use if the wait times out. * @return {string} The resolved message */ function resolveWaitMessage(message) { return message ? `${typeof message === 'function' ? message() : message}\n` : '' } /** * Structural interface for a WebDriver client. * * @record */ class IWebDriver { /** * Executes the provided {@link command.Command} using this driver's * {@link command.Executor}. * * @param {!command.Command} command The command to schedule. * @return {!Promise<T>} A promise that will be resolved with the command * result. * @template T */ execute(command) {} // eslint-disable-line /** * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. * @param {input.FileDetector} detector The detector to use or `null`. */ setFileDetector(detector) {} // eslint-disable-line /** * @return {!command.Executor} The command executor used by this instance. */ getExecutor() {} /** * @return {!Promise<!Session>} A promise for this client's session. */ getSession() {} /** * @return {!Promise<!Capabilities>} A promise that will resolve with * the instance's capabilities. */ getCapabilities() {} /** * Terminates the browser session. After calling quit, this instance will be * invalidated and may no longer be used to issue commands against the * browser. * * @return {!Promise<void>} A promise that will be resolved when the * command has completed. */ quit() {} /** * Creates a new action sequence using this driver. The sequence will not be * submitted for execution until * {@link ./input.Actions#perform Actions.perform()} is called. * * @param {{async: (boolean|undefined), * bridge: (boolean|undefined)}=} options Configuration options for * the action sequence (see {@link ./input.Actions Actions} documentation * for details). * @return {!input.Actions} A new action sequence for this instance. */ actions(options) {} // eslint-disable-line /** * Executes a snippet of JavaScript in the context of the currently selected * frame or window. The script fragment will be executed as the body of an * anonymous function. If the script is provided as a function object, that * function will be converted to a string for injection into the target * window. * * Any arguments provided in addition to the script will be included as script * arguments and may be referenced using the `arguments` object. Arguments may * be a boolean, number, string, or {@linkplain WebElement}. Arrays and * objects may also be used as script arguments as long as each item adheres * to the types previously mentioned. * * The script may refer to any variables accessible from the current window. * Furthermore, the script will execute in the window's context, thus * `document` may be used to refer to the current document. Any local * variables will not be available once the script has finished executing, * though global variables will persist. * * If the script has a return value (i.e. if the script contains a return * statement), then the following steps will be taken for resolving this * functions return value: * * - For a HTML element, the value will resolve to a {@linkplain WebElement} * - Null and undefined return values will resolve to null</li> * - Booleans, numbers, and strings will resolve as is</li> * - Functions will resolve to their string representation</li> * - For arrays and objects, each member item will be converted according to * the rules above * * @param {!(string|Function)} script The script to execute. * @param {...*} args The arguments to pass to the script. * @return {!IThenable<T>} A promise that will resolve to the * scripts return value. * @template T */ executeScript(script, ...args) {} // eslint-disable-line /** * Executes a snippet of asynchronous JavaScript in the context of the * currently selected frame or window. The script fragment will be executed as * the body of an anonymous function. If the script is provided as a function * object, that function will be converted to a string for injection into the * target window. * * Any arguments provided in addition to the script will be included as script * arguments and may be referenced using the `arguments` object. Arguments may * be a boolean, number, string, or {@linkplain WebElement}. Arrays and * objects may also be used as script arguments as long as each item adheres * to the types previously mentioned. * * Unlike executing synchronous JavaScript with {@link #executeScript}, * scripts executed with this function must explicitly signal they are * finished by invoking the provided callback. This callback will always be * injected into the executed function as the last argument, and thus may be * referenced with `arguments[arguments.length - 1]`. The following steps * will be taken for resolving this functions return value against the first * argument to the script's callback function: * * - For a HTML element, the value will resolve to a {@link WebElement} * - Null and undefined return values will resolve to null * - Booleans, numbers, and strings will resolve as is * - Functions will resolve to their string representation * - For arrays and objects, each member item will be converted according to * the rules above * * __Example #1:__ Performing a sleep that is synchronized with the currently * selected window: * * var start = new Date().getTime(); * driver.executeAsyncScript( * 'window.setTimeout(arguments[arguments.length - 1], 500);'). * then(function() { * console.log( * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); * }); * * __Example #2:__ Synchronizing a test with an AJAX application: * * var button = driver.findElement(By.id('compose-button')); * button.click(); * driver.executeAsyncScript( * 'var callback = arguments[arguments.length - 1];' + * 'mailClient.getComposeWindowWidget().onload(callback);'); * driver.switchTo().frame('composeWidget'); * driver.findElement(By.id('to')).sendKeys('dog@example.com'); * * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In * this example, the inject script is specified with a function literal. When * using this format, the function is converted to a string for injection, so * it should not reference any symbols not defined in the scope of the page * under test. * * driver.executeAsyncScript(function() { * var callback = arguments[arguments.length - 1]; * var xhr = new XMLHttpRequest(); * xhr.open("GET", "/resource/data.json", true); * xhr.onreadystatechange = function() { * if (xhr.readyState == 4) { * callback(xhr.responseText); * } * }; * xhr.send(''); * }).then(function(str) { * console.log(JSON.parse(str)['food']); * }); * * @param {!(string|Function)} script The script to execute. * @param {...*} args The arguments to pass to the script. * @return {!IThenable<T>} A promise that will resolve to the scripts return * value. * @template T */ executeAsyncScript(script, ...args) {} // eslint-disable-line /** * Waits for a condition to evaluate to a "truthy" value. The condition may be * specified by a {@link Condition}, as a custom function, or as any * promise-like thenable. * * For a {@link Condition} or function, the wait will repeatedly * evaluate the condition until it returns a truthy value. If any errors occur * while evaluating the condition, they will be allowed to propagate. In the * event a condition returns a {@linkplain Promise}, the polling loop will * wait for it to be resolved and use the resolved value for whether the * condition has been satisfied. The resolution time for a promise is always * factored into whether a wait has timed out. * * If the provided condition is a {@link WebElementCondition}, then * the wait will return a {@link WebElementPromise} that will resolve to the * element that satisfied the condition. * * _Example:_ waiting up to 10 seconds for an element to be present on the * page. * * async function example() { * let button = * await driver.wait(until.elementLocated(By.id('foo')), 10000); * await button.click(); * } * * @param {!(IThenable<T>| * Condition<T>| * function(!WebDriver): T)} condition The condition to * wait on, defined as a promise, condition object, or a function to * evaluate as a condition. * @param {number=} timeout The duration in milliseconds, how long to wait * for the condition to be true. * @param {(string|Function)=} message An optional message to use if the wait times out. * @param {number=} pollTimeout The duration in milliseconds, how long to * wait between polling the condition. * @return {!(IThenable<T>|WebElementPromise)} A promise that will be * resolved with the first truthy value returned by the condition * function, or rejected if the condition times out. If the input * condition is an instance of a {@link WebElementCondition}, * the returned value will be a {@link WebElementPromise}. * @throws {TypeError} if the provided `condition` is not a valid type. * @template T */ wait( condition, // eslint-disable-line timeout = undefined, // eslint-disable-line message = undefined, // eslint-disable-line pollTimeout = undefined, // eslint-disable-line ) {} /** * Makes the driver sleep for the given amount of time. * * @param {number} ms The amount of time, in milliseconds, to sleep. * @return {!Promise<void>} A promise that will be resolved when the sleep has * finished. */ sleep(ms) {} // eslint-disable-line /** * Retrieves the current window handle. * * @return {!Promise<string>} A promise that will be resolved with the current * window handle. */ getWindowHandle() {} /** * Retrieves a list of all available window handles. * * @return {!Promise<!Array<string>>} A promise that will be resolved with an * array of window handles. */ getAllWindowHandles() {} /** * Retrieves the current page's source. The returned source is a representation * of the underlying DOM: do not expect it to be formatted or escaped in the * same way as the raw response sent from the web server. * * @return {!Promise<string>} A promise that will be resolved with the current * page source. */ getPageSource() {} /** * Closes the current window. * * @return {!Promise<void>} A promise that will be resolved when this command * has completed. */ close() {} /** * Navigates to the given URL. * * @param {string} url The fully qualified URL to open. * @return {!Promise<void>} A promise that will be resolved when the document * has finished loading. */ get(url) {} // eslint-disable-line /** * Retrieves the URL for the current page. * * @return {!Promise<string>} A promise that will be resolved with the * current URL. */ getCurrentUrl() {} /** * Retrieves the current page title. * * @return {!Promise<string>} A promise that will be resolved with the current * page's title. */ getTitle() {} /** * Locates an element on the page. If the element cannot be found, a * {@link error.NoSuchElementError} will be returned by the driver. * * This function should not be used to test whether an element is present on * the page. Rather, you should use {@link #findElements}: * * driver.findElements(By.id('foo')) * .then(found => console.log('Element found? %s', !!found.length)); * * The search criteria for an element may be defined using one of the * factories in the {@link webdriver.By} namespace, or as a short-hand * {@link webdriver.By.Hash} object. For example, the following two statements * are equivalent: * * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * * You may also provide a custom locator function, which takes as input this * instance and returns a {@link WebElement}, or a promise that will resolve * to a WebElement. If the returned promise resolves to an array of * WebElements, WebDriver will use the first element. For example, to find the * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); * return promise.filter(links, function(link) { * return link.isDisplayed(); * }); * } * * @param {!(by.By|Function)} locator The locator to use. * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ findElement(locator) {} // eslint-disable-line /** * Search for multiple elements on the page. Refer to the documentation on * {@link #findElement(by)} for information on element locator strategies. * * @param {!(by.By|Function)} locator The locator to use. * @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an * array of WebElements. */ findElements(locator) {} // eslint-disable-line /** * Takes a screenshot of the current page. The driver makes the best effort to * return a screenshot of the following, in order of preference: * * 1. Entire page * 2. Current window * 3. Visible portion of the current frame * 4. The entire display containing the browser * * @return {!Promise<string>} A promise that will be resolved to the * screenshot as a base-64 encoded PNG. */ takeScreenshot() {} /** * @return {!Options} The options interface for this instance. */ manage() {} /** * @return {!Navigation} The navigation interface for this instance. */ navigate() {} /** * @return {!TargetLocator} The target locator interface for this * instance. */ switchTo() {} /** * * Takes a PDF of the current page. The driver makes a best effort to * return a PDF based on the provided parameters. * * @param {{orientation:(string|undefined), * scale:(number|undefined), * background:(boolean|undefined), * width:(number|undefined), * height:(number|undefined), * top:(number|undefined), * bottom:(number|undefined), * left:(number|undefined), * right:(number|undefined), * shrinkToFit:(boolean|undefined), * pageRanges:(Array|undefined)}} options */ printPage(options) {} // eslint-disable-line } /** * @param {!Capabilities} capabilities A capabilities object. * @return {!Capabilities} A copy of the parameter capabilities, omitting * capability names that are not valid W3C names. */ function filterNonW3CCaps(capabilities) { let newCaps = new Capabilities(capabilities) for (let k of newCaps.keys()) { // Any key containing a colon is a vendor-prefixed capability. if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) { newCaps.delete(k) } } return newCaps } /** * Each WebDriver instance provides automated control over a browser session. * * @implements {IWebDriver} */ class WebDriver { #script = undefined #network = undefined /** * @param {!(./session.Session|IThenable<!./session.Session>)} session Either * a known session or a promise that will be resolved to a session. * @param {!command.Executor} executor The executor to use when sending * commands to the browser. * @param {(function(this: void): ?)=} onQuit A function to call, if any, * when the session is terminated. */ constructor(session, executor, onQuit = undefined) { /** @private {!Promise<!Session>} */ this.session_ = Promise.resolve(session) // If session is a rejected promise, add a no-op rejection handler. // This effectively hides setup errors until users attempt to interact // with the session. this.session_.catch(function () {}) /** @private {!command.Executor} */ this.executor_ = executor /** @private {input.FileDetector} */ this.fileDetector_ = null /** @private @const {(function(this: void): ?|undefined)} */ this.onQuit_ = onQuit /** @private {./virtual_authenticator}*/ this.authenticatorId_ = null this.pinnedScripts_ = {} } /** * Creates a new WebDriver session. * * This function will always return a WebDriver instance. If there is an error * creating the session, such as the aforementioned SessionNotCreatedError, * the driver will have a rejected {@linkplain #getSession session} promise. * This rejection will propagate through any subsequent commands scheduled * on the returned WebDriver instance. * * let required = Capabilities.firefox(); * let driver = WebDriver.createSession(executor, {required}); * * // If the createSession operation failed, then this command will also * // also fail, propagating the creation failure. * driver.get('http://www.google.com').catch(e => console.log(e)); * * @param {!command.Executor} executor The executor to create the new session * with. * @param {!Capabilities} capabilities The desired capabilities for the new * session. * @param {(function(this: void): ?)=} onQuit A callback to invoke when * the newly created session is terminated. This should be used to clean * up any resources associated with the session. * @return {!WebDriver} The driver for the newly created session. */ static createSession(executor, capabilities, onQuit = undefined) { let cmd = new command.Command(command.Name.NEW_SESSION) // For W3C remote ends. cmd.setParameter('capabilities', { firstMatch: [{}], alwaysMatch: filterNonW3CCaps(capabilities), }) let session = executeCommand(executor, cmd) if (typeof onQuit === 'function') { session = session.catch((err) => { return Promise.resolve(onQuit.call(void 0)).then((_) => { throw err }) }) } return new this(session, executor, onQuit) } /** @override */ async execute(command) { command.setParameter('sessionId', this.session_) let parameters = await toWireValue(command.getParameters()) command.setParameters(parameters) let value = await this.executor_.execute(command) return fromWireValue(this, value) } /** @override */ setFileDetector(detector) { this.fileDetector_ = detector } /** @override */ getExecutor() { return this.executor_ } /** @override */ getSession() { return this.session_ } /** @override */ getCapabilities() { return this.session_.then((s) => s.getCapabilities()) } /** @override */ quit() { let result = this.execute(new command.Command(command.Name.QUIT)) // Delete our session ID when the quit command finishes; this will allow us // to throw an error when attempting to use a driver post-quit. return promise.finally(result, () => { this.session_ = Promise.reject( new error.NoSuchSessionError( 'This driver instance does not have a valid session ID ' + '(did you call WebDriver.quit()?) and may no longer be used.', ), ) // Only want the session rejection to bubble if accessed. this.session_.catch(function () {}) if (this.onQuit_) { return this.onQuit_.call(void 0) } // Close the websocket connection on quit // If the websocket connection is not closed, // and we are running CDP sessions against the Selenium Grid, // the node process never exits since the websocket connection is open until the Grid is shutdown. if (this._cdpWsConnection !== undefined) { this._cdpWsConnection.close() } // Close the BiDi websocket connection if (this._bidiConnection !== undefined) { this._bidiConnection.close() } }) } /** @override */ actions(options) { return new input.Actions(this, options || undefined) } /** @override */ executeScript(script, ...args) { if (typeof script === 'function') { script = 'return (' + script + ').apply(null, arguments);' } if (script && script instanceof PinnedScript) { return this.execute( new command.Command(command.Name.EXECUTE_SCRIPT) .setParameter('script', script.executionScript()) .setParameter('args', args), ) } return this.execute( new command.Command(command.Name.EXECUTE_SCRIPT).setParameter('script', script).setParameter('args', args), ) } /** @override */ executeAsyncScript(script, ...args) { if (typeof script === 'function') { script = 'return (' + script + ').apply(null, arguments);' } if (script && script instanceof PinnedScript) { return this.execute( new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT) .setParameter('script', script.executionScript()) .setParameter('args', args), ) } return this.execute( new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).setParameter('script', script).setParameter('args', args), ) } /** @override */ wait(condition, timeout = 0, message = undefined, pollTimeout = 200) { if (typeof timeout !== 'number' || timeout < 0) { throw TypeError('timeout must be a number >= 0: ' + timeout) } if (typeof pollTimeout !== 'number' || pollTimeout < 0) { throw TypeError('pollTimeout must be a number >= 0: ' + pollTimeout) } if (promise.isPromise(condition)) { return new Promise((resolve, reject) => { if (!timeout) { resolve(condition) return } let start = Date.now() let timer = setTimeout(function () { timer = null try { let timeoutMessage = resolveWaitMessage(message) reject( new error.TimeoutError( `${timeoutMessage}Timed out waiting for promise to resolve after ${Date.now() - start}ms`, ), ) } catch (ex) { reject( new error.TimeoutError( `${ex.message}\nTimed out waiting for promise to resolve after ${Date.now() - start}ms`, ), ) } }, timeout) const clearTimer = () => timer && clearTimeout(timer) /** @type {!IThenable} */ condition.then( function (value) { clearTimer() resolve(value) }, function (error) { clearTimer() reject(error) }, ) }) } let fn = /** @type {!Function} */ (condition) if (condition instanceof Condition) { message = message || condition.description() fn = condition.fn } if (typeof fn !== 'function') { throw TypeError('Wait condition must be a promise-like object, function, or a ' + 'Condition object') } const driver = this function evaluateCondition() { return new Promise((resolve, reject) => { try { resolve(fn(driver)) } catch (ex) { reject(ex) } }) } let result = new Promise((resolve, reject) => { const startTime = Date.now() const pollCondition = async () => { evaluateCondition().then(function (value) { const elapsed = Date.now() - startTime if (value) { resolve(value) } else if (timeout && elapsed >= timeout) { try { let timeoutMessage = resolveWaitMessage(message) reject(new error.TimeoutError(`${timeoutMessage}Wait timed out after ${elapsed}ms`)) } catch (ex) { reject(new error.TimeoutError(`${ex.message}\nWait timed out after ${elapsed}ms`)) } } else { setTimeout(pollCondition, pollTimeout) } }, reject) } pollCondition() }) if (condition instanceof WebElementCondition) { result = new WebElementPromise( this, result.then(function (value) { if (!(value instanceof WebElement)) { throw TypeError( 'WebElementCondition did not resolve to a WebElement: ' + Object.prototype.toString.call(value), ) } return value }), ) } return result } /** @override */ sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) } /** @override */ getWindowHandle() { return this.execute(new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE)) } /** @override */ getAllWindowHandles() { return this.execute(new command.Command(command.Name.GET_WINDOW_HANDLES)) } /** @override */ getPageSource() { return this.execute(new command.Command(command.Name.GET_PAGE_SOURCE)) } /** @override */ close() { return this.execute(new command.Command(command.Name.CLOSE)) } /** @override */ get(url) { return this.navigate().to(url) } /** @override */ getCurrentUrl() { return this.execute(new command.Command(command.Name.GET_CURRENT_URL)) } /** @override */ getTitle() { return this.execute(new command.Command(command.Name.GET_TITLE)) } /** @override */ findElement(locator) { let id let cmd = null if (locator instanceof RelativeBy) { cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall()) } else { locator = by.checkedLocator(locator) } if (typeof locator === 'function') { id = this.findElementInternal_(locator, this) return new WebElementPromise(this, id) } else if (cmd === null) { cmd = new command.Command(command.Name.FIND_ELEMENT) .setParameter('using', locator.using) .setParameter('value', locator.value) } id = this.execute(cmd) if (locator instanceof RelativeBy) { return this.normalize_(id) } else { return new WebElementPromise(this, id) } } /** * @param {!Function} webElementPromise The webElement in unresolved state * @return {!Promise<!WebElement>} First single WebElement from array of resolved promises */ async normalize_(webElementPromise) { let result = await webElementPromise if (result.length === 0) { throw new NoSuchElementError('Cannot locate an element with provided parameters') } else { return result[0] } } /** * @param {!Function} locatorFn The locator function to use. * @param {!(WebDriver|WebElement)} context The search context. * @return {!Promise<!WebElement>} A promise that will resolve to a list of * WebElements. * @private */ async findElementInternal_(locatorFn, context) { let result = await locatorFn(context) if (Array.isArray(result)) { result = result[0] } if (!(result instanceof WebElement)) { throw new TypeError('Custom locator did not return a WebElement') } return result } /** @override */ async findElements(locator) { let cmd = null if (locator instanceof RelativeBy) { cmd = new command.Command(command.Name.FIND_ELEMENTS_RELATIVE).setParameter('args', locator.marshall()) } else { locator = by.checkedLocator(locator) } if (typeof locator === 'function') { return this.findElementsInternal_(locator, this) } else if (cmd === null) { cmd = new command.Command(command.Name.FIND_ELEMENTS) .setParameter('using', locator.using) .setParameter('value', locator.value) } try { let res = await this.execute(cmd) return Array.isArray(res) ? res : [] } catch (ex) { if (ex instanceof error.NoSuchElementError) { return [] } throw ex } } /** * @param {!Function} locatorFn The locator function to use. * @param {!(WebDriver|WebElement)} context The search context. * @return {!Promise<!Array<!WebElement>>} A promise that will resolve to an * array of WebElements. * @private */ async findElementsInternal_(locatorFn, context) { const result = await locatorFn(context) if (result instanceof WebElement) { return [result] } if (!Array.isArray(result)) { return [] } return result.filter(function (item) { return item instanceof WebElement }) } /** @override */ takeScreenshot() { return this.execute(new command.Command(command.Name.SCREENSHOT)) } setDelayEnabled(enabled) { return this.execute(new command.Command(command.Name.SET_DELAY_ENABLED).setParameter('enabled', enabled)) } resetCooldown() { return this.execute(new command.Command(command.Name.RESET_COOLDOWN)) } getFederalCredentialManagementDialog() { return new Dialog(this) } /** @override */ manage() { return new Options(this) } /** @override */ navigate() { return new Navigation(this) } /** @override */ switchTo() { return new TargetLocator(this) } script() { // The Script calls the LogInspector which maintains state of the callbacks. // Returning a new instance of the same driver will not work while removing callbacks. if (this.#script === undefined) { this.#script = new Script(this) } return this.#script } network() { // The Network maintains state of the callbacks. // Returning a new instance of the same driver will not work while removing callbacks. if (this.#network === undefined) { this.#network = new Network(this) } return this.#network } validatePrintPageParams(keys, object) { let page = {} let margin = {} let data Object.keys(keys).forEach(function (key) { data = keys[key] let obj = { orientation: function () { object.orientation = data }, scale: function () { object.scale = data }, background: function () { object.background = data }, width: function () { page.width = data object.page = page }, height: function () { page.height = data object.page = page }, top: function () { margin.top = data object.margin = margin }, left: function () { margin.left = data object.margin = margin }, bottom: function () { margin.bottom = data object.margin = margin }, right: function () { margin.right = data object.margin = margin }, shrinkToFit: function () { object.shrinkToFit = data }, pageRanges: function () { object.pageRanges = data }, } if (!Object.prototype.hasOwnProperty.call(obj, key)) { throw new error.InvalidArgumentError(`Invalid Argument '${key}'`) } else { obj[key]() } }) return object } /** @override */ printPage(options = {}) { let keys = options let params = {} let resultObj let self = this resultObj = self.validatePrintPageParams(keys, params) return this.execute(new command.Command(command.Name.PRINT_PAGE).setParameters(resultObj)) } /** * Creates a new WebSocket connection. * @return {!Promise<resolved>} A new CDP instance. */ async createCDPConnection(target) { let debuggerUrl = null const caps = await this.getCapabilities() if (caps['map_'].get('browserName') === 'firefox') { throw new Error('CDP support for Firefox is removed. Please switch to WebDriver BiDi.') } if (process.env.SELENIUM_REMOTE_URL) { const host = new URL(process.env.SELENIUM_REMOTE_URL).host const sessionId = await this.getSession().then((session) => session.getId()) debuggerUrl = `ws://${host}/session/${sessionId}/se/cdp` } else { const seCdp = caps['map_'].get('se:cdp') const vendorInfo = caps['map_'].get('goog:chromeOptions') || caps['map_'].get('ms:edgeOptions') || new Map() debuggerUrl = seCdp || vendorInfo['debuggerAddress'] || vendorInfo } this._wsUrl = await this.getWsUrl(debuggerUrl, target, caps) return new Promise((resolve, reject) => { try { this._cdpWsConnection = new WebSocket(this._wsUrl.replace('localhost', '127.0.0.1')) this._cdpConnection = new cdp.CdpConnection(this._cdpWsConnection) } catch (err) { reject(err) return } this._cdpWsConnection.on('open', async () => { await this.getCdpTargets() }) this._cdpWsConnection.on('message', async (message) => { const params = JSON.parse(message) if (params.result) { if (params.result.targetInfos) { const targets = params.result.targetInfos const page = targets.find((info) => info.type === 'page') if (page) { this.targetID = page.targetId this._cdpConnection.execute('Target.attachToTarget', { targetId: this.targetID, flatten: true }, null) } else { reject('Unable to find Page target.') } } if (params.result.sessionId) { this.sessionId = params.result.sessionId this._cdpConnection.sessionId = this.sessionId resolve(this._cdpConnection) } } }) this._cdpWsConnection.on('error', (error) => { reject(error) }) }) } async getCdpTargets() { this._cdpConnection.execute('Target.getTargets') } /** * Initiates bidi connection using 'webSocketUrl' * @returns {BIDI} */ async getBidi() { if (this._bidiConnection === undefined) { const caps = await this.getCapabilities() let WebSocketUrl = caps['map_'].get('webSocketUrl') this._bidiConnection = new BIDI(WebSocketUrl.replace('localhost', '127.0.0.1')) } return this._bidiConnection } /** * Retrieves 'webSocketDebuggerUrl' by sending a http request using debugger address * @param {string} debuggerAddress * @param target * @param caps * @return {string} Returns parsed webSocketDebuggerUrl obtained from the http request */ async getWsUrl(debuggerAddress, target, caps) { if (target && cdpTargets.indexOf(target.toLowerCase()) === -1) { throw new error.InvalidArgumentError('invalid target value') } if (debuggerAddress.match(/\/se\/cdp/)) { return debuggerAddress } let path if (target === 'page' && caps['map_'].get('browserName') !== 'firefox') { path = '/json' } else if (target === 'page' && caps['map_'].get('browserName') === 'firefox') { path = '/json/list' } else { path = '/json/version' } let request = new http.Request('GET', path) let client = new http.HttpClient('http://' + debuggerAddress) let response = await client.send(request) if (target.toLowerCase() === 'page') { return JSON.parse(response.body)[0]['webSocketDebuggerUrl'] } else { return JSON.parse(response.body)['webSocketDebuggerUrl'] } } /** * Sets a listener for Fetch.authRequired event from CDP * If event is triggered, it enters username and password * and allows the test to move forward * @param {string} username * @param {string} password * @param connection CDP Connection */ async register(username, password, connection) { this._cdpWsConnection.on('message', (message) => { const params = JSON.parse(message) if (params.method === 'Fetch.authRequired') { const requestParams = params['params'] connection.execute('Fetch.continueWithAuth', { requestId: requestParams['requestId'], authChallengeResponse: { response: 'ProvideCredentials', username: username, password: password, }, }) } else if (params.method === 'Fetch.requestPaused') { const requestPausedParams = params['params'] connection.execute('Fetch.continueRequest', { requestId: requestPausedParams['requestId'], }) } }) await connection.execute( 'Fetch.enable', { handleAuthRequests: true, }, null, ) await connection.execute( 'Network.setCacheDisabled', { cacheDisabled: true, }, null, ) } /** * Handle Network interception requests * @param connection WebSocket connection to the browser * @param httpResponse Object representing what we are intercepting * as well as what should be returned. * @param callback callback called when we intercept requests. */ async onIntercept(connection, httpResponse, callback) { this._cdpWsConnection.on('message', (message) => { const params = JSON.parse(message) if (params.method === 'Fetch.requestPaused') { const requestPausedParams = params['params'] if (requestPausedParams.request.url == httpResponse.urlToIntercept) { connection.execute('Fetch.fulfillRequest', { requestId: requestPausedParams['requestId'], responseCode: httpResponse.status, responseHeaders: httpResponse.headers, body: httpResponse.body, }) callback() } else { connection.execute('Fetch.continueRequest', { requestId: requestPausedParams['requestId'], }) } } }) await connection.execute('Fetch.enable', {}, null) await connection.execute( 'Network.setCacheDisabled', { cacheDisabled: true, }, null, ) } /** * * @param connection * @param callback * @returns {Promise<void>} */ async onLogEvent(connection, callback) { this._cdpWsConnection.on('message', (message) => { const params = JSON.parse(message) if (params.method === 'Runtime.consoleAPICalled') { const consoleEventParams = params['params'] let event = { type: consoleEventParams['type'], timestamp: new Date(consoleEventParams['timestamp']), args: consoleEventParams['args'], } callback(event) } if (params.method === 'Log.entryAdded') { const logEventParams = params['params'] const logEntry = logEventParams['entry'] let event = { level: logEntry['level'], timestamp: new Date(logEntry['timestamp']), message: logEntry['text'], } callback(event) } }) await connection.execute('Runtime.enable', {}, null) } /** * * @param connection * @param callback * @returns {Promise<void>} */ async onLogException(connection, callback) { await connection.execute('Runtime.enable', {}, null) this._cdpWsConnection.on('message', (message) => { const params = JSON.parse(message) if (params.method === 'Runtime.exceptionThrown') { const exceptionEventParams = params['params'] let event = { exceptionDetails: exceptionEventParams['exceptionDetails'], timestamp: new Date(exceptionEventParams['timestamp']), } callback(event) } }) } /** * @param connection * @param callback * @returns {Promise<void>} */ async logMutationEvents(connection, callback) { await connection.execute('Runtime.enable', {}, null) await connection.execute('Page.enable', {}, null) await connection.execute( 'Runtime.addBinding', { name: '__webdriver_attribute', }, null, ) let mutationListener = '' try { // Depending on what is running the code it could appear in 2 different places which is why we try // here and then the other location mutationListener = fs .readFileSync('./javascript/selenium-webdriver/lib/atoms/mutation-listener.js', 'utf-8') .toString() } catch { mutationListener = fs.readFileSync(path.resolve(__dirname, './atoms/mutation-listener.js'), 'utf-8').toString() } this.executeScript(mutationListener) await connection.execute( 'Page.addScriptToEvaluateOnNewDocument', { source: mutationListener, }, null, ) this._cdpWsConnection.on('message', async (message) => { const params = JSON.parse(message) if (params.method === 'Runtime.bindingCalled') { let payload = JSON.parse(params['params']['payload']) let elements = await this.findElements({ css: '*[data-__webdriver_id=' + by.escapeCss(payload['target']) + ']', }) if (elements.length === 0) { return } let event = { element: elements[0], attribute_name: payload['name'], current_value: payload['value'], old_value: payload['oldValue'], } callback(event) } }) } async pinScript(script) { let pinnedScript = new PinnedScript(script) let connection if (Object.is(this._cdpConnection, undefined)) { connection = await this.createCDPConnection('page') } else { connection = this._cdpConnection } await connection.execute('Page.enable', {}, null) await connection.execute( 'Runtime.evaluate', { expression: pinnedScript.creationScript(), }, null, ) let result = await connection.send('Page.addScriptToEvaluateOnNewDocument', { source: pinnedScript.creationScript(), }) pinnedScript.scriptId = result['result']['identifier'] this.pinnedScripts_[pinnedScript.handle] = pinnedSc