Path: blob/trunk/javascript/selenium-webdriver/index.js
2884 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617/**18* @fileoverview The main user facing module. Exports WebDriver's primary19* public API and provides convenience assessors to certain sub-modules.20*/2122'use strict'2324const _http = require('./http')25const by = require('./lib/by')26const capabilities = require('./lib/capabilities')27const chrome = require('./chrome')28const edge = require('./edge')29const error = require('./lib/error')30const firefox = require('./firefox')31const ie = require('./ie')32const input = require('./lib/input')33const logging = require('./lib/logging')34const promise = require('./lib/promise')35const remote = require('./remote')36const safari = require('./safari')37const session = require('./lib/session')38const until = require('./lib/until')39const webdriver = require('./lib/webdriver')40const select = require('./lib/select')41const LogInspector = require('./bidi/logInspector')42const BrowsingContext = require('./bidi/browsingContext')43const BrowsingContextInspector = require('./bidi/browsingContextInspector')44const ScriptManager = require('./bidi/scriptManager')45const NetworkInspector = require('./bidi/networkInspector')46const version = require('./package.json').version4748const Browser = capabilities.Browser49const Capabilities = capabilities.Capabilities50const Capability = capabilities.Capability51const WebDriver = webdriver.WebDriver5253let seleniumServer5455/**56* Starts an instance of the Selenium server if not yet running.57* @param {string} jar Path to the server jar to use.58* @return {!Promise<string>} A promise for the server's59* address once started.60*/61function startSeleniumServer(jar) {62if (!seleniumServer) {63seleniumServer = new remote.SeleniumServer(jar)64}65return seleniumServer.start()66}6768/**69* {@linkplain webdriver.WebDriver#setFileDetector WebDriver's setFileDetector}70* method uses a non-standard command to transfer files from the local client71* to the remote end hosting the browser. Many of the WebDriver sub-types, like72* the {@link chrome.Driver} and {@link firefox.Driver}, do not support this73* command. Thus, these classes override the `setFileDetector` to no-op.74*75* This function uses a mixin to re-enable `setFileDetector` by calling the76* original method on the WebDriver prototype directly. This is used only when77* the builder creates a Chrome or Firefox instance that communicates with a78* remote end (and thus, support for remote file detectors is unknown).79*80* @param {function(new: webdriver.WebDriver, ...?)} ctor81* @return {function(new: webdriver.WebDriver, ...?)}82*/83function ensureFileDetectorsAreEnabled(ctor) {84return class extends ctor {85/** @param {input.FileDetector} detector */86setFileDetector(detector) {87webdriver.WebDriver.prototype.setFileDetector.call(this, detector)88}89}90}9192/**93* A thenable wrapper around a {@linkplain webdriver.IWebDriver IWebDriver}94* instance that allows commands to be issued directly instead of having to95* repeatedly call `then`:96*97* let driver = new Builder().build();98* driver.then(d => d.get(url)); // You can do this...99* driver.get(url); // ...or this100*101* If the driver instance fails to resolve (e.g. the session cannot be created),102* every issued command will fail.103*104* @extends {webdriver.IWebDriver}105* @extends {IThenable<!webdriver.IWebDriver>}106* @interface107*/108class ThenableWebDriver {109/** @param {...?} args */110static createSession(...args) {} // eslint-disable-line111}112113/**114* @const {!Map<function(new: WebDriver, !IThenable<!Session>, ...?),115* function(new: ThenableWebDriver, !IThenable<!Session>, ...?)>}116*/117const THENABLE_DRIVERS = new Map()118119/**120* @param {function(new: WebDriver, !IThenable<!Session>, ...?)} ctor121* @param {...?} args122* @return {!ThenableWebDriver}123*/124function createDriver(ctor, ...args) {125let thenableWebDriverProxy = THENABLE_DRIVERS.get(ctor)126if (!thenableWebDriverProxy) {127/**128* @extends {WebDriver} // Needed since `ctor` is dynamically typed.129* @implements {ThenableWebDriver}130*/131thenableWebDriverProxy = class extends ctor {132/**133* @param {!IThenable<!Session>} session134* @param {...?} rest135*/136constructor(session, ...rest) {137super(session, ...rest)138139const pd = this.getSession().then((session) => {140return new ctor(session, ...rest)141})142143/** @override */144this.then = pd.then.bind(pd)145146/** @override */147this.catch = pd.catch.bind(pd)148}149}150THENABLE_DRIVERS.set(ctor, thenableWebDriverProxy)151}152return thenableWebDriverProxy.createSession(...args)153}154155/**156* Creates new {@link webdriver.WebDriver WebDriver} instances. The environment157* variables listed below may be used to override a builder's configuration,158* allowing quick runtime changes.159*160* - {@code SELENIUM_BROWSER}: defines the target browser in the form161* {@code browser[:version][:platform]}.162*163* - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder164* instances. This environment variable should be set to a fully qualified165* URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This166* option always takes precedence over {@code SELENIUM_SERVER_JAR}.167*168* - {@code SELENIUM_SERVER_JAR}: defines the path to the169* <a href="https://www.selenium.dev/downloads/">170* standalone Selenium server</a> jar to use. The server will be started the171* first time a WebDriver instance and be killed when the process exits.172*173* Suppose you had mytest.js that created WebDriver with174*175* var driver = new webdriver.Builder()176* .forBrowser('chrome')177* .build();178*179* This test could be made to use Firefox on the local machine by running with180* `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to181* target Google Chrome on a remote machine, you can simply set the182* `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables:183*184* SELENIUM_BROWSER=chrome:36:LINUX \185* SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \186* node mytest.js187*188* You could also use a local copy of the standalone Selenium server:189*190* SELENIUM_BROWSER=chrome:36:LINUX \191* SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \192* node mytest.js193*/194class Builder {195constructor() {196/** @private @const */197this.log_ = logging.getLogger(`${logging.Type.DRIVER}.Builder`)198199/** @private {string} */200this.url_ = ''201202/** @private {?string} */203this.proxy_ = null204205/** @private {!Capabilities} */206this.capabilities_ = new Capabilities()207208/** @private {chrome.Options} */209this.chromeOptions_ = null210211/** @private {chrome.ServiceBuilder} */212this.chromeService_ = null213214/** @private {firefox.Options} */215this.firefoxOptions_ = null216217/** @private {firefox.ServiceBuilder} */218this.firefoxService_ = null219220/** @private {ie.Options} */221this.ieOptions_ = null222223/** @private {ie.ServiceBuilder} */224this.ieService_ = null225226/** @private {safari.Options} */227this.safariOptions_ = null228229/** @private {edge.Options} */230this.edgeOptions_ = null231232/** @private {remote.DriverService.Builder} */233this.edgeService_ = null234235/** @private {boolean} */236this.ignoreEnv_ = false237238/** @private {http.Agent} */239this.agent_ = null240}241242/**243* Configures this builder to ignore any environment variable overrides and to244* only use the configuration specified through this instance's API.245*246* @return {!Builder} A self reference.247*/248disableEnvironmentOverrides() {249this.ignoreEnv_ = true250return this251}252253/**254* Sets the URL of a remote WebDriver server to use. Once a remote URL has255* been specified, the builder direct all new clients to that server. If this256* method is never called, the Builder will attempt to create all clients257* locally.258*259* As an alternative to this method, you may also set the260* `SELENIUM_REMOTE_URL` environment variable.261*262* @param {string} url The URL of a remote server to use.263* @return {!Builder} A self reference.264*/265usingServer(url) {266this.url_ = url267return this268}269270/**271* @return {string} The URL of the WebDriver server this instance is272* configured to use.273*/274getServerUrl() {275return this.url_276}277278/**279* Sets the URL of the proxy to use for the WebDriver's HTTP connections.280* If this method is never called, the Builder will create a connection281* without a proxy.282*283* @param {string} proxy The URL of a proxy to use.284* @return {!Builder} A self reference.285*/286usingWebDriverProxy(proxy) {287this.proxy_ = proxy288return this289}290291/**292* @return {?string} The URL of the proxy server to use for the WebDriver's293* HTTP connections, or `null` if not set.294*/295getWebDriverProxy() {296return this.proxy_297}298299/**300* Sets the http agent to use for each request.301* If this method is not called, the Builder will use http.globalAgent by default.302*303* @param {http.Agent} agent The agent to use for each request.304* @return {!Builder} A self reference.305*/306usingHttpAgent(agent) {307this.agent_ = agent308return this309}310311/**312* @return {http.Agent} The http agent used for each request313*/314getHttpAgent() {315return this.agent_316}317318/**319* Recommended way is to use set*Options where * is the browser(eg setChromeOptions)320*321* Sets the desired capabilities when requesting a new session. This will322* overwrite any previously set capabilities.323* @param {!(Object|Capabilities)} capabilities The desired capabilities for324* a new session.325* @return {!Builder} A self reference.326*/327withCapabilities(capabilities) {328this.capabilities_ = new Capabilities(capabilities)329return this330}331332/**333* Returns the base set of capabilities this instance is currently configured334* to use.335* @return {!Capabilities} The current capabilities for this builder.336*/337getCapabilities() {338return this.capabilities_339}340341/**342* Sets the desired capability when requesting a new session.343* If there is already a capability named key, its value will be overwritten with value.344* This is a convenience wrapper around builder.getCapabilities().set(key, value) to support Builder method chaining.345* @param {string} key The capability key.346* @param {*} value The capability value.347* @return {!Builder} A self reference.348*/349setCapability(key, value) {350this.capabilities_.set(key, value)351return this352}353354/**355* Configures the target browser for clients created by this instance.356* Any calls to {@link #withCapabilities} after this function will357* overwrite these settings.358*359* You may also define the target browser using the {@code SELENIUM_BROWSER}360* environment variable. If set, this environment variable should be of the361* form `browser[:[version][:platform]]`.362*363* @param {(string|!Browser)} name The name of the target browser;364* common defaults are available on the {@link webdriver.Browser} enum.365* @param {string=} opt_version A desired version; may be omitted if any366* version should be used.367* @param {(string|!capabilities.Platform)=} opt_platform368* The desired platform; may be omitted if any platform may be used.369* @return {!Builder} A self reference.370*/371forBrowser(name, opt_version, opt_platform) {372this.capabilities_.setBrowserName(name)373if (opt_version) {374this.capabilities_.setBrowserVersion(opt_version)375}376if (opt_platform) {377this.capabilities_.setPlatform(opt_platform)378}379return this380}381382/**383* Sets the proxy configuration for the target browser.384* Any calls to {@link #withCapabilities} after this function will385* overwrite these settings.386*387* @param {!./lib/proxy.Config} config The configuration to use.388* @return {!Builder} A self reference.389*/390setProxy(config) {391this.capabilities_.setProxy(config)392return this393}394395/**396* Sets the logging preferences for the created session. Preferences may be397* changed by repeated calls, or by calling {@link #withCapabilities}.398* @param {!(./lib/logging.Preferences|Object<string, string>)} prefs The399* desired logging preferences.400* @return {!Builder} A self reference.401*/402setLoggingPrefs(prefs) {403this.capabilities_.setLoggingPrefs(prefs)404return this405}406407/**408* Sets the default action to take with an unexpected alert before returning409* an error.410*411* @param {?capabilities.UserPromptHandler} behavior The desired behavior.412* @return {!Builder} A self reference.413* @see capabilities.Capabilities#setAlertBehavior414*/415setAlertBehavior(behavior) {416this.capabilities_.setAlertBehavior(behavior)417return this418}419420/**421* Sets Chrome specific {@linkplain chrome.Options options} for drivers422* created by this builder. Any logging or proxy settings defined on the given423* options will take precedence over those set through424* {@link #setLoggingPrefs} and {@link #setProxy}, respectively.425*426* @param {!chrome.Options} options The ChromeDriver options to use.427* @return {!Builder} A self reference.428*/429setChromeOptions(options) {430this.chromeOptions_ = options431return this432}433434/**435* @return {chrome.Options} the Chrome specific options currently configured436* for this builder.437*/438getChromeOptions() {439return this.chromeOptions_440}441442/**443* Sets the service builder to use for managing the chromedriver child process444* when creating new Chrome sessions.445*446* @param {chrome.ServiceBuilder} service the service to use.447* @return {!Builder} A self reference.448*/449setChromeService(service) {450if (service && !(service instanceof chrome.ServiceBuilder)) {451throw TypeError('not a chrome.ServiceBuilder object')452}453this.chromeService_ = service454return this455}456457/**458* Sets Firefox specific {@linkplain firefox.Options options} for drivers459* created by this builder. Any logging or proxy settings defined on the given460* options will take precedence over those set through461* {@link #setLoggingPrefs} and {@link #setProxy}, respectively.462*463* @param {!firefox.Options} options The FirefoxDriver options to use.464* @return {!Builder} A self reference.465*/466setFirefoxOptions(options) {467this.firefoxOptions_ = options468return this469}470471/**472* @return {firefox.Options} the Firefox specific options currently configured473* for this instance.474*/475getFirefoxOptions() {476return this.firefoxOptions_477}478479/**480* Sets the {@link firefox.ServiceBuilder} to use to manage the geckodriver481* child process when creating Firefox sessions locally.482*483* @param {firefox.ServiceBuilder} service the service to use.484* @return {!Builder} a self reference.485*/486setFirefoxService(service) {487if (service && !(service instanceof firefox.ServiceBuilder)) {488throw TypeError('not a firefox.ServiceBuilder object')489}490this.firefoxService_ = service491return this492}493494/**495* Set Internet Explorer specific {@linkplain ie.Options options} for drivers496* created by this builder. Any proxy settings defined on the given options497* will take precedence over those set through {@link #setProxy}.498*499* @param {!ie.Options} options The IEDriver options to use.500* @return {!Builder} A self reference.501*/502setIeOptions(options) {503this.ieOptions_ = options504return this505}506507/**508* Sets the {@link ie.ServiceBuilder} to use to manage the geckodriver509* child process when creating IE sessions locally.510*511* @param {ie.ServiceBuilder} service the service to use.512* @return {!Builder} a self reference.513*/514setIeService(service) {515this.ieService_ = service516return this517}518519/**520* Set {@linkplain edge.Options options} specific to Microsoft's Edge browser521* for drivers created by this builder. Any proxy settings defined on the522* given options will take precedence over those set through523* {@link #setProxy}.524*525* @param {!edge.Options} options The MicrosoftEdgeDriver options to use.526* @return {!Builder} A self reference.527*/528setEdgeOptions(options) {529this.edgeOptions_ = options530return this531}532533/**534* Sets the {@link edge.ServiceBuilder} to use to manage the535* MicrosoftEdgeDriver child process when creating sessions locally.536*537* @param {edge.ServiceBuilder} service the service to use.538* @return {!Builder} a self reference.539*/540setEdgeService(service) {541if (service && !(service instanceof edge.ServiceBuilder)) {542throw TypeError('not a edge.ServiceBuilder object')543}544this.edgeService_ = service545return this546}547548/**549* Sets Safari specific {@linkplain safari.Options options} for drivers550* created by this builder. Any logging settings defined on the given options551* will take precedence over those set through {@link #setLoggingPrefs}.552*553* @param {!safari.Options} options The Safari options to use.554* @return {!Builder} A self reference.555*/556setSafariOptions(options) {557this.safariOptions_ = options558return this559}560561/**562* @return {safari.Options} the Safari specific options currently configured563* for this instance.564*/565getSafariOptions() {566return this.safariOptions_567}568569/**570* Creates a new WebDriver client based on this builder's current571* configuration.572*573* This method will return a {@linkplain ThenableWebDriver} instance, allowing574* users to issue commands directly without calling `then()`. The returned575* thenable wraps a promise that will resolve to a concrete576* {@linkplain webdriver.WebDriver WebDriver} instance. The promise will be577* rejected if the remote end fails to create a new session.578*579* @return {!ThenableWebDriver} A new WebDriver instance.580* @throws {Error} If the current configuration is invalid.581*/582build() {583// Create a copy for any changes we may need to make based on the current584// environment.585const capabilities = new Capabilities(this.capabilities_)586587let browser588if (!this.ignoreEnv_ && process.env.SELENIUM_BROWSER) {589this.log_.fine(`SELENIUM_BROWSER=${process.env.SELENIUM_BROWSER}`)590browser = process.env.SELENIUM_BROWSER.split(/:/, 3)591capabilities.setBrowserName(browser[0])592593browser[1] && capabilities.setBrowserVersion(browser[1])594browser[2] && capabilities.setPlatform(browser[2])595}596597browser = capabilities.get(Capability.BROWSER_NAME)598599/**600* If browser is not defined in forBrowser, check if browserOptions are defined to pick the browserName601*/602if (!browser) {603const options =604this.chromeOptions_ || this.firefoxOptions_ || this.ieOptions_ || this.safariOptions_ || this.edgeOptions_605if (options) {606browser = options['map_'].get(Capability.BROWSER_NAME)607}608}609610if (typeof browser !== 'string') {611throw TypeError(612`Target browser must be a string, but is <${typeof browser}>;` + ' did you forget to call forBrowser()?',613)614}615616if (browser === 'ie') {617browser = Browser.INTERNET_EXPLORER618}619620// Apply browser specific overrides.621if (browser === Browser.CHROME && this.chromeOptions_) {622capabilities.merge(this.chromeOptions_)623} else if (browser === Browser.FIREFOX && this.firefoxOptions_) {624capabilities.merge(this.firefoxOptions_)625} else if (browser === Browser.INTERNET_EXPLORER && this.ieOptions_) {626capabilities.merge(this.ieOptions_)627} else if (browser === Browser.SAFARI && this.safariOptions_) {628capabilities.merge(this.safariOptions_)629} else if (browser === Browser.EDGE && this.edgeOptions_) {630capabilities.merge(this.edgeOptions_)631}632633checkOptions(capabilities, 'chromeOptions', chrome.Options, 'setChromeOptions')634checkOptions(capabilities, 'moz:firefoxOptions', firefox.Options, 'setFirefoxOptions')635checkOptions(capabilities, 'safari.options', safari.Options, 'setSafariOptions')636637// Check for a remote browser.638let url = this.url_639if (!this.ignoreEnv_) {640if (process.env.SELENIUM_REMOTE_URL) {641this.log_.fine(`SELENIUM_REMOTE_URL=${process.env.SELENIUM_REMOTE_URL}`)642url = process.env.SELENIUM_REMOTE_URL643} else if (process.env.SELENIUM_SERVER_JAR) {644this.log_.fine(`SELENIUM_SERVER_JAR=${process.env.SELENIUM_SERVER_JAR}`)645url = startSeleniumServer(process.env.SELENIUM_SERVER_JAR)646}647}648649if (url) {650this.log_.fine('Creating session on remote server')651let client = Promise.resolve(url).then((url) => new _http.HttpClient(url, this.agent_, this.proxy_))652let executor = new _http.Executor(client)653654if (browser === Browser.CHROME) {655const driver = ensureFileDetectorsAreEnabled(chrome.Driver)656return createDriver(driver, capabilities, executor)657}658659if (browser === Browser.FIREFOX) {660const driver = ensureFileDetectorsAreEnabled(firefox.Driver)661return createDriver(driver, capabilities, executor)662}663return createDriver(WebDriver, executor, capabilities)664}665666// Check for a native browser.667switch (browser) {668case Browser.CHROME: {669let service = null670if (this.chromeService_) {671service = this.chromeService_.build()672}673return createDriver(chrome.Driver, capabilities, service)674}675676case Browser.FIREFOX: {677let service = null678if (this.firefoxService_) {679service = this.firefoxService_.build()680}681return createDriver(firefox.Driver, capabilities, service)682}683684case Browser.INTERNET_EXPLORER: {685let service = null686if (this.ieService_) {687service = this.ieService_.build()688}689return createDriver(ie.Driver, capabilities, service)690}691692case Browser.EDGE: {693let service = null694if (this.edgeService_) {695service = this.edgeService_.build()696}697return createDriver(edge.Driver, capabilities, service)698}699700case Browser.SAFARI:701return createDriver(safari.Driver, capabilities)702703default:704throw new Error('Do not know how to build driver: ' + browser + '; did you forget to call usingServer(url)?')705}706}707}708709/**710* In the 3.x releases, the various browser option classes711* (e.g. firefox.Options) had to be manually set as an option using the712* Capabilities class:713*714* let ffo = new firefox.Options();715* // Configure firefox options...716*717* let caps = new Capabilities();718* caps.set('moz:firefoxOptions', ffo);719*720* let driver = new Builder()721* .withCapabilities(caps)722* .build();723*724* The options are now subclasses of Capabilities and can be used directly. A725* direct translation of the above is:726*727* let ffo = new firefox.Options();728* // Configure firefox options...729*730* let driver = new Builder()731* .withCapabilities(ffo)732* .build();733*734* You can also set the options for various browsers at once and let the builder735* choose the correct set at runtime (see Builder docs above):736*737* let ffo = new firefox.Options();738* // Configure ...739*740* let co = new chrome.Options();741* // Configure ...742*743* let driver = new Builder()744* .setChromeOptions(co)745* .setFirefoxOptions(ffo)746* .build();747*748* @param {!Capabilities} caps749* @param {string} key750* @param {function(new: Capabilities)} optionType751* @param {string} setMethod752* @throws {error.InvalidArgumentError}753*/754function checkOptions(caps, key, optionType, setMethod) {755let val = caps.get(key)756if (val instanceof optionType) {757throw new error.InvalidArgumentError(758'Options class extends Capabilities and should not be set as key ' +759`"${key}"; set browser-specific options with ` +760`Builder.${setMethod}(). For more information, see the ` +761'documentation attached to the function that threw this error',762)763}764}765766// PUBLIC API767768exports.Browser = capabilities.Browser769exports.Builder = Builder770exports.Button = input.Button771exports.By = by.By772exports.RelativeBy = by.RelativeBy773exports.withTagName = by.withTagName774exports.locateWith = by.locateWith775exports.Capabilities = capabilities.Capabilities776exports.Capability = capabilities.Capability777exports.Condition = webdriver.Condition778exports.FileDetector = input.FileDetector779exports.Key = input.Key780exports.Origin = input.Origin781exports.Session = session.Session782exports.ThenableWebDriver = ThenableWebDriver783exports.WebDriver = webdriver.WebDriver784exports.WebElement = webdriver.WebElement785exports.WebElementCondition = webdriver.WebElementCondition786exports.WebElementPromise = webdriver.WebElementPromise787exports.error = error788exports.logging = logging789exports.promise = promise790exports.until = until791exports.Select = select.Select792exports.LogInspector = LogInspector793exports.BrowsingContext = BrowsingContext794exports.BrowsingContextInspector = BrowsingContextInspector795exports.ScriptManager = ScriptManager796exports.NetworkInspector = NetworkInspector797exports.version = version798799800