UNPKG

selenium-webdriver

Version:

The official WebDriver JavaScript bindings from the Selenium project

1,368 lines (1,214 loc) 89.9 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. */ goog.provide('webdriver.Alert'); goog.provide('webdriver.AlertPromise'); goog.provide('webdriver.FileDetector'); goog.provide('webdriver.UnhandledAlertError'); goog.provide('webdriver.WebDriver'); goog.provide('webdriver.WebElement'); goog.provide('webdriver.WebElementPromise'); goog.require('bot.Error'); goog.require('bot.ErrorCode'); goog.require('bot.response'); goog.require('goog.array'); goog.require('goog.object'); goog.require('webdriver.ActionSequence'); goog.require('webdriver.Command'); goog.require('webdriver.CommandName'); goog.require('webdriver.Key'); goog.require('webdriver.Locator'); goog.require('webdriver.Serializable'); goog.require('webdriver.Session'); goog.require('webdriver.TouchSequence'); goog.require('webdriver.logging'); goog.require('webdriver.promise'); goog.require('webdriver.until'); ////////////////////////////////////////////////////////////////////////////// // // webdriver.WebDriver // ////////////////////////////////////////////////////////////////////////////// /** * Creates a new WebDriver client, which provides control over a browser. * * Every WebDriver command returns a {@code webdriver.promise.Promise} that * represents the result of that command. Callbacks may be registered on this * object to manipulate the command result or catch an expected error. Any * commands scheduled with a callback are considered sub-commands and will * execute before the next command in the current frame. For example: * * var message = []; * driver.call(message.push, message, 'a').then(function() { * driver.call(message.push, message, 'b'); * }); * driver.call(message.push, message, 'c'); * driver.call(function() { * alert('message is abc? ' + (message.join('') == 'abc')); * }); * * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a * known session or a promise that will be resolved to a session. * @param {!webdriver.CommandExecutor} executor The executor to use when * sending commands to the browser. * @param {webdriver.promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. * @constructor */ webdriver.WebDriver = function(session, executor, opt_flow) { /** @private {!(webdriver.Session|webdriver.promise.Promise)} */ this.session_ = session; /** @private {!webdriver.CommandExecutor} */ this.executor_ = executor; /** @private {!webdriver.promise.ControlFlow} */ this.flow_ = opt_flow || webdriver.promise.controlFlow(); /** @private {webdriver.FileDetector} */ this.fileDetector_ = null; }; /** * Creates a new WebDriver client for an existing session. * @param {!webdriver.CommandExecutor} executor Command executor to use when * querying for session details. * @param {string} sessionId ID of the session to attach to. * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under. Defaults to the * {@link webdriver.promise.controlFlow() currently active} control flow. * @return {!webdriver.WebDriver} A new client for the specified session. */ webdriver.WebDriver.attachToSession = function(executor, sessionId, opt_flow) { return webdriver.WebDriver.acquireSession_(executor, new webdriver.Command(webdriver.CommandName.DESCRIBE_SESSION). setParameter('sessionId', sessionId), 'WebDriver.attachToSession()', opt_flow); }; /** * Creates a new WebDriver session. * @param {!webdriver.CommandExecutor} executor The executor to create the new * session with. * @param {!webdriver.Capabilities} desiredCapabilities The desired * capabilities for the new session. * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. * Defaults to the {@link webdriver.promise.controlFlow() currently active} * control flow. * @return {!webdriver.WebDriver} The driver for the newly created session. */ webdriver.WebDriver.createSession = function( executor, desiredCapabilities, opt_flow) { return webdriver.WebDriver.acquireSession_(executor, new webdriver.Command(webdriver.CommandName.NEW_SESSION). setParameter('desiredCapabilities', desiredCapabilities), 'WebDriver.createSession()', opt_flow); }; /** * Sends a command to the server that is expected to return the details for a * {@link webdriver.Session}. This may either be an existing session, or a * newly created one. * @param {!webdriver.CommandExecutor} executor Command executor to use when * querying for session details. * @param {!webdriver.Command} command The command to send to fetch the session * details. * @param {string} description A descriptive debug label for this action. * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under. Defaults to the * {@link webdriver.promise.controlFlow() currently active} control flow. * @return {!webdriver.WebDriver} A new WebDriver client for the session. * @private */ webdriver.WebDriver.acquireSession_ = function( executor, command, description, opt_flow) { var flow = opt_flow || webdriver.promise.controlFlow(); var session = flow.execute(function() { return webdriver.WebDriver.executeCommand_(executor, command). then(function(response) { bot.response.checkResponse(response); return new webdriver.Session(response['sessionId'], response['value']); }); }, description); return new webdriver.WebDriver(session, executor, flow); }; /** * 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 is a Serializable, its * {@link webdriver.Serializable#serialize} function will be invoked and * this algorithm will recursively be applied to the result * <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 {!webdriver.promise.Promise.<?>} A promise that will resolve to the * input value's JSON representation. * @private * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol */ webdriver.WebDriver.toWireValue_ = function(obj) { if (webdriver.promise.isPromise(obj)) { return obj.then(webdriver.WebDriver.toWireValue_); } return webdriver.promise.fulfilled(convertValue(obj)); function convertValue(value) { switch (goog.typeOf(value)) { case 'array': return convertKeys(value, true); case 'object': // NB: WebElement is a Serializable, but we know its serialized form // is a promise for its wire format. This is a micro optimization to // avoid creating extra promises by recursing on the promised id. if (value instanceof webdriver.WebElement) { return value.getId(); } if (value instanceof webdriver.Serializable) { return webdriver.WebDriver.toWireValue_(value.serialize()); } if (goog.isFunction(value.toJSON)) { return webdriver.WebDriver.toWireValue_(value.toJSON()); } if (goog.isNumber(value.nodeType) && goog.isString(value.nodeName)) { throw new TypeError( 'Invalid argument type: ' + value.nodeName + '(' + value.nodeType + ')'); } return convertKeys(value, false); case 'function': return '' + value; case 'undefined': return null; default: return value; } } function convertKeys(obj, isArray) { var numKeys = isArray ? obj.length : goog.object.getCount(obj); var ret = isArray ? new Array(numKeys) : {}; if (!numKeys) { return webdriver.promise.fulfilled(ret); } var numResolved = 0; var done = webdriver.promise.defer(); // forEach will stop iteration at undefined, where we want to convert // these to null and keep iterating. var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) { var n = arr.length; for (var i = 0; i < n; i++) { fn(arr[i], i); } }; forEachKey(obj, function(value, key) { if (webdriver.promise.isPromise(value)) { value.then(webdriver.WebDriver.toWireValue_). then(setValue, done.reject); } else { webdriver.promise.asap(convertValue(value), setValue, done.reject); } function setValue(value) { ret[key] = value; maybeFulfill(); } }); return done.promise; function maybeFulfill() { if (++numResolved === numKeys) { done.fulfill(ret); } } } }; /** * Converts a value from its JSON representation according to the WebDriver wire * protocol. Any JSON object containing a * {@code webdriver.WebElement.ELEMENT_KEY} key will be decoded to a * {@code webdriver.WebElement} object. All other values will be passed through * as is. * @param {!webdriver.WebDriver} driver The driver instance to use as the * parent of any unwrapped {@code webdriver.WebElement} values. * @param {*} value The value to convert. * @return {*} The converted value. * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol * @private */ webdriver.WebDriver.fromWireValue_ = function(driver, value) { if (goog.isArray(value)) { value = goog.array.map(/**@type {goog.array.ArrayLike}*/ (value), goog.partial(webdriver.WebDriver.fromWireValue_, driver)); } else if (value && goog.isObject(value) && !goog.isFunction(value)) { if (webdriver.WebElement.ELEMENT_KEY in value) { value = new webdriver.WebElement(driver, value); } else { value = goog.object.map(/**@type {!Object}*/ (value), goog.partial(webdriver.WebDriver.fromWireValue_, driver)); } } return value; }; /** * Translates a command to its wire-protocol representation before passing it * to the given {@code executor} for execution. * @param {!webdriver.CommandExecutor} executor The executor to use. * @param {!webdriver.Command} command The command to execute. * @return {!webdriver.promise.Promise} A promise that will resolve with the * command response. * @private */ webdriver.WebDriver.executeCommand_ = function(executor, command) { return webdriver.WebDriver.toWireValue_(command.getParameters()). then(function(parameters) { command.setParameters(parameters); return webdriver.promise.checkedNodeCall( goog.bind(executor.execute, executor, command)); }); }; /** * @return {!webdriver.promise.ControlFlow} The control flow used by this * instance. */ webdriver.WebDriver.prototype.controlFlow = function() { return this.flow_; }; /** * Schedules a {@code webdriver.Command} to be executed by this driver's * {@code webdriver.CommandExecutor}. * @param {!webdriver.Command} command The command to schedule. * @param {string} description A description of the command for debugging. * @return {!webdriver.promise.Promise.<T>} A promise that will be resolved * with the command result. * @template T */ webdriver.WebDriver.prototype.schedule = function(command, description) { var self = this; checkHasNotQuit(); command.setParameter('sessionId', this.session_); // If any of the command parameters are rejected promises, those // rejections may be reported as unhandled before the control flow // attempts to execute the command. To ensure parameters errors // propagate through the command itself, we resolve all of the // command parameters now, but suppress any errors until the ControlFlow // actually executes the command. This addresses scenarios like catching // an element not found error in: // // driver.findElement(By.id('foo')).click().thenCatch(function(e) { // if (e.code === bot.ErrorCode.NO_SUCH_ELEMENT) { // // Do something. // } // }); var prepCommand = webdriver.WebDriver.toWireValue_(command.getParameters()); prepCommand.thenCatch(goog.nullFunction); var flow = this.flow_; var executor = this.executor_; return flow.execute(function() { // A call to WebDriver.quit() may have been scheduled in the same event // loop as this |command|, which would prevent us from detecting that the // driver has quit above. Therefore, we need to make another quick check. // We still check above so we can fail as early as possible. checkHasNotQuit(); // Retrieve resolved command parameters; any previously suppressed errors // will now propagate up through the control flow as part of the command // execution. return prepCommand.then(function(parameters) { command.setParameters(parameters); return webdriver.promise.checkedNodeCall( goog.bind(executor.execute, executor, command)); }); }, description).then(function(response) { try { bot.response.checkResponse(response); } catch (ex) { var value = response['value']; if (ex.code === bot.ErrorCode.UNEXPECTED_ALERT_OPEN) { var text = value && value['alert'] ? value['alert']['text'] : ''; throw new webdriver.UnhandledAlertError(ex.message, text, new webdriver.Alert(self, text)); } throw ex; } return webdriver.WebDriver.fromWireValue_(self, response['value']); }); function checkHasNotQuit() { if (!self.session_) { throw new Error('This driver instance does not have a valid session ID ' + '(did you call WebDriver.quit()?) and may no longer be ' + 'used.'); } } }; /** * Sets the {@linkplain webdriver.FileDetector file detector} that should be * used with this instance. * @param {webdriver.FileDetector} detector The detector to use or {@code null}. */ webdriver.WebDriver.prototype.setFileDetector = function(detector) { this.fileDetector_ = detector; }; // ---------------------------------------------------------------------------- // Client command functions: // ---------------------------------------------------------------------------- /** * @return {!webdriver.promise.Promise.<!webdriver.Session>} A promise for this * client's session. */ webdriver.WebDriver.prototype.getSession = function() { return webdriver.promise.when(this.session_); }; /** * @return {!webdriver.promise.Promise.<!webdriver.Capabilities>} A promise * that will resolve with the this instance's capabilities. */ webdriver.WebDriver.prototype.getCapabilities = function() { return webdriver.promise.when(this.session_, function(session) { return session.getCapabilities(); }); }; /** * Schedules a command to quit the current session. After calling quit, this * instance will be invalidated and may no longer be used to issue commands * against the browser. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the command has completed. */ webdriver.WebDriver.prototype.quit = function() { var result = this.schedule( new webdriver.Command(webdriver.CommandName.QUIT), 'WebDriver.quit()'); // Delete our session ID when the quit command finishes; this will allow us to // throw an error when attemnpting to use a driver post-quit. return result.thenFinally(goog.bind(function() { delete this.session_; }, this)); }; /** * Creates a new action sequence using this driver. The sequence will not be * scheduled for execution until {@link webdriver.ActionSequence#perform} is * called. Example: * * driver.actions(). * mouseDown(element1). * mouseMove(element2). * mouseUp(). * perform(); * * @return {!webdriver.ActionSequence} A new action sequence for this instance. */ webdriver.WebDriver.prototype.actions = function() { return new webdriver.ActionSequence(this); }; /** * Creates a new touch sequence using this driver. The sequence will not be * scheduled for execution until {@link webdriver.TouchSequence#perform} is * called. Example: * * driver.touchActions(). * tap(element1). * doubleTap(element2). * perform(); * * @return {!webdriver.TouchSequence} A new touch sequence for this instance. */ webdriver.WebDriver.prototype.touchActions = function() { return new webdriver.TouchSequence(this); }; /** * Schedules a command to execute 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 {@code arguments} object. * Arguments may be a boolean, number, string, or {@code webdriver.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 * {@code 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 * {@link webdriver.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 {...*} var_args The arguments to pass to the script. * @return {!webdriver.promise.Promise.<T>} A promise that will resolve to the * scripts return value. * @template T */ webdriver.WebDriver.prototype.executeScript = function(script, var_args) { if (goog.isFunction(script)) { script = 'return (' + script + ').apply(null, arguments);'; } var args = arguments.length > 1 ? goog.array.slice(arguments, 1) : []; return this.schedule( new webdriver.Command(webdriver.CommandName.EXECUTE_SCRIPT). setParameter('script', script). setParameter('args', args), 'WebDriver.executeScript()'); }; /** * Schedules a command to execute 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 {@code arguments} object. * Arguments may be a boolean, number, string, or {@code webdriver.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 {@code 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 webdriver.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 {...*} var_args The arguments to pass to the script. * @return {!webdriver.promise.Promise.<T>} A promise that will resolve to the * scripts return value. * @template T */ webdriver.WebDriver.prototype.executeAsyncScript = function(script, var_args) { if (goog.isFunction(script)) { script = 'return (' + script + ').apply(null, arguments);'; } return this.schedule( new webdriver.Command(webdriver.CommandName.EXECUTE_ASYNC_SCRIPT). setParameter('script', script). setParameter('args', goog.array.slice(arguments, 1)), 'WebDriver.executeScript()'); }; /** * Schedules a command to execute a custom function. * @param {function(...): (T|webdriver.promise.Promise.<T>)} fn The function to * execute. * @param {Object=} opt_scope The object in whose scope to execute the function. * @param {...*} var_args Any arguments to pass to the function. * @return {!webdriver.promise.Promise.<T>} A promise that will be resolved' * with the function's result. * @template T */ webdriver.WebDriver.prototype.call = function(fn, opt_scope, var_args) { var args = goog.array.slice(arguments, 2); var flow = this.flow_; return flow.execute(function() { return webdriver.promise.fullyResolved(args).then(function(args) { if (webdriver.promise.isGenerator(fn)) { args.unshift(fn, opt_scope); return webdriver.promise.consume.apply(null, args); } return fn.apply(opt_scope, args); }); }, 'WebDriver.call(' + (fn.name || 'function') + ')'); }; /** * Schedules a command to wait for a condition to hold. The condition may be * specified by a {@link webdriver.until.Condition}, as a custom function, or * as a {@link webdriver.promise.Promise}. * * For a {@link webdriver.until.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 {@link webdriver.promise.Promise promise}, the * polling loop will wait for it to be resolved and use the resolved value for * whether the condition has been satisified. Note the resolution time for * a promise is factored into whether a wait has timed out. * * *Example:* waiting up to 10 seconds for an element to be present and visible * on the page. * * var button = driver.wait(until.elementLocated(By.id('foo')), 10000); * button.click(); * * This function may also be used to block the command flow on the resolution * of a {@link webdriver.promise.Promise promise}. When given a promise, the * command will simply wait for its resolution before completing. A timeout may * be provided to fail the command if the promise does not resolve before the * timeout expires. * * *Example:* Suppose you have a function, `startTestServer`, that returns a * promise for when a server is ready for requests. You can block a `WebDriver` * client on this promise with: * * var started = startTestServer(); * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); * driver.get(getServerUrl()); * * @param {!(webdriver.promise.Promise<T>| * webdriver.until.Condition<T>| * function(!webdriver.WebDriver): T)} condition The condition to * wait on, defined as a promise, condition object, or a function to * evaluate as a condition. * @param {number=} opt_timeout How long to wait for the condition to be true. * @param {string=} opt_message An optional message to use if the wait times * out. * @return {!webdriver.promise.Promise<T>} A promise that will be fulfilled * with the first truthy value returned by the condition function, or * rejected if the condition times out. * @template T */ webdriver.WebDriver.prototype.wait = function( condition, opt_timeout, opt_message) { if (webdriver.promise.isPromise(condition)) { return this.flow_.wait( /** @type {!webdriver.promise.Promise} */(condition), opt_timeout, opt_message); } var message = opt_message; var fn = /** @type {!Function} */(condition); if (condition instanceof webdriver.until.Condition) { message = message || condition.description(); fn = condition.fn; } var driver = this; return this.flow_.wait(function() { if (webdriver.promise.isGenerator(fn)) { return webdriver.promise.consume(fn, null, [driver]); } return fn(driver); }, opt_timeout, message); }; /** * Schedules a command to make the driver sleep for the given amount of time. * @param {number} ms The amount of time, in milliseconds, to sleep. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the sleep has finished. */ webdriver.WebDriver.prototype.sleep = function(ms) { return this.flow_.timeout(ms, 'WebDriver.sleep(' + ms + ')'); }; /** * Schedules a command to retrieve they current window handle. * @return {!webdriver.promise.Promise.<string>} A promise that will be * resolved with the current window handle. */ webdriver.WebDriver.prototype.getWindowHandle = function() { return this.schedule( new webdriver.Command(webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE), 'WebDriver.getWindowHandle()'); }; /** * Schedules a command to retrieve the current list of available window handles. * @return {!webdriver.promise.Promise.<!Array.<string>>} A promise that will * be resolved with an array of window handles. */ webdriver.WebDriver.prototype.getAllWindowHandles = function() { return this.schedule( new webdriver.Command(webdriver.CommandName.GET_WINDOW_HANDLES), 'WebDriver.getAllWindowHandles()'); }; /** * Schedules a command to retrieve the current page's source. The page source * returned is a representation of the underlying DOM: do not expect it to be * formatted or escaped in the same way as the response sent from the web * server. * @return {!webdriver.promise.Promise.<string>} A promise that will be * resolved with the current page source. */ webdriver.WebDriver.prototype.getPageSource = function() { return this.schedule( new webdriver.Command(webdriver.CommandName.GET_PAGE_SOURCE), 'WebDriver.getAllWindowHandles()'); }; /** * Schedules a command to close the current window. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when this command has completed. */ webdriver.WebDriver.prototype.close = function() { return this.schedule(new webdriver.Command(webdriver.CommandName.CLOSE), 'WebDriver.close()'); }; /** * Schedules a command to navigate to the given URL. * @param {string} url The fully qualified URL to open. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the document has finished loading. */ webdriver.WebDriver.prototype.get = function(url) { return this.navigate().to(url); }; /** * Schedules a command to retrieve the URL of the current page. * @return {!webdriver.promise.Promise.<string>} A promise that will be * resolved with the current URL. */ webdriver.WebDriver.prototype.getCurrentUrl = function() { return this.schedule( new webdriver.Command(webdriver.CommandName.GET_CURRENT_URL), 'WebDriver.getCurrentUrl()'); }; /** * Schedules a command to retrieve the current page's title. * @return {!webdriver.promise.Promise.<string>} A promise that will be * resolved with the current page's title. */ webdriver.WebDriver.prototype.getTitle = function() { return this.schedule(new webdriver.Command(webdriver.CommandName.GET_TITLE), 'WebDriver.getTitle()'); }; /** * Schedule a command to find an element on the page. If the element cannot be * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned * by the driver. Unlike other commands, this error cannot be suppressed. In * other words, scheduling a command to find an element doubles as an assert * that the element is present on the page. To test whether an element is * present on the page, use {@link #isElementPresent} instead. * * 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 WebDriver instance and returns a {@link webdriver.WebElement}, or a * promise that will resolve to a WebElement. 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 webdriver.promise.filter(links, function(link) { * return links.isDisplayed(); * }).then(function(visibleLinks) { * return visibleLinks[0]; * }); * } * * When running in the browser, a WebDriver cannot manipulate DOM elements * directly; it may do so only through a {@link webdriver.WebElement} reference. * This function may be used to generate a WebElement from a DOM element. A * reference to the DOM element will be stored in a known location and this * driver will attempt to retrieve it through {@link #executeScript}. If the * element cannot be found (eg, it belongs to a different document than the * one this instance is currently focused on), a * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. * * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The * locator to use. * @return {!webdriver.WebElement} 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. */ webdriver.WebDriver.prototype.findElement = function(locator) { var id; if ('nodeType' in locator && 'ownerDocument' in locator) { var element = /** @type {!Element} */ (locator); id = this.findDomElement_(element).then(function(element) { if (!element) { throw new bot.Error(bot.ErrorCode.NO_SUCH_ELEMENT, 'Unable to locate element. Is WebDriver focused on its ' + 'ownerDocument\'s frame?'); } return element; }); } else { locator = webdriver.Locator.checkLocator(locator); if (goog.isFunction(locator)) { id = this.findElementInternal_(locator, this); } else { var command = new webdriver.Command(webdriver.CommandName.FIND_ELEMENT). setParameter('using', locator.using). setParameter('value', locator.value); id = this.schedule(command, 'WebDriver.findElement(' + locator + ')'); } } return new webdriver.WebElementPromise(this, id); }; /** * @param {!Function} locatorFn The locator function to use. * @param {!(webdriver.WebDriver|webdriver.WebElement)} context The search * context. * @return {!webdriver.promise.Promise.<!webdriver.WebElement>} A * promise that will resolve to a list of WebElements. * @private */ webdriver.WebDriver.prototype.findElementInternal_ = function( locatorFn, context) { return this.call(goog.partial(locatorFn, context)).then(function(result) { if (goog.isArray(result)) { result = result[0]; } if (!(result instanceof webdriver.WebElement)) { throw new TypeError('Custom locator did not return a WebElement'); } return result; }); }; /** * Locates a DOM element so that commands may be issued against it using the * {@link webdriver.WebElement} class. This is accomplished by storing a * reference to the element in an object on the element's ownerDocument. * {@link #executeScript} will then be used to create a WebElement from this * reference. This requires this driver to currently be focused on the * ownerDocument's window+frame. * @param {!Element} element The element to locate. * @return {!webdriver.promise.Promise.<webdriver.WebElement>} A promise that * will be fulfilled with the located element, or null if the element * could not be found. * @private */ webdriver.WebDriver.prototype.findDomElement_ = function(element) { var doc = element.ownerDocument; var store = doc['$webdriver$'] = doc['$webdriver$'] || {}; var id = Math.floor(Math.random() * goog.now()).toString(36); store[id] = element; element[id] = id; function cleanUp() { delete store[id]; } function lookupElement(id) { var store = document['$webdriver$']; if (!store) { return null; } var element = store[id]; if (!element || element[id] !== id) { return null; } return element; } /** @type {!webdriver.promise.Promise.<webdriver.WebElement>} */ var foundElement = this.executeScript(lookupElement, id); foundElement.thenFinally(cleanUp); return foundElement; }; /** * Schedules a command to test if an element is present on the page. * * If given a DOM element, this function will check if it belongs to the * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * * @param {!(webdriver.Locator|webdriver.By.Hash|Element| * Function)} locatorOrElement The locator to use, or the actual * DOM element to be located by the server. * @return {!webdriver.promise.Promise.<boolean>} A promise that will resolve * with whether the element is present on the page. */ webdriver.WebDriver.prototype.isElementPresent = function(locatorOrElement) { if ('nodeType' in locatorOrElement && 'ownerDocument' in locatorOrElement) { return this.findDomElement_(/** @type {!Element} */ (locatorOrElement)). then(function(result) { return !!result; }); } else { return this.findElements.apply(this, arguments).then(function(result) { return !!result.length; }); } }; /** * Schedule a command to search for multiple elements on the page. * * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator * strategy to use when searching for the element. * @return {!webdriver.promise.Promise.<!Array.<!webdriver.WebElement>>} A * promise that will resolve to an array of WebElements. */ webdriver.WebDriver.prototype.findElements = function(locator) { locator = webdriver.Locator.checkLocator(locator); if (goog.isFunction(locator)) { return this.findElementsInternal_(locator, this); } else { var command = new webdriver.Command(webdriver.CommandName.FIND_ELEMENTS). setParameter('using', locator.using). setParameter('value', locator.value); return this.schedule(command, 'WebDriver.findElements(' + locator + ')'); } }; /** * @param {!Function} locatorFn The locator function to use. * @param {!(webdriver.WebDriver|webdriver.WebElement)} context The search * context. * @return {!webdriver.promise.Promise.<!Array.<!webdriver.WebElement>>} A * promise that will resolve to an array of WebElements. * @private */ webdriver.WebDriver.prototype.findElementsInternal_ = function( locatorFn, context) { return this.call(goog.partial(locatorFn, context)).then(function(result) { if (result instanceof webdriver.WebElement) { return [result]; } if (!goog.isArray(result)) { return []; } return goog.array.filter(result, function(item) { return item instanceof webdriver.WebElement; }); }); }; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: * <ol> * <li>Entire page * <li>Current window * <li>Visible portion of the current frame * <li>The screenshot of the entire display containing the browser * </ol> * * @return {!webdriver.promise.Promise.<string>} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ webdriver.WebDriver.prototype.takeScreenshot = function() { return this.schedule(new webdriver.Command(webdriver.CommandName.SCREENSHOT), 'WebDriver.takeScreenshot()'); }; /** * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ webdriver.WebDriver.prototype.manage = function() { return new webdriver.WebDriver.Options(this); }; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ webdriver.WebDriver.prototype.navigate = function() { return new webdriver.WebDriver.Navigation(this); }; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ webdriver.WebDriver.prototype.switchTo = function() { return new webdriver.WebDriver.TargetLocator(this); }; /** * Interface for navigating back and forth in the browser history. * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ webdriver.WebDriver.Navigation = function(driver) { /** @private {!webdriver.WebDriver} */ this.driver_ = driver; }; /** * Schedules a command to navigate to a new URL. * @param {string} url The URL to navigate to. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the URL has been loaded. */ webdriver.WebDriver.Navigation.prototype.to = function(url) { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.GET). setParameter('url', url), 'WebDriver.navigate().to(' + url + ')'); }; /** * Schedules a command to move backwards in the browser history. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the navigation event has completed. */ webdriver.WebDriver.Navigation.prototype.back = function() { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.GO_BACK), 'WebDriver.navigate().back()'); }; /** * Schedules a command to move forwards in the browser history. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the navigation event has completed. */ webdriver.WebDriver.Navigation.prototype.forward = function() { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.GO_FORWARD), 'WebDriver.navigate().forward()'); }; /** * Schedules a command to refresh the current page. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the navigation event has completed. */ webdriver.WebDriver.Navigation.prototype.refresh = function() { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.REFRESH), 'WebDriver.navigate().refresh()'); }; /** * Provides methods for managing browser and driver state. * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ webdriver.WebDriver.Options = function(driver) { /** @private {!webdriver.WebDriver} */ this.driver_ = driver; }; /** * A JSON description of a browser cookie. * @typedef {{ * name: string, * value: string, * path: (string|undefined), * domain: (string|undefined), * secure: (boolean|undefined), * expiry: (number|undefined) * }} * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#cookie-json-object */ webdriver.WebDriver.Options.Cookie; /** * Schedules a command to add a cookie. * @param {string} name The cookie name. * @param {string} value The cookie value. * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as * a number, should be in milliseconds since midnight, January 1, 1970 UTC. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the cookie has been added to the page. */ webdriver.WebDriver.Options.prototype.addCookie = function( name, value, opt_path, opt_domain, opt_isSecure, opt_expiry) { // We do not allow '=' or ';' in the name. if (/[;=]/.test(name)) { throw Error('Invalid cookie name "' + name + '"'); } // We do not allow ';' in value. if (/;/.test(value)) { throw Error('Invalid cookie value "' + value + '"'); } var cookieString = name + '=' + value + (opt_domain ? ';domain=' + opt_domain : '') + (opt_path ? ';path=' + opt_path : '') + (opt_isSecure ? ';secure' : ''); var expiry; if (goog.isDef(opt_expiry)) { var expiryDate; if (goog.isNumber(opt_expiry)) { expiryDate = new Date(opt_expiry); } else { expiryDate = /** @type {!Date} */ (opt_expiry); opt_expiry = expiryDate.getTime(); } cookieString += ';expires=' + expiryDate.toUTCString(); // Convert from milliseconds to seconds. expiry = Math.floor(/** @type {number} */ (opt_expiry) / 1000); } return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.ADD_COOKIE). setParameter('cookie', { 'name': name, 'value': value, 'path': opt_path, 'domain': opt_domain, 'secure': !!opt_isSecure, 'expiry': expiry }), 'WebDriver.manage().addCookie(' + cookieString + ')'); }; /** * Schedules a command to delete all cookies visible to the current page. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when all cookies have been deleted. */ webdriver.WebDriver.Options.prototype.deleteAllCookies = function() { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.DELETE_ALL_COOKIES), 'WebDriver.manage().deleteAllCookies()'); }; /** * Schedules a command to delete the cookie with the given name. This command is * a no-op if there is no cookie with the given name visible to the current * page. * @param {string} name The name of the cookie to delete. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the cookie has been deleted. */ webdriver.WebDriver.Options.prototype.deleteCookie = function(name) { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.DELETE_COOKIE). setParameter('name', name), 'WebDriver.manage().deleteCookie(' + name + ')'); }; /** * Schedules a command to retrieve all cookies visible to the current page. * Each cookie will be returned as a JSON object as described by the WebDriver * wire protocol. * @return {!webdriver.promise.Promise.< * !Array.<webdriver.WebDriver.Options.Cookie>>} A promise that will be * resolved with the cookies visible to the current page. * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#cookie-json-object */ webdriver.WebDriver.Options.prototype.getCookies = function() { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.GET_ALL_COOKIES), 'WebDriver.manage().getCookies()'); }; /** * Schedules a command to retrieve the cookie with the given name. Returns null * if there is no such cookie. The cookie will be returned as a JSON object as * described by the WebDriver wire protocol. * @param {string} name The name of the cookie to retrieve. * @return {!webdriver.promise.Promise.<?webdriver.WebDriver.Options.Cookie>} A * promise that will be resolved with the named cookie, or {@code null} * if there is no such cookie. * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#cookie-json-object */ webdriver.WebDriver.Options.prototype.getCookie = function(name) { return this.getCookies().then(function(cookies) { return goog.array.find(cookies, function(cookie) { return cookie && cookie['name'] == name; }); }); }; /** * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ webdriver.WebDriver.Options.prototype.logs = function() { return new webdriver.WebDriver.Logs(this.driver_); }; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ webdriver.WebDriver.Options.prototype.timeouts = function() { return new webdriver.WebDriver.Timeouts(this.driver_); }; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ webdriver.WebDriver.Options.prototype.window = function() { return new webdriver.WebDriver.Window(this.driver_); }; /** * An interface for managing timeout behavior for WebDriver instances. * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ webdriver.WebDriver.Timeouts = function(driver) { /** @private {!webdriver.WebDriver} */ this.driver_ = driver; }; /** * Specifies the amount of time the driver should wait when searching for an * element if it is not immediately present. * * When searching for a single element, the driver should poll the page * until the element has been found, or this timeout expires before failing * with a {@link bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching * for multiple elements, the driver should poll the page until at least one * element has been found or this timeout has expired. * * Setting the wait timeout to 0 (its default value), disables implicit * waiting. * * Increasing the implicit wait timeout should be used judiciously as it * will have an adverse effect on test run time, especially when used with * slower location strategies like XPath. * * @param {number} ms The amount of time to wait, in milliseconds. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the implicit wait timeout has been set. */ webdriver.WebDriver.Timeouts.prototype.implicitlyWait = function(ms) { return this.driver_.schedule( new webdriver.Command(webdriver.CommandName.IMPLICITLY_WAIT). setParameter('ms', ms < 0 ? 0 : ms), 'WebDriver.manage().timeouts().implicitlyWait(' + ms + ')'); }; /** * Sets the amount of time to wait, in milliseconds, for an asynchronous script * to finish execution before returning an error. If the timeout is less than or * equal to 0, the script will be allowed to run indefinitely. * * @param {number} ms The amount of time to wait, in milliseconds. * @return {!webdriver.promise.Promise.<void>} A promise that will be resolved * when the script timeout has been set. */ webdriver.WebDriver.Timeouts.prototype.setScriptTimeout = function(