webdriver.js 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  1. // Licensed to the Software Freedom Conservancy (SFC) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The SFC licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. /**
  18. * @fileoverview The heart of the WebDriver JavaScript API.
  19. */
  20. 'use strict';
  21. const actions = require('./actions');
  22. const by = require('./by');
  23. const Capabilities = require('./capabilities').Capabilities;
  24. const command = require('./command');
  25. const error = require('./error');
  26. const input = require('./input');
  27. const logging = require('./logging');
  28. const {Session} = require('./session');
  29. const Symbols = require('./symbols');
  30. const promise = require('./promise');
  31. /**
  32. * Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait
  33. * command}.
  34. *
  35. * @template OUT
  36. */
  37. class Condition {
  38. /**
  39. * @param {string} message A descriptive error message. Should complete the
  40. * sentence "Waiting [...]"
  41. * @param {function(!WebDriver): OUT} fn The condition function to
  42. * evaluate on each iteration of the wait loop.
  43. */
  44. constructor(message, fn) {
  45. /** @private {string} */
  46. this.description_ = 'Waiting ' + message;
  47. /** @type {function(!WebDriver): OUT} */
  48. this.fn = fn;
  49. }
  50. /** @return {string} A description of this condition. */
  51. description() {
  52. return this.description_;
  53. }
  54. }
  55. /**
  56. * Defines a condition that will result in a {@link WebElement}.
  57. *
  58. * @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
  59. */
  60. class WebElementCondition extends Condition {
  61. /**
  62. * @param {string} message A descriptive error message. Should complete the
  63. * sentence "Waiting [...]"
  64. * @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}
  65. * fn The condition function to evaluate on each iteration of the wait
  66. * loop.
  67. */
  68. constructor(message, fn) {
  69. super(message, fn);
  70. }
  71. }
  72. //////////////////////////////////////////////////////////////////////////////
  73. //
  74. // WebDriver
  75. //
  76. //////////////////////////////////////////////////////////////////////////////
  77. /**
  78. * Translates a command to its wire-protocol representation before passing it
  79. * to the given `executor` for execution.
  80. * @param {!command.Executor} executor The executor to use.
  81. * @param {!command.Command} command The command to execute.
  82. * @return {!Promise} A promise that will resolve with the command response.
  83. */
  84. function executeCommand(executor, command) {
  85. return toWireValue(command.getParameters()).
  86. then(function(parameters) {
  87. command.setParameters(parameters);
  88. return executor.execute(command);
  89. });
  90. }
  91. /**
  92. * Converts an object to its JSON representation in the WebDriver wire protocol.
  93. * When converting values of type object, the following steps will be taken:
  94. * <ol>
  95. * <li>if the object is a WebElement, the return value will be the element's
  96. * server ID
  97. * <li>if the object defines a {@link Symbols.serialize} method, this algorithm
  98. * will be recursively applied to the object's serialized representation
  99. * <li>if the object provides a "toJSON" function, this algorithm will
  100. * recursively be applied to the result of that function
  101. * <li>otherwise, the value of each key will be recursively converted according
  102. * to the rules above.
  103. * </ol>
  104. *
  105. * @param {*} obj The object to convert.
  106. * @return {!Promise<?>} A promise that will resolve to the input value's JSON
  107. * representation.
  108. */
  109. function toWireValue(obj) {
  110. if (promise.isPromise(obj)) {
  111. return Promise.resolve(obj).then(toWireValue);
  112. }
  113. return Promise.resolve(convertValue(obj));
  114. }
  115. function convertValue(value) {
  116. if (value === void 0 || value === null) {
  117. return value;
  118. }
  119. if (typeof value === 'boolean'
  120. || typeof value === 'number'
  121. || typeof value === 'string') {
  122. return value;
  123. }
  124. if (Array.isArray(value)) {
  125. return convertKeys(value);
  126. }
  127. if (typeof value === 'function') {
  128. return '' + value;
  129. }
  130. if (typeof value[Symbols.serialize] === 'function') {
  131. return toWireValue(value[Symbols.serialize]());
  132. } else if (typeof value.toJSON === 'function') {
  133. return toWireValue(value.toJSON());
  134. }
  135. return convertKeys(value);
  136. }
  137. function convertKeys(obj) {
  138. const isArray = Array.isArray(obj);
  139. const numKeys = isArray ? obj.length : Object.keys(obj).length;
  140. const ret = isArray ? new Array(numKeys) : {};
  141. if (!numKeys) {
  142. return Promise.resolve(ret);
  143. }
  144. let numResolved = 0;
  145. function forEachKey(obj, fn) {
  146. if (Array.isArray(obj)) {
  147. for (let i = 0, n = obj.length; i < n; i++) {
  148. fn(obj[i], i);
  149. }
  150. } else {
  151. for (let key in obj) {
  152. fn(obj[key], key);
  153. }
  154. }
  155. }
  156. return new Promise(function(done, reject) {
  157. forEachKey(obj, function(value, key) {
  158. if (promise.isPromise(value)) {
  159. value.then(toWireValue).then(setValue, reject);
  160. } else {
  161. value = convertValue(value);
  162. if (promise.isPromise(value)) {
  163. value.then(toWireValue).then(setValue, reject);
  164. } else {
  165. setValue(value);
  166. }
  167. }
  168. function setValue(value) {
  169. ret[key] = value;
  170. maybeFulfill();
  171. }
  172. });
  173. function maybeFulfill() {
  174. if (++numResolved === numKeys) {
  175. done(ret);
  176. }
  177. }
  178. });
  179. }
  180. /**
  181. * Converts a value from its JSON representation according to the WebDriver wire
  182. * protocol. Any JSON object that defines a WebElement ID will be decoded to a
  183. * {@link WebElement} object. All other values will be passed through as is.
  184. *
  185. * @param {!WebDriver} driver The driver to use as the parent of any unwrapped
  186. * {@link WebElement} values.
  187. * @param {*} value The value to convert.
  188. * @return {*} The converted value.
  189. */
  190. function fromWireValue(driver, value) {
  191. if (Array.isArray(value)) {
  192. value = value.map(v => fromWireValue(driver, v));
  193. } else if (WebElement.isId(value)) {
  194. let id = WebElement.extractId(value);
  195. value = new WebElement(driver, id);
  196. } else if (value && typeof value === 'object') {
  197. let result = {};
  198. for (let key in value) {
  199. if (value.hasOwnProperty(key)) {
  200. result[key] = fromWireValue(driver, value[key]);
  201. }
  202. }
  203. value = result;
  204. }
  205. return value;
  206. }
  207. /**
  208. * Structural interface for a WebDriver client.
  209. *
  210. * @record
  211. */
  212. class IWebDriver {
  213. /** @return {!promise.ControlFlow} The control flow used by this instance. */
  214. controlFlow() {}
  215. /**
  216. * Schedules a {@link command.Command} to be executed by this driver's
  217. * {@link command.Executor}.
  218. *
  219. * @param {!command.Command} command The command to schedule.
  220. * @param {string} description A description of the command for debugging.
  221. * @return {!promise.Thenable<T>} A promise that will be resolved
  222. * with the command result.
  223. * @template T
  224. */
  225. schedule(command, description) {}
  226. /**
  227. * Sets the {@linkplain input.FileDetector file detector} that should be
  228. * used with this instance.
  229. * @param {input.FileDetector} detector The detector to use or {@code null}.
  230. */
  231. setFileDetector(detector) {}
  232. /**
  233. * @return {!command.Executor} The command executor used by this instance.
  234. */
  235. getExecutor() {}
  236. /**
  237. * @return {!promise.Thenable<!Session>} A promise for this client's session.
  238. */
  239. getSession() {}
  240. /**
  241. * @return {!promise.Thenable<!Capabilities>} A promise that will resolve with
  242. * the this instance's capabilities.
  243. */
  244. getCapabilities() {}
  245. /**
  246. * Terminates the browser session. After calling quit, this instance will be
  247. * invalidated and may no longer be used to issue commands against the
  248. * browser.
  249. *
  250. * @return {!promise.Thenable<void>} A promise that will be resolved when the
  251. * command has completed.
  252. */
  253. quit() {}
  254. /**
  255. * Creates a new action sequence using this driver. The sequence will not be
  256. * scheduled for execution until {@link actions.ActionSequence#perform} is
  257. * called. Example:
  258. *
  259. * driver.actions().
  260. * mouseDown(element1).
  261. * mouseMove(element2).
  262. * mouseUp().
  263. * perform();
  264. *
  265. * @return {!actions.ActionSequence} A new action sequence for this instance.
  266. */
  267. actions() {}
  268. /**
  269. * Creates a new touch sequence using this driver. The sequence will not be
  270. * scheduled for execution until {@link actions.TouchSequence#perform} is
  271. * called. Example:
  272. *
  273. * driver.touchActions().
  274. * tap(element1).
  275. * doubleTap(element2).
  276. * perform();
  277. *
  278. * @return {!actions.TouchSequence} A new touch sequence for this instance.
  279. */
  280. touchActions() {}
  281. /**
  282. * Schedules a command to execute JavaScript in the context of the currently
  283. * selected frame or window. The script fragment will be executed as the body
  284. * of an anonymous function. If the script is provided as a function object,
  285. * that function will be converted to a string for injection into the target
  286. * window.
  287. *
  288. * Any arguments provided in addition to the script will be included as script
  289. * arguments and may be referenced using the {@code arguments} object.
  290. * Arguments may be a boolean, number, string, or {@linkplain WebElement}.
  291. * Arrays and objects may also be used as script arguments as long as each item
  292. * adheres to the types previously mentioned.
  293. *
  294. * The script may refer to any variables accessible from the current window.
  295. * Furthermore, the script will execute in the window's context, thus
  296. * {@code document} may be used to refer to the current document. Any local
  297. * variables will not be available once the script has finished executing,
  298. * though global variables will persist.
  299. *
  300. * If the script has a return value (i.e. if the script contains a return
  301. * statement), then the following steps will be taken for resolving this
  302. * functions return value:
  303. *
  304. * - For a HTML element, the value will resolve to a {@linkplain WebElement}
  305. * - Null and undefined return values will resolve to null</li>
  306. * - Booleans, numbers, and strings will resolve as is</li>
  307. * - Functions will resolve to their string representation</li>
  308. * - For arrays and objects, each member item will be converted according to
  309. * the rules above
  310. *
  311. * @param {!(string|Function)} script The script to execute.
  312. * @param {...*} var_args The arguments to pass to the script.
  313. * @return {!promise.Thenable<T>} A promise that will resolve to the
  314. * scripts return value.
  315. * @template T
  316. */
  317. executeScript(script, var_args) {}
  318. /**
  319. * Schedules a command to execute asynchronous JavaScript in the context of the
  320. * currently selected frame or window. The script fragment will be executed as
  321. * the body of an anonymous function. If the script is provided as a function
  322. * object, that function will be converted to a string for injection into the
  323. * target window.
  324. *
  325. * Any arguments provided in addition to the script will be included as script
  326. * arguments and may be referenced using the {@code arguments} object.
  327. * Arguments may be a boolean, number, string, or {@code WebElement}.
  328. * Arrays and objects may also be used as script arguments as long as each item
  329. * adheres to the types previously mentioned.
  330. *
  331. * Unlike executing synchronous JavaScript with {@link #executeScript},
  332. * scripts executed with this function must explicitly signal they are finished
  333. * by invoking the provided callback. This callback will always be injected
  334. * into the executed function as the last argument, and thus may be referenced
  335. * with {@code arguments[arguments.length - 1]}. The following steps will be
  336. * taken for resolving this functions return value against the first argument
  337. * to the script's callback function:
  338. *
  339. * - For a HTML element, the value will resolve to a
  340. * {@link WebElement}
  341. * - Null and undefined return values will resolve to null
  342. * - Booleans, numbers, and strings will resolve as is
  343. * - Functions will resolve to their string representation
  344. * - For arrays and objects, each member item will be converted according to
  345. * the rules above
  346. *
  347. * __Example #1:__ Performing a sleep that is synchronized with the currently
  348. * selected window:
  349. *
  350. * var start = new Date().getTime();
  351. * driver.executeAsyncScript(
  352. * 'window.setTimeout(arguments[arguments.length - 1], 500);').
  353. * then(function() {
  354. * console.log(
  355. * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
  356. * });
  357. *
  358. * __Example #2:__ Synchronizing a test with an AJAX application:
  359. *
  360. * var button = driver.findElement(By.id('compose-button'));
  361. * button.click();
  362. * driver.executeAsyncScript(
  363. * 'var callback = arguments[arguments.length - 1];' +
  364. * 'mailClient.getComposeWindowWidget().onload(callback);');
  365. * driver.switchTo().frame('composeWidget');
  366. * driver.findElement(By.id('to')).sendKeys('dog@example.com');
  367. *
  368. * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
  369. * this example, the inject script is specified with a function literal. When
  370. * using this format, the function is converted to a string for injection, so it
  371. * should not reference any symbols not defined in the scope of the page under
  372. * test.
  373. *
  374. * driver.executeAsyncScript(function() {
  375. * var callback = arguments[arguments.length - 1];
  376. * var xhr = new XMLHttpRequest();
  377. * xhr.open("GET", "/resource/data.json", true);
  378. * xhr.onreadystatechange = function() {
  379. * if (xhr.readyState == 4) {
  380. * callback(xhr.responseText);
  381. * }
  382. * };
  383. * xhr.send('');
  384. * }).then(function(str) {
  385. * console.log(JSON.parse(str)['food']);
  386. * });
  387. *
  388. * @param {!(string|Function)} script The script to execute.
  389. * @param {...*} var_args The arguments to pass to the script.
  390. * @return {!promise.Thenable<T>} A promise that will resolve to the
  391. * scripts return value.
  392. * @template T
  393. */
  394. executeAsyncScript(script, var_args) {}
  395. /**
  396. * Schedules a command to execute a custom function.
  397. * @param {function(...): (T|IThenable<T>)} fn The function to execute.
  398. * @param {Object=} opt_scope The object in whose scope to execute the function.
  399. * @param {...*} var_args Any arguments to pass to the function.
  400. * @return {!promise.Thenable<T>} A promise that will be resolved'
  401. * with the function's result.
  402. * @template T
  403. */
  404. call(fn, opt_scope, var_args) {}
  405. /**
  406. * Schedules a command to wait for a condition to hold. The condition may be
  407. * specified by a {@link Condition}, as a custom function, or as any
  408. * promise-like thenable.
  409. *
  410. * For a {@link Condition} or function, the wait will repeatedly
  411. * evaluate the condition until it returns a truthy value. If any errors occur
  412. * while evaluating the condition, they will be allowed to propagate. In the
  413. * event a condition returns a {@link promise.Promise promise}, the polling
  414. * loop will wait for it to be resolved and use the resolved value for whether
  415. * the condition has been satisfied. Note the resolution time for a promise
  416. * is factored into whether a wait has timed out.
  417. *
  418. * Note, if the provided condition is a {@link WebElementCondition}, then
  419. * the wait will return a {@link WebElementPromise} that will resolve to the
  420. * element that satisfied the condition.
  421. *
  422. * _Example:_ waiting up to 10 seconds for an element to be present on the
  423. * page.
  424. *
  425. * var button = driver.wait(until.elementLocated(By.id('foo')), 10000);
  426. * button.click();
  427. *
  428. * This function may also be used to block the command flow on the resolution
  429. * of any thenable promise object. When given a promise, the command will
  430. * simply wait for its resolution before completing. A timeout may be provided
  431. * to fail the command if the promise does not resolve before the timeout
  432. * expires.
  433. *
  434. * _Example:_ Suppose you have a function, `startTestServer`, that returns a
  435. * promise for when a server is ready for requests. You can block a WebDriver
  436. * client on this promise with:
  437. *
  438. * var started = startTestServer();
  439. * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
  440. * driver.get(getServerUrl());
  441. *
  442. * @param {!(IThenable<T>|
  443. * Condition<T>|
  444. * function(!WebDriver): T)} condition The condition to
  445. * wait on, defined as a promise, condition object, or a function to
  446. * evaluate as a condition.
  447. * @param {number=} opt_timeout How long to wait for the condition to be true.
  448. * @param {string=} opt_message An optional message to use if the wait times
  449. * out.
  450. * @return {!(promise.Thenable<T>|WebElementPromise)} A promise that will be
  451. * resolved with the first truthy value returned by the condition
  452. * function, or rejected if the condition times out. If the input
  453. * input condition is an instance of a {@link WebElementCondition},
  454. * the returned value will be a {@link WebElementPromise}.
  455. * @throws {TypeError} if the provided `condition` is not a valid type.
  456. * @template T
  457. */
  458. wait(condition, opt_timeout, opt_message) {}
  459. /**
  460. * Schedules a command to make the driver sleep for the given amount of time.
  461. * @param {number} ms The amount of time, in milliseconds, to sleep.
  462. * @return {!promise.Thenable<void>} A promise that will be resolved
  463. * when the sleep has finished.
  464. */
  465. sleep(ms) {}
  466. /**
  467. * Schedules a command to retrieve the current window handle.
  468. * @return {!promise.Thenable<string>} A promise that will be
  469. * resolved with the current window handle.
  470. */
  471. getWindowHandle() {}
  472. /**
  473. * Schedules a command to retrieve the current list of available window handles.
  474. * @return {!promise.Thenable<!Array<string>>} A promise that will
  475. * be resolved with an array of window handles.
  476. */
  477. getAllWindowHandles() {}
  478. /**
  479. * Schedules a command to retrieve the current page's source. The page source
  480. * returned is a representation of the underlying DOM: do not expect it to be
  481. * formatted or escaped in the same way as the response sent from the web
  482. * server.
  483. * @return {!promise.Thenable<string>} A promise that will be
  484. * resolved with the current page source.
  485. */
  486. getPageSource() {}
  487. /**
  488. * Schedules a command to close the current window.
  489. * @return {!promise.Thenable<void>} A promise that will be resolved
  490. * when this command has completed.
  491. */
  492. close() {}
  493. /**
  494. * Schedules a command to navigate to the given URL.
  495. * @param {string} url The fully qualified URL to open.
  496. * @return {!promise.Thenable<void>} A promise that will be resolved
  497. * when the document has finished loading.
  498. */
  499. get(url) {}
  500. /**
  501. * Schedules a command to retrieve the URL of the current page.
  502. * @return {!promise.Thenable<string>} A promise that will be
  503. * resolved with the current URL.
  504. */
  505. getCurrentUrl() {}
  506. /**
  507. * Schedules a command to retrieve the current page's title.
  508. * @return {!promise.Thenable<string>} A promise that will be
  509. * resolved with the current page's title.
  510. */
  511. getTitle() {}
  512. /**
  513. * Schedule a command to find an element on the page. If the element cannot be
  514. * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned
  515. * by the driver. Unlike other commands, this error cannot be suppressed. In
  516. * other words, scheduling a command to find an element doubles as an assert
  517. * that the element is present on the page. To test whether an element is
  518. * present on the page, use {@link #findElements}:
  519. *
  520. * driver.findElements(By.id('foo'))
  521. * .then(found => console.log('Element found? %s', !!found.length));
  522. *
  523. * The search criteria for an element may be defined using one of the
  524. * factories in the {@link webdriver.By} namespace, or as a short-hand
  525. * {@link webdriver.By.Hash} object. For example, the following two statements
  526. * are equivalent:
  527. *
  528. * var e1 = driver.findElement(By.id('foo'));
  529. * var e2 = driver.findElement({id:'foo'});
  530. *
  531. * You may also provide a custom locator function, which takes as input this
  532. * instance and returns a {@link WebElement}, or a promise that will resolve
  533. * to a WebElement. If the returned promise resolves to an array of
  534. * WebElements, WebDriver will use the first element. For example, to find the
  535. * first visible link on a page, you could write:
  536. *
  537. * var link = driver.findElement(firstVisibleLink);
  538. *
  539. * function firstVisibleLink(driver) {
  540. * var links = driver.findElements(By.tagName('a'));
  541. * return promise.filter(links, function(link) {
  542. * return link.isDisplayed();
  543. * });
  544. * }
  545. *
  546. * @param {!(by.By|Function)} locator The locator to use.
  547. * @return {!WebElementPromise} A WebElement that can be used to issue
  548. * commands against the located element. If the element is not found, the
  549. * element will be invalidated and all scheduled commands aborted.
  550. */
  551. findElement(locator) {}
  552. /**
  553. * Schedule a command to search for multiple elements on the page.
  554. *
  555. * @param {!(by.By|Function)} locator The locator to use.
  556. * @return {!promise.Thenable<!Array<!WebElement>>} A
  557. * promise that will resolve to an array of WebElements.
  558. */
  559. findElements(locator) {}
  560. /**
  561. * Schedule a command to take a screenshot. The driver makes a best effort to
  562. * return a screenshot of the following, in order of preference:
  563. *
  564. * 1. Entire page
  565. * 2. Current window
  566. * 3. Visible portion of the current frame
  567. * 4. The entire display containing the browser
  568. *
  569. * @return {!promise.Thenable<string>} A promise that will be
  570. * resolved to the screenshot as a base-64 encoded PNG.
  571. */
  572. takeScreenshot() {}
  573. /**
  574. * @return {!Options} The options interface for this instance.
  575. */
  576. manage() {}
  577. /**
  578. * @return {!Navigation} The navigation interface for this instance.
  579. */
  580. navigate() {}
  581. /**
  582. * @return {!TargetLocator} The target locator interface for this
  583. * instance.
  584. */
  585. switchTo() {}
  586. }
  587. /**
  588. * Each WebDriver instance provides automated control over a browser session.
  589. *
  590. * @implements {IWebDriver}
  591. */
  592. class WebDriver {
  593. /**
  594. * @param {!(Session|IThenable<!Session>)} session Either a known session or a
  595. * promise that will be resolved to a session.
  596. * @param {!command.Executor} executor The executor to use when sending
  597. * commands to the browser.
  598. * @param {promise.ControlFlow=} opt_flow The flow to
  599. * schedule commands through. Defaults to the active flow object.
  600. * @param {(function(this: void): ?)=} opt_onQuit A function to call, if any,
  601. * when the session is terminated.
  602. */
  603. constructor(session, executor, opt_flow, opt_onQuit) {
  604. /** @private {!promise.ControlFlow} */
  605. this.flow_ = opt_flow || promise.controlFlow();
  606. /** @private {!promise.Thenable<!Session>} */
  607. this.session_ = this.flow_.promise(resolve => resolve(session));
  608. /** @private {!command.Executor} */
  609. this.executor_ = executor;
  610. /** @private {input.FileDetector} */
  611. this.fileDetector_ = null;
  612. /** @private @const {(function(this: void): ?|undefined)} */
  613. this.onQuit_ = opt_onQuit;
  614. }
  615. /**
  616. * Creates a new WebDriver client for an existing session.
  617. * @param {!command.Executor} executor Command executor to use when querying
  618. * for session details.
  619. * @param {string} sessionId ID of the session to attach to.
  620. * @param {promise.ControlFlow=} opt_flow The control flow all
  621. * driver commands should execute under. Defaults to the
  622. * {@link promise.controlFlow() currently active} control flow.
  623. * @return {!WebDriver} A new client for the specified session.
  624. */
  625. static attachToSession(executor, sessionId, opt_flow) {
  626. let flow = opt_flow || promise.controlFlow();
  627. let cmd = new command.Command(command.Name.DESCRIBE_SESSION)
  628. .setParameter('sessionId', sessionId);
  629. let session = flow.execute(
  630. () => executeCommand(executor, cmd).catch(err => {
  631. // The DESCRIBE_SESSION command is not supported by the W3C spec, so
  632. // if we get back an unknown command, just return a session with
  633. // unknown capabilities.
  634. if (err instanceof error.UnknownCommandError) {
  635. return new Session(sessionId, new Capabilities);
  636. }
  637. throw err;
  638. }),
  639. 'WebDriver.attachToSession()');
  640. return new WebDriver(session, executor, flow);
  641. }
  642. /**
  643. * Creates a new WebDriver session.
  644. *
  645. * By default, the requested session `capabilities` are merely "desired" and
  646. * the remote end will still create a new session even if it cannot satisfy
  647. * all of the requested capabilities. You can query which capabilities a
  648. * session actually has using the
  649. * {@linkplain #getCapabilities() getCapabilities()} method on the returned
  650. * WebDriver instance.
  651. *
  652. * To define _required capabilities_, provide the `capabilities` as an object
  653. * literal with `required` and `desired` keys. The `desired` key may be
  654. * omitted if all capabilities are required, and vice versa. If the server
  655. * cannot create a session with all of the required capabilities, it will
  656. * return an {@linkplain error.SessionNotCreatedError}.
  657. *
  658. * let required = new Capabilities().set('browserName', 'firefox');
  659. * let desired = new Capabilities().set('version', '45');
  660. * let driver = WebDriver.createSession(executor, {required, desired});
  661. *
  662. * This function will always return a WebDriver instance. If there is an error
  663. * creating the session, such as the aforementioned SessionNotCreatedError,
  664. * the driver will have a rejected {@linkplain #getSession session} promise.
  665. * It is recommended that this promise is left _unhandled_ so it will
  666. * propagate through the {@linkplain promise.ControlFlow control flow} and
  667. * cause subsequent commands to fail.
  668. *
  669. * let required = Capabilities.firefox();
  670. * let driver = WebDriver.createSession(executor, {required});
  671. *
  672. * // If the createSession operation failed, then this command will also
  673. * // also fail, propagating the creation failure.
  674. * driver.get('http://www.google.com').catch(e => console.log(e));
  675. *
  676. * @param {!command.Executor} executor The executor to create the new session
  677. * with.
  678. * @param {(!Capabilities|
  679. * {desired: (Capabilities|undefined),
  680. * required: (Capabilities|undefined)})} capabilities The desired
  681. * capabilities for the new session.
  682. * @param {promise.ControlFlow=} opt_flow The control flow all driver
  683. * commands should execute under, including the initial session creation.
  684. * Defaults to the {@link promise.controlFlow() currently active}
  685. * control flow.
  686. * @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when
  687. * the newly created session is terminated. This should be used to clean
  688. * up any resources associated with the session.
  689. * @return {!WebDriver} The driver for the newly created session.
  690. */
  691. static createSession(executor, capabilities, opt_flow, opt_onQuit) {
  692. let flow = opt_flow || promise.controlFlow();
  693. let cmd = new command.Command(command.Name.NEW_SESSION);
  694. if (capabilities && (capabilities.desired || capabilities.required)) {
  695. cmd.setParameter('desiredCapabilities', capabilities.desired);
  696. cmd.setParameter('requiredCapabilities', capabilities.required);
  697. } else {
  698. cmd.setParameter('desiredCapabilities', capabilities);
  699. }
  700. let session = flow.execute(
  701. () => executeCommand(executor, cmd),
  702. 'WebDriver.createSession()');
  703. if (typeof opt_onQuit === 'function') {
  704. session = session.catch(err => {
  705. return Promise.resolve(opt_onQuit.call(void 0)).then(_ => {throw err;});
  706. });
  707. }
  708. return new this(session, executor, flow, opt_onQuit);
  709. }
  710. /** @override */
  711. controlFlow() {
  712. return this.flow_;
  713. }
  714. /** @override */
  715. schedule(command, description) {
  716. command.setParameter('sessionId', this.session_);
  717. // If any of the command parameters are rejected promises, those
  718. // rejections may be reported as unhandled before the control flow
  719. // attempts to execute the command. To ensure parameters errors
  720. // propagate through the command itself, we resolve all of the
  721. // command parameters now, but suppress any errors until the ControlFlow
  722. // actually executes the command. This addresses scenarios like catching
  723. // an element not found error in:
  724. //
  725. // driver.findElement(By.id('foo')).click().catch(function(e) {
  726. // if (e instanceof NoSuchElementError) {
  727. // // Do something.
  728. // }
  729. // });
  730. var prepCommand = toWireValue(command.getParameters());
  731. prepCommand.catch(function() {});
  732. var flow = this.flow_;
  733. var executor = this.executor_;
  734. return flow.execute(() => {
  735. // Retrieve resolved command parameters; any previously suppressed errors
  736. // will now propagate up through the control flow as part of the command
  737. // execution.
  738. return prepCommand.then(function(parameters) {
  739. command.setParameters(parameters);
  740. return executor.execute(command);
  741. }).then(value => fromWireValue(this, value));
  742. }, description);
  743. }
  744. /** @override */
  745. setFileDetector(detector) {
  746. this.fileDetector_ = detector;
  747. }
  748. /** @override */
  749. getExecutor() {
  750. return this.executor_;
  751. }
  752. /** @override */
  753. getSession() {
  754. return this.session_;
  755. }
  756. /** @override */
  757. getCapabilities() {
  758. return this.session_.then(s => s.getCapabilities());
  759. }
  760. /** @override */
  761. quit() {
  762. var result = this.schedule(
  763. new command.Command(command.Name.QUIT),
  764. 'WebDriver.quit()');
  765. // Delete our session ID when the quit command finishes; this will allow us
  766. // to throw an error when attempting to use a driver post-quit.
  767. return /** @type {!promise.Thenable} */(promise.finally(result, () => {
  768. this.session_ = this.flow_.promise((_, reject) => {
  769. reject(new error.NoSuchSessionError(
  770. 'This driver instance does not have a valid session ID ' +
  771. '(did you call WebDriver.quit()?) and may no longer be used.'));
  772. });
  773. // Only want the session rejection to bubble if accessed.
  774. this.session_.catch(function() {});
  775. if (this.onQuit_) {
  776. return this.onQuit_.call(void 0);
  777. }
  778. }));
  779. }
  780. /** @override */
  781. actions() {
  782. return new actions.ActionSequence(this);
  783. }
  784. /** @override */
  785. touchActions() {
  786. return new actions.TouchSequence(this);
  787. }
  788. /** @override */
  789. executeScript(script, var_args) {
  790. if (typeof script === 'function') {
  791. script = 'return (' + script + ').apply(null, arguments);';
  792. }
  793. let args =
  794. arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : [];
  795. return this.schedule(
  796. new command.Command(command.Name.EXECUTE_SCRIPT).
  797. setParameter('script', script).
  798. setParameter('args', args),
  799. 'WebDriver.executeScript()');
  800. }
  801. /** @override */
  802. executeAsyncScript(script, var_args) {
  803. if (typeof script === 'function') {
  804. script = 'return (' + script + ').apply(null, arguments);';
  805. }
  806. let args = Array.prototype.slice.call(arguments, 1);
  807. return this.schedule(
  808. new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).
  809. setParameter('script', script).
  810. setParameter('args', args),
  811. 'WebDriver.executeScript()');
  812. }
  813. /** @override */
  814. call(fn, opt_scope, var_args) {
  815. let args = Array.prototype.slice.call(arguments, 2);
  816. return this.flow_.execute(function() {
  817. return promise.fullyResolved(args).then(function(args) {
  818. if (promise.isGenerator(fn)) {
  819. args.unshift(fn, opt_scope);
  820. return promise.consume.apply(null, args);
  821. }
  822. return fn.apply(opt_scope, args);
  823. });
  824. }, 'WebDriver.call(' + (fn.name || 'function') + ')');
  825. }
  826. /** @override */
  827. wait(condition, opt_timeout, opt_message) {
  828. if (promise.isPromise(condition)) {
  829. return this.flow_.wait(
  830. /** @type {!IThenable} */(condition),
  831. opt_timeout, opt_message);
  832. }
  833. var message = opt_message;
  834. var fn = /** @type {!Function} */(condition);
  835. if (condition instanceof Condition) {
  836. message = message || condition.description();
  837. fn = condition.fn;
  838. }
  839. if (typeof fn !== 'function') {
  840. throw TypeError(
  841. 'Wait condition must be a promise-like object, function, or a '
  842. + 'Condition object');
  843. }
  844. var driver = this;
  845. var result = this.flow_.wait(function() {
  846. if (promise.isGenerator(fn)) {
  847. return promise.consume(fn, null, [driver]);
  848. }
  849. return fn(driver);
  850. }, opt_timeout, message);
  851. if (condition instanceof WebElementCondition) {
  852. result = new WebElementPromise(this, result.then(function(value) {
  853. if (!(value instanceof WebElement)) {
  854. throw TypeError(
  855. 'WebElementCondition did not resolve to a WebElement: '
  856. + Object.prototype.toString.call(value));
  857. }
  858. return value;
  859. }));
  860. }
  861. return result;
  862. }
  863. /** @override */
  864. sleep(ms) {
  865. return this.flow_.timeout(ms, 'WebDriver.sleep(' + ms + ')');
  866. }
  867. /** @override */
  868. getWindowHandle() {
  869. return this.schedule(
  870. new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE),
  871. 'WebDriver.getWindowHandle()');
  872. }
  873. /** @override */
  874. getAllWindowHandles() {
  875. return this.schedule(
  876. new command.Command(command.Name.GET_WINDOW_HANDLES),
  877. 'WebDriver.getAllWindowHandles()');
  878. }
  879. /** @override */
  880. getPageSource() {
  881. return this.schedule(
  882. new command.Command(command.Name.GET_PAGE_SOURCE),
  883. 'WebDriver.getPageSource()');
  884. }
  885. /** @override */
  886. close() {
  887. return this.schedule(new command.Command(command.Name.CLOSE),
  888. 'WebDriver.close()');
  889. }
  890. /** @override */
  891. get(url) {
  892. return this.navigate().to(url);
  893. }
  894. /** @override */
  895. getCurrentUrl() {
  896. return this.schedule(
  897. new command.Command(command.Name.GET_CURRENT_URL),
  898. 'WebDriver.getCurrentUrl()');
  899. }
  900. /** @override */
  901. getTitle() {
  902. return this.schedule(new command.Command(command.Name.GET_TITLE),
  903. 'WebDriver.getTitle()');
  904. }
  905. /** @override */
  906. findElement(locator) {
  907. let id;
  908. locator = by.checkedLocator(locator);
  909. if (typeof locator === 'function') {
  910. id = this.findElementInternal_(locator, this);
  911. } else {
  912. let cmd = new command.Command(command.Name.FIND_ELEMENT).
  913. setParameter('using', locator.using).
  914. setParameter('value', locator.value);
  915. id = this.schedule(cmd, 'WebDriver.findElement(' + locator + ')');
  916. }
  917. return new WebElementPromise(this, id);
  918. }
  919. /**
  920. * @param {!Function} locatorFn The locator function to use.
  921. * @param {!(WebDriver|WebElement)} context The search
  922. * context.
  923. * @return {!promise.Thenable<!WebElement>} A
  924. * promise that will resolve to a list of WebElements.
  925. * @private
  926. */
  927. findElementInternal_(locatorFn, context) {
  928. return this.call(() => locatorFn(context)).then(function(result) {
  929. if (Array.isArray(result)) {
  930. result = result[0];
  931. }
  932. if (!(result instanceof WebElement)) {
  933. throw new TypeError('Custom locator did not return a WebElement');
  934. }
  935. return result;
  936. });
  937. }
  938. /** @override */
  939. findElements(locator) {
  940. locator = by.checkedLocator(locator);
  941. if (typeof locator === 'function') {
  942. return this.findElementsInternal_(locator, this);
  943. } else {
  944. let cmd = new command.Command(command.Name.FIND_ELEMENTS).
  945. setParameter('using', locator.using).
  946. setParameter('value', locator.value);
  947. return this.schedule(cmd, 'WebDriver.findElements(' + locator + ')')
  948. .then(
  949. (res) => Array.isArray(res) ? res : [],
  950. (e) => {
  951. if (e instanceof error.NoSuchElementError) {
  952. return [];
  953. }
  954. throw e;
  955. });
  956. }
  957. }
  958. /**
  959. * @param {!Function} locatorFn The locator function to use.
  960. * @param {!(WebDriver|WebElement)} context The search context.
  961. * @return {!promise.Thenable<!Array<!WebElement>>} A promise that
  962. * will resolve to an array of WebElements.
  963. * @private
  964. */
  965. findElementsInternal_(locatorFn, context) {
  966. return this.call(() => locatorFn(context)).then(function(result) {
  967. if (result instanceof WebElement) {
  968. return [result];
  969. }
  970. if (!Array.isArray(result)) {
  971. return [];
  972. }
  973. return result.filter(function(item) {
  974. return item instanceof WebElement;
  975. });
  976. });
  977. }
  978. /** @override */
  979. takeScreenshot() {
  980. return this.schedule(new command.Command(command.Name.SCREENSHOT),
  981. 'WebDriver.takeScreenshot()');
  982. }
  983. /** @override */
  984. manage() {
  985. return new Options(this);
  986. }
  987. /** @override */
  988. navigate() {
  989. return new Navigation(this);
  990. }
  991. /** @override */
  992. switchTo() {
  993. return new TargetLocator(this);
  994. }
  995. }
  996. /**
  997. * Interface for navigating back and forth in the browser history.
  998. *
  999. * This class should never be instantiated directly. Instead, obtain an instance
  1000. * with
  1001. *
  1002. * webdriver.navigate()
  1003. *
  1004. * @see WebDriver#navigate()
  1005. */
  1006. class Navigation {
  1007. /**
  1008. * @param {!WebDriver} driver The parent driver.
  1009. * @private
  1010. */
  1011. constructor(driver) {
  1012. /** @private {!WebDriver} */
  1013. this.driver_ = driver;
  1014. }
  1015. /**
  1016. * Schedules a command to navigate to a new URL.
  1017. * @param {string} url The URL to navigate to.
  1018. * @return {!promise.Thenable<void>} A promise that will be resolved
  1019. * when the URL has been loaded.
  1020. */
  1021. to(url) {
  1022. return this.driver_.schedule(
  1023. new command.Command(command.Name.GET).
  1024. setParameter('url', url),
  1025. 'WebDriver.navigate().to(' + url + ')');
  1026. }
  1027. /**
  1028. * Schedules a command to move backwards in the browser history.
  1029. * @return {!promise.Thenable<void>} A promise that will be resolved
  1030. * when the navigation event has completed.
  1031. */
  1032. back() {
  1033. return this.driver_.schedule(
  1034. new command.Command(command.Name.GO_BACK),
  1035. 'WebDriver.navigate().back()');
  1036. }
  1037. /**
  1038. * Schedules a command to move forwards in the browser history.
  1039. * @return {!promise.Thenable<void>} A promise that will be resolved
  1040. * when the navigation event has completed.
  1041. */
  1042. forward() {
  1043. return this.driver_.schedule(
  1044. new command.Command(command.Name.GO_FORWARD),
  1045. 'WebDriver.navigate().forward()');
  1046. }
  1047. /**
  1048. * Schedules a command to refresh the current page.
  1049. * @return {!promise.Thenable<void>} A promise that will be resolved
  1050. * when the navigation event has completed.
  1051. */
  1052. refresh() {
  1053. return this.driver_.schedule(
  1054. new command.Command(command.Name.REFRESH),
  1055. 'WebDriver.navigate().refresh()');
  1056. }
  1057. }
  1058. /**
  1059. * Provides methods for managing browser and driver state.
  1060. *
  1061. * This class should never be instantiated directly. Instead, obtain an instance
  1062. * with {@linkplain WebDriver#manage() webdriver.manage()}.
  1063. */
  1064. class Options {
  1065. /**
  1066. * @param {!WebDriver} driver The parent driver.
  1067. * @private
  1068. */
  1069. constructor(driver) {
  1070. /** @private {!WebDriver} */
  1071. this.driver_ = driver;
  1072. }
  1073. /**
  1074. * Schedules a command to add a cookie.
  1075. *
  1076. * __Sample Usage:__
  1077. *
  1078. * // Set a basic cookie.
  1079. * driver.manage().addCookie({name: 'foo', value: 'bar'});
  1080. *
  1081. * // Set a cookie that expires in 10 minutes.
  1082. * let expiry = new Date(Date.now() + (10 * 60 * 1000));
  1083. * driver.manage().addCookie({name: 'foo', value: 'bar', expiry});
  1084. *
  1085. * // The cookie expiration may also be specified in seconds since epoch.
  1086. * driver.manage().addCookie({
  1087. * name: 'foo',
  1088. * value: 'bar',
  1089. * expiry: Math.floor(Date.now() / 1000)
  1090. * });
  1091. *
  1092. * @param {!Options.Cookie} spec Defines the cookie to add.
  1093. * @return {!promise.Thenable<void>} A promise that will be resolved
  1094. * when the cookie has been added to the page.
  1095. * @throws {error.InvalidArgumentError} if any of the cookie parameters are
  1096. * invalid.
  1097. * @throws {TypeError} if `spec` is not a cookie object.
  1098. */
  1099. addCookie({name, value, path, domain, secure, httpOnly, expiry}) {
  1100. // We do not allow '=' or ';' in the name.
  1101. if (/[;=]/.test(name)) {
  1102. throw new error.InvalidArgumentError(
  1103. 'Invalid cookie name "' + name + '"');
  1104. }
  1105. // We do not allow ';' in value.
  1106. if (/;/.test(value)) {
  1107. throw new error.InvalidArgumentError(
  1108. 'Invalid cookie value "' + value + '"');
  1109. }
  1110. let cookieString = name + '=' + value +
  1111. (domain ? ';domain=' + domain : '') +
  1112. (path ? ';path=' + path : '') +
  1113. (secure ? ';secure' : '');
  1114. if (typeof expiry === 'number') {
  1115. expiry = Math.floor(expiry);
  1116. cookieString += ';expires=' + new Date(expiry * 1000).toUTCString();
  1117. } else if (expiry instanceof Date) {
  1118. let date = /** @type {!Date} */(expiry);
  1119. expiry = Math.floor(date.getTime() / 1000);
  1120. cookieString += ';expires=' + date.toUTCString();
  1121. }
  1122. return this.driver_.schedule(
  1123. new command.Command(command.Name.ADD_COOKIE).
  1124. setParameter('cookie', {
  1125. 'name': name,
  1126. 'value': value,
  1127. 'path': path,
  1128. 'domain': domain,
  1129. 'secure': !!secure,
  1130. 'httpOnly': !!httpOnly,
  1131. 'expiry': expiry
  1132. }),
  1133. 'WebDriver.manage().addCookie(' + cookieString + ')');
  1134. }
  1135. /**
  1136. * Schedules a command to delete all cookies visible to the current page.
  1137. * @return {!promise.Thenable<void>} A promise that will be resolved
  1138. * when all cookies have been deleted.
  1139. */
  1140. deleteAllCookies() {
  1141. return this.driver_.schedule(
  1142. new command.Command(command.Name.DELETE_ALL_COOKIES),
  1143. 'WebDriver.manage().deleteAllCookies()');
  1144. }
  1145. /**
  1146. * Schedules a command to delete the cookie with the given name. This command
  1147. * is a no-op if there is no cookie with the given name visible to the current
  1148. * page.
  1149. * @param {string} name The name of the cookie to delete.
  1150. * @return {!promise.Thenable<void>} A promise that will be resolved
  1151. * when the cookie has been deleted.
  1152. */
  1153. deleteCookie(name) {
  1154. return this.driver_.schedule(
  1155. new command.Command(command.Name.DELETE_COOKIE).
  1156. setParameter('name', name),
  1157. 'WebDriver.manage().deleteCookie(' + name + ')');
  1158. }
  1159. /**
  1160. * Schedules a command to retrieve all cookies visible to the current page.
  1161. * Each cookie will be returned as a JSON object as described by the WebDriver
  1162. * wire protocol.
  1163. * @return {!promise.Thenable<!Array<!Options.Cookie>>} A promise that will be
  1164. * resolved with the cookies visible to the current browsing context.
  1165. */
  1166. getCookies() {
  1167. return this.driver_.schedule(
  1168. new command.Command(command.Name.GET_ALL_COOKIES),
  1169. 'WebDriver.manage().getCookies()');
  1170. }
  1171. /**
  1172. * Schedules a command to retrieve the cookie with the given name. Returns null
  1173. * if there is no such cookie. The cookie will be returned as a JSON object as
  1174. * described by the WebDriver wire protocol.
  1175. *
  1176. * @param {string} name The name of the cookie to retrieve.
  1177. * @return {!promise.Thenable<?Options.Cookie>} A promise that will be resolved
  1178. * with the named cookie, or `null` if there is no such cookie.
  1179. */
  1180. getCookie(name) {
  1181. return this.getCookies().then(function(cookies) {
  1182. for (let cookie of cookies) {
  1183. if (cookie && cookie['name'] === name) {
  1184. return cookie;
  1185. }
  1186. }
  1187. return null;
  1188. });
  1189. }
  1190. /**
  1191. * Schedules a command to fetch the timeouts currently configured for the
  1192. * current session.
  1193. *
  1194. * @return {!promise.Thenable<{script: number,
  1195. * pageLoad: number,
  1196. * implicit: number}>} A promise that will be
  1197. * resolved with the timeouts currently configured for the current
  1198. * session.
  1199. * @see #setTimeouts()
  1200. */
  1201. getTimeouts() {
  1202. return this.driver_.schedule(
  1203. new command.Command(command.Name.GET_TIMEOUT),
  1204. `WebDriver.manage().getTimeouts()`)
  1205. }
  1206. /**
  1207. * Schedules a command to set timeout durations associated with the current
  1208. * session.
  1209. *
  1210. * The following timeouts are supported (all timeouts are specified in
  1211. * milliseconds):
  1212. *
  1213. * - `implicit` specifies the maximum amount of time to wait for an element
  1214. * locator to succeed when {@linkplain WebDriver#findElement locating}
  1215. * {@linkplain WebDriver#findElements elements} on the page.
  1216. * Defaults to 0 milliseconds.
  1217. *
  1218. * - `pageLoad` specifies the maximum amount of time to wait for a page to
  1219. * finishing loading. Defaults to 300000 milliseconds.
  1220. *
  1221. * - `script` specifies the maximum amount of time to wait for an
  1222. * {@linkplain WebDriver#executeScript evaluated script} to run. If set to
  1223. * `null`, the script timeout will be indefinite.
  1224. * Defaults to 30000 milliseconds.
  1225. *
  1226. * @param {{script: (number|null|undefined),
  1227. * pageLoad: (number|null|undefined),
  1228. * implicit: (number|null|undefined)}} conf
  1229. * The desired timeout configuration.
  1230. * @return {!promise.Thenable<void>} A promise that will be resolved when the
  1231. * timeouts have been set.
  1232. * @throws {!TypeError} if an invalid options object is provided.
  1233. * @see #getTimeouts()
  1234. * @see <https://w3c.github.io/webdriver/webdriver-spec.html#dfn-set-timeouts>
  1235. */
  1236. setTimeouts({script, pageLoad, implicit} = {}) {
  1237. let cmd = new command.Command(command.Name.SET_TIMEOUT);
  1238. let valid = false;
  1239. function setParam(key, value) {
  1240. if (value === null || typeof value === 'number') {
  1241. valid = true;
  1242. cmd.setParameter(key, value);
  1243. } else if (typeof value !== 'undefined') {
  1244. throw TypeError(
  1245. 'invalid timeouts configuration:'
  1246. + ` expected "${key}" to be a number, got ${typeof value}`);
  1247. }
  1248. }
  1249. setParam('implicit', implicit);
  1250. setParam('pageLoad', pageLoad);
  1251. setParam('script', script);
  1252. if (valid) {
  1253. return this.driver_.schedule(cmd, `WebDriver.manage().setTimeouts()`)
  1254. .catch(() => {
  1255. // Fallback to the legacy method.
  1256. let cmds = [];
  1257. if (typeof script === 'number') {
  1258. cmds.push(legacyTimeout(this.driver_, 'script', script));
  1259. }
  1260. if (typeof implicit === 'number') {
  1261. cmds.push(legacyTimeout(this.driver_, 'implicit', implicit));
  1262. }
  1263. if (typeof pageLoad === 'number') {
  1264. cmds.push(legacyTimeout(this.driver_, 'page load', pageLoad));
  1265. }
  1266. return Promise.all(cmds);
  1267. });
  1268. }
  1269. throw TypeError('no timeouts specified');
  1270. }
  1271. /**
  1272. * @return {!Logs} The interface for managing driver
  1273. * logs.
  1274. */
  1275. logs() {
  1276. return new Logs(this.driver_);
  1277. }
  1278. /**
  1279. * @return {!Timeouts} The interface for managing driver timeouts.
  1280. * @deprecated Use {@link #setTimeouts()} instead.
  1281. */
  1282. timeouts() {
  1283. return new Timeouts(this.driver_);
  1284. }
  1285. /**
  1286. * @return {!Window} The interface for managing the current window.
  1287. */
  1288. window() {
  1289. return new Window(this.driver_);
  1290. }
  1291. }
  1292. /**
  1293. * @param {!WebDriver} driver
  1294. * @param {string} type
  1295. * @param {number} ms
  1296. * @return {!promise.Thenable<void>}
  1297. */
  1298. function legacyTimeout(driver, type, ms) {
  1299. return driver.schedule(
  1300. new command.Command(command.Name.SET_TIMEOUT)
  1301. .setParameter('type', type)
  1302. .setParameter('ms', ms),
  1303. `WebDriver.manage().setTimeouts({${type}: ${ms}})`);
  1304. }
  1305. /**
  1306. * A record object describing a browser cookie.
  1307. *
  1308. * @record
  1309. */
  1310. Options.Cookie = function() {};
  1311. /**
  1312. * The name of the cookie.
  1313. *
  1314. * @type {string}
  1315. */
  1316. Options.Cookie.prototype.name;
  1317. /**
  1318. * The cookie value.
  1319. *
  1320. * @type {string}
  1321. */
  1322. Options.Cookie.prototype.value;
  1323. /**
  1324. * The cookie path. Defaults to "/" when adding a cookie.
  1325. *
  1326. * @type {(string|undefined)}
  1327. */
  1328. Options.Cookie.prototype.path;
  1329. /**
  1330. * The domain the cookie is visible to. Defaults to the current browsing
  1331. * context's document's URL when adding a cookie.
  1332. *
  1333. * @type {(string|undefined)}
  1334. */
  1335. Options.Cookie.prototype.domain;
  1336. /**
  1337. * Whether the cookie is a secure cookie. Defaults to false when adding a new
  1338. * cookie.
  1339. *
  1340. * @type {(boolean|undefined)}
  1341. */
  1342. Options.Cookie.prototype.secure;
  1343. /**
  1344. * Whether the cookie is an HTTP only cookie. Defaults to false when adding a
  1345. * new cookie.
  1346. *
  1347. * @type {(boolean|undefined)}
  1348. */
  1349. Options.Cookie.prototype.httpOnly;
  1350. /**
  1351. * When the cookie expires.
  1352. *
  1353. * When {@linkplain Options#addCookie() adding a cookie}, this may be specified
  1354. * as a {@link Date} object, or in _seconds_ since Unix epoch (January 1, 1970).
  1355. *
  1356. * The expiry is always returned in seconds since epoch when
  1357. * {@linkplain Options#getCookies() retrieving cookies} from the browser.
  1358. *
  1359. * @type {(!Date|number|undefined)}
  1360. */
  1361. Options.Cookie.prototype.expiry;
  1362. /**
  1363. * An interface for managing timeout behavior for WebDriver instances.
  1364. *
  1365. * This class should never be instantiated directly. Instead, obtain an instance
  1366. * with
  1367. *
  1368. * webdriver.manage().timeouts()
  1369. *
  1370. * @deprecated This has been deprecated in favor of
  1371. * {@link Options#setTimeouts()}, which supports setting multiple timeouts
  1372. * at once.
  1373. * @see WebDriver#manage()
  1374. * @see Options#timeouts()
  1375. */
  1376. class Timeouts {
  1377. /**
  1378. * @param {!WebDriver} driver The parent driver.
  1379. * @private
  1380. */
  1381. constructor(driver) {
  1382. /** @private {!WebDriver} */
  1383. this.driver_ = driver;
  1384. }
  1385. /**
  1386. * Specifies the amount of time the driver should wait when searching for an
  1387. * element if it is not immediately present.
  1388. *
  1389. * When searching for a single element, the driver should poll the page
  1390. * until the element has been found, or this timeout expires before failing
  1391. * with a {@link bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching
  1392. * for multiple elements, the driver should poll the page until at least one
  1393. * element has been found or this timeout has expired.
  1394. *
  1395. * Setting the wait timeout to 0 (its default value), disables implicit
  1396. * waiting.
  1397. *
  1398. * Increasing the implicit wait timeout should be used judiciously as it
  1399. * will have an adverse effect on test run time, especially when used with
  1400. * slower location strategies like XPath.
  1401. *
  1402. * @param {number} ms The amount of time to wait, in milliseconds.
  1403. * @return {!promise.Thenable<void>} A promise that will be resolved
  1404. * when the implicit wait timeout has been set.
  1405. * @deprecated Use {@link Options#setTimeouts()
  1406. * driver.manage().setTimeouts({implicit: ms})}.
  1407. */
  1408. implicitlyWait(ms) {
  1409. return this.driver_.manage().setTimeouts({implicit: ms});
  1410. }
  1411. /**
  1412. * Sets the amount of time to wait, in milliseconds, for an asynchronous
  1413. * script to finish execution before returning an error. If the timeout is
  1414. * less than or equal to 0, the script will be allowed to run indefinitely.
  1415. *
  1416. * @param {number} ms The amount of time to wait, in milliseconds.
  1417. * @return {!promise.Thenable<void>} A promise that will be resolved
  1418. * when the script timeout has been set.
  1419. * @deprecated Use {@link Options#setTimeouts()
  1420. * driver.manage().setTimeouts({script: ms})}.
  1421. */
  1422. setScriptTimeout(ms) {
  1423. return this.driver_.manage().setTimeouts({script: ms});
  1424. }
  1425. /**
  1426. * Sets the amount of time to wait for a page load to complete before
  1427. * returning an error. If the timeout is negative, page loads may be
  1428. * indefinite.
  1429. *
  1430. * @param {number} ms The amount of time to wait, in milliseconds.
  1431. * @return {!promise.Thenable<void>} A promise that will be resolved
  1432. * when the timeout has been set.
  1433. * @deprecated Use {@link Options#setTimeouts()
  1434. * driver.manage().setTimeouts({pageLoad: ms})}.
  1435. */
  1436. pageLoadTimeout(ms) {
  1437. return this.driver_.manage().setTimeouts({pageLoad: ms});
  1438. }
  1439. }
  1440. /**
  1441. * An interface for managing the current window.
  1442. *
  1443. * This class should never be instantiated directly. Instead, obtain an instance
  1444. * with
  1445. *
  1446. * webdriver.manage().window()
  1447. *
  1448. * @see WebDriver#manage()
  1449. * @see Options#window()
  1450. */
  1451. class Window {
  1452. /**
  1453. * @param {!WebDriver} driver The parent driver.
  1454. * @private
  1455. */
  1456. constructor(driver) {
  1457. /** @private {!WebDriver} */
  1458. this.driver_ = driver;
  1459. }
  1460. /**
  1461. * Retrieves the window's current position, relative to the top left corner of
  1462. * the screen.
  1463. * @return {!promise.Thenable<{x: number, y: number}>} A promise
  1464. * that will be resolved with the window's position in the form of a
  1465. * {x:number, y:number} object literal.
  1466. */
  1467. getPosition() {
  1468. return this.driver_.schedule(
  1469. new command.Command(command.Name.GET_WINDOW_POSITION).
  1470. setParameter('windowHandle', 'current'),
  1471. 'WebDriver.manage().window().getPosition()');
  1472. }
  1473. /**
  1474. * Repositions the current window.
  1475. * @param {number} x The desired horizontal position, relative to the left
  1476. * side of the screen.
  1477. * @param {number} y The desired vertical position, relative to the top of the
  1478. * of the screen.
  1479. * @return {!promise.Thenable<void>} A promise that will be resolved
  1480. * when the command has completed.
  1481. */
  1482. setPosition(x, y) {
  1483. return this.driver_.schedule(
  1484. new command.Command(command.Name.SET_WINDOW_POSITION).
  1485. setParameter('windowHandle', 'current').
  1486. setParameter('x', x).
  1487. setParameter('y', y),
  1488. 'WebDriver.manage().window().setPosition(' + x + ', ' + y + ')');
  1489. }
  1490. /**
  1491. * Retrieves the window's current size.
  1492. * @return {!promise.Thenable<{width: number, height: number}>} A
  1493. * promise that will be resolved with the window's size in the form of a
  1494. * {width:number, height:number} object literal.
  1495. */
  1496. getSize() {
  1497. return this.driver_.schedule(
  1498. new command.Command(command.Name.GET_WINDOW_SIZE).
  1499. setParameter('windowHandle', 'current'),
  1500. 'WebDriver.manage().window().getSize()');
  1501. }
  1502. /**
  1503. * Resizes the current window.
  1504. * @param {number} width The desired window width.
  1505. * @param {number} height The desired window height.
  1506. * @return {!promise.Thenable<void>} A promise that will be resolved
  1507. * when the command has completed.
  1508. */
  1509. setSize(width, height) {
  1510. return this.driver_.schedule(
  1511. new command.Command(command.Name.SET_WINDOW_SIZE).
  1512. setParameter('windowHandle', 'current').
  1513. setParameter('width', width).
  1514. setParameter('height', height),
  1515. 'WebDriver.manage().window().setSize(' + width + ', ' + height + ')');
  1516. }
  1517. /**
  1518. * Maximizes the current window.
  1519. * @return {!promise.Thenable<void>} A promise that will be resolved
  1520. * when the command has completed.
  1521. */
  1522. maximize() {
  1523. return this.driver_.schedule(
  1524. new command.Command(command.Name.MAXIMIZE_WINDOW).
  1525. setParameter('windowHandle', 'current'),
  1526. 'WebDriver.manage().window().maximize()');
  1527. }
  1528. }
  1529. /**
  1530. * Interface for managing WebDriver log records.
  1531. *
  1532. * This class should never be instantiated directly. Instead, obtain an
  1533. * instance with
  1534. *
  1535. * webdriver.manage().logs()
  1536. *
  1537. * @see WebDriver#manage()
  1538. * @see Options#logs()
  1539. */
  1540. class Logs {
  1541. /**
  1542. * @param {!WebDriver} driver The parent driver.
  1543. * @private
  1544. */
  1545. constructor(driver) {
  1546. /** @private {!WebDriver} */
  1547. this.driver_ = driver;
  1548. }
  1549. /**
  1550. * Fetches available log entries for the given type.
  1551. *
  1552. * Note that log buffers are reset after each call, meaning that available
  1553. * log entries correspond to those entries not yet returned for a given log
  1554. * type. In practice, this means that this call will return the available log
  1555. * entries since the last call, or from the start of the session.
  1556. *
  1557. * @param {!logging.Type} type The desired log type.
  1558. * @return {!promise.Thenable<!Array.<!logging.Entry>>} A
  1559. * promise that will resolve to a list of log entries for the specified
  1560. * type.
  1561. */
  1562. get(type) {
  1563. let cmd = new command.Command(command.Name.GET_LOG).
  1564. setParameter('type', type);
  1565. return this.driver_.schedule(
  1566. cmd, 'WebDriver.manage().logs().get(' + type + ')').
  1567. then(function(entries) {
  1568. return entries.map(function(entry) {
  1569. if (!(entry instanceof logging.Entry)) {
  1570. return new logging.Entry(
  1571. entry['level'], entry['message'], entry['timestamp'],
  1572. entry['type']);
  1573. }
  1574. return entry;
  1575. });
  1576. });
  1577. }
  1578. /**
  1579. * Retrieves the log types available to this driver.
  1580. * @return {!promise.Thenable<!Array<!logging.Type>>} A
  1581. * promise that will resolve to a list of available log types.
  1582. */
  1583. getAvailableLogTypes() {
  1584. return this.driver_.schedule(
  1585. new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES),
  1586. 'WebDriver.manage().logs().getAvailableLogTypes()');
  1587. }
  1588. }
  1589. /**
  1590. * An interface for changing the focus of the driver to another frame or window.
  1591. *
  1592. * This class should never be instantiated directly. Instead, obtain an
  1593. * instance with
  1594. *
  1595. * webdriver.switchTo()
  1596. *
  1597. * @see WebDriver#switchTo()
  1598. */
  1599. class TargetLocator {
  1600. /**
  1601. * @param {!WebDriver} driver The parent driver.
  1602. * @private
  1603. */
  1604. constructor(driver) {
  1605. /** @private {!WebDriver} */
  1606. this.driver_ = driver;
  1607. }
  1608. /**
  1609. * Schedules a command retrieve the {@code document.activeElement} element on
  1610. * the current document, or {@code document.body} if activeElement is not
  1611. * available.
  1612. * @return {!WebElementPromise} The active element.
  1613. */
  1614. activeElement() {
  1615. var id = this.driver_.schedule(
  1616. new command.Command(command.Name.GET_ACTIVE_ELEMENT),
  1617. 'WebDriver.switchTo().activeElement()');
  1618. return new WebElementPromise(this.driver_, id);
  1619. }
  1620. /**
  1621. * Schedules a command to switch focus of all future commands to the topmost
  1622. * frame on the page.
  1623. * @return {!promise.Thenable<void>} A promise that will be resolved
  1624. * when the driver has changed focus to the default content.
  1625. */
  1626. defaultContent() {
  1627. return this.driver_.schedule(
  1628. new command.Command(command.Name.SWITCH_TO_FRAME).
  1629. setParameter('id', null),
  1630. 'WebDriver.switchTo().defaultContent()');
  1631. }
  1632. /**
  1633. * Schedules a command to switch the focus of all future commands to another
  1634. * frame on the page. The target frame may be specified as one of the
  1635. * following:
  1636. *
  1637. * - A number that specifies a (zero-based) index into [window.frames](
  1638. * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
  1639. * - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
  1640. * DOM element.
  1641. * - The `null` value, to select the topmost frame on the page. Passing `null`
  1642. * is the same as calling {@link #defaultContent defaultContent()}.
  1643. *
  1644. * If the specified frame can not be found, the returned promise will be
  1645. * rejected with a {@linkplain error.NoSuchFrameError}.
  1646. *
  1647. * @param {(number|WebElement|null)} id The frame locator.
  1648. * @return {!promise.Thenable<void>} A promise that will be resolved
  1649. * when the driver has changed focus to the specified frame.
  1650. */
  1651. frame(id) {
  1652. return this.driver_.schedule(
  1653. new command.Command(command.Name.SWITCH_TO_FRAME).
  1654. setParameter('id', id),
  1655. 'WebDriver.switchTo().frame(' + id + ')');
  1656. }
  1657. /**
  1658. * Schedules a command to switch the focus of all future commands to another
  1659. * window. Windows may be specified by their {@code window.name} attribute or
  1660. * by its handle (as returned by {@link WebDriver#getWindowHandles}).
  1661. *
  1662. * If the specified window cannot be found, the returned promise will be
  1663. * rejected with a {@linkplain error.NoSuchWindowError}.
  1664. *
  1665. * @param {string} nameOrHandle The name or window handle of the window to
  1666. * switch focus to.
  1667. * @return {!promise.Thenable<void>} A promise that will be resolved
  1668. * when the driver has changed focus to the specified window.
  1669. */
  1670. window(nameOrHandle) {
  1671. return this.driver_.schedule(
  1672. new command.Command(command.Name.SWITCH_TO_WINDOW).
  1673. // "name" supports the legacy drivers. "handle" is the W3C
  1674. // compliant parameter.
  1675. setParameter('name', nameOrHandle).
  1676. setParameter('handle', nameOrHandle),
  1677. 'WebDriver.switchTo().window(' + nameOrHandle + ')');
  1678. }
  1679. /**
  1680. * Schedules a command to change focus to the active modal dialog, such as
  1681. * those opened by `window.alert()`, `window.confirm()`, and
  1682. * `window.prompt()`. The returned promise will be rejected with a
  1683. * {@linkplain error.NoSuchAlertError} if there are no open alerts.
  1684. *
  1685. * @return {!AlertPromise} The open alert.
  1686. */
  1687. alert() {
  1688. var text = this.driver_.schedule(
  1689. new command.Command(command.Name.GET_ALERT_TEXT),
  1690. 'WebDriver.switchTo().alert()');
  1691. var driver = this.driver_;
  1692. return new AlertPromise(driver, text.then(function(text) {
  1693. return new Alert(driver, text);
  1694. }));
  1695. }
  1696. }
  1697. //////////////////////////////////////////////////////////////////////////////
  1698. //
  1699. // WebElement
  1700. //
  1701. //////////////////////////////////////////////////////////////////////////////
  1702. const LEGACY_ELEMENT_ID_KEY = 'ELEMENT';
  1703. const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf';
  1704. /**
  1705. * Represents a DOM element. WebElements can be found by searching from the
  1706. * document root using a {@link WebDriver} instance, or by searching
  1707. * under another WebElement:
  1708. *
  1709. * driver.get('http://www.google.com');
  1710. * var searchForm = driver.findElement(By.tagName('form'));
  1711. * var searchBox = searchForm.findElement(By.name('q'));
  1712. * searchBox.sendKeys('webdriver');
  1713. */
  1714. class WebElement {
  1715. /**
  1716. * @param {!WebDriver} driver the parent WebDriver instance for this element.
  1717. * @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
  1718. * the underlying DOM element.
  1719. */
  1720. constructor(driver, id) {
  1721. /** @private {!WebDriver} */
  1722. this.driver_ = driver;
  1723. /** @private {!promise.Thenable<string>} */
  1724. this.id_ = driver.controlFlow().promise(resolve => resolve(id));
  1725. }
  1726. /**
  1727. * @param {string} id The raw ID.
  1728. * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key.
  1729. * @return {!Object} The element ID for use with WebDriver's wire protocol.
  1730. */
  1731. static buildId(id, opt_noLegacy) {
  1732. return opt_noLegacy
  1733. ? {[ELEMENT_ID_KEY]: id}
  1734. : {[ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id};
  1735. }
  1736. /**
  1737. * Extracts the encoded WebElement ID from the object.
  1738. *
  1739. * @param {?} obj The object to extract the ID from.
  1740. * @return {string} the extracted ID.
  1741. * @throws {TypeError} if the object is not a valid encoded ID.
  1742. */
  1743. static extractId(obj) {
  1744. if (obj && typeof obj === 'object') {
  1745. if (typeof obj[ELEMENT_ID_KEY] === 'string') {
  1746. return obj[ELEMENT_ID_KEY];
  1747. } else if (typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string') {
  1748. return obj[LEGACY_ELEMENT_ID_KEY];
  1749. }
  1750. }
  1751. throw new TypeError('object is not a WebElement ID');
  1752. }
  1753. /**
  1754. * @param {?} obj the object to test.
  1755. * @return {boolean} whether the object is a valid encoded WebElement ID.
  1756. */
  1757. static isId(obj) {
  1758. return obj && typeof obj === 'object'
  1759. && (typeof obj[ELEMENT_ID_KEY] === 'string'
  1760. || typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string');
  1761. }
  1762. /**
  1763. * Compares two WebElements for equality.
  1764. *
  1765. * @param {!WebElement} a A WebElement.
  1766. * @param {!WebElement} b A WebElement.
  1767. * @return {!promise.Thenable<boolean>} A promise that will be
  1768. * resolved to whether the two WebElements are equal.
  1769. */
  1770. static equals(a, b) {
  1771. if (a === b) {
  1772. return a.driver_.controlFlow().promise(resolve => resolve(true));
  1773. }
  1774. let ids = [a.getId(), b.getId()];
  1775. return promise.all(ids).then(function(ids) {
  1776. // If the two element's have the same ID, they should be considered
  1777. // equal. Otherwise, they may still be equivalent, but we'll need to
  1778. // ask the server to check for us.
  1779. if (ids[0] === ids[1]) {
  1780. return true;
  1781. }
  1782. let cmd = new command.Command(command.Name.ELEMENT_EQUALS);
  1783. cmd.setParameter('id', ids[0]);
  1784. cmd.setParameter('other', ids[1]);
  1785. return a.driver_.schedule(cmd, 'WebElement.equals()');
  1786. });
  1787. }
  1788. /** @return {!WebDriver} The parent driver for this instance. */
  1789. getDriver() {
  1790. return this.driver_;
  1791. }
  1792. /**
  1793. * @return {!promise.Thenable<string>} A promise that resolves to
  1794. * the server-assigned opaque ID assigned to this element.
  1795. */
  1796. getId() {
  1797. return this.id_;
  1798. }
  1799. /**
  1800. * @return {!Object} Returns the serialized representation of this WebElement.
  1801. */
  1802. [Symbols.serialize]() {
  1803. return this.getId().then(WebElement.buildId);
  1804. }
  1805. /**
  1806. * Schedules a command that targets this element with the parent WebDriver
  1807. * instance. Will ensure this element's ID is included in the command
  1808. * parameters under the "id" key.
  1809. *
  1810. * @param {!command.Command} command The command to schedule.
  1811. * @param {string} description A description of the command for debugging.
  1812. * @return {!promise.Thenable<T>} A promise that will be resolved
  1813. * with the command result.
  1814. * @template T
  1815. * @see WebDriver#schedule
  1816. * @private
  1817. */
  1818. schedule_(command, description) {
  1819. command.setParameter('id', this);
  1820. return this.driver_.schedule(command, description);
  1821. }
  1822. /**
  1823. * Schedule a command to find a descendant of this element. If the element
  1824. * cannot be found, the returned promise will be rejected with a
  1825. * {@linkplain error.NoSuchElementError NoSuchElementError}.
  1826. *
  1827. * The search criteria for an element may be defined using one of the static
  1828. * factories on the {@link by.By} class, or as a short-hand
  1829. * {@link ./by.ByHash} object. For example, the following two statements
  1830. * are equivalent:
  1831. *
  1832. * var e1 = element.findElement(By.id('foo'));
  1833. * var e2 = element.findElement({id:'foo'});
  1834. *
  1835. * You may also provide a custom locator function, which takes as input this
  1836. * instance and returns a {@link WebElement}, or a promise that will resolve
  1837. * to a WebElement. If the returned promise resolves to an array of
  1838. * WebElements, WebDriver will use the first element. For example, to find the
  1839. * first visible link on a page, you could write:
  1840. *
  1841. * var link = element.findElement(firstVisibleLink);
  1842. *
  1843. * function firstVisibleLink(element) {
  1844. * var links = element.findElements(By.tagName('a'));
  1845. * return promise.filter(links, function(link) {
  1846. * return link.isDisplayed();
  1847. * });
  1848. * }
  1849. *
  1850. * @param {!(by.By|Function)} locator The locator strategy to use when
  1851. * searching for the element.
  1852. * @return {!WebElementPromise} A WebElement that can be used to issue
  1853. * commands against the located element. If the element is not found, the
  1854. * element will be invalidated and all scheduled commands aborted.
  1855. */
  1856. findElement(locator) {
  1857. locator = by.checkedLocator(locator);
  1858. let id;
  1859. if (typeof locator === 'function') {
  1860. id = this.driver_.findElementInternal_(locator, this);
  1861. } else {
  1862. let cmd = new command.Command(
  1863. command.Name.FIND_CHILD_ELEMENT).
  1864. setParameter('using', locator.using).
  1865. setParameter('value', locator.value);
  1866. id = this.schedule_(cmd, 'WebElement.findElement(' + locator + ')');
  1867. }
  1868. return new WebElementPromise(this.driver_, id);
  1869. }
  1870. /**
  1871. * Schedules a command to find all of the descendants of this element that
  1872. * match the given search criteria.
  1873. *
  1874. * @param {!(by.By|Function)} locator The locator strategy to use when
  1875. * searching for the element.
  1876. * @return {!promise.Thenable<!Array<!WebElement>>} A
  1877. * promise that will resolve to an array of WebElements.
  1878. */
  1879. findElements(locator) {
  1880. locator = by.checkedLocator(locator);
  1881. let id;
  1882. if (typeof locator === 'function') {
  1883. return this.driver_.findElementsInternal_(locator, this);
  1884. } else {
  1885. var cmd = new command.Command(
  1886. command.Name.FIND_CHILD_ELEMENTS).
  1887. setParameter('using', locator.using).
  1888. setParameter('value', locator.value);
  1889. return this.schedule_(cmd, 'WebElement.findElements(' + locator + ')')
  1890. .then(result => Array.isArray(result) ? result : []);
  1891. }
  1892. }
  1893. /**
  1894. * Schedules a command to click on this element.
  1895. * @return {!promise.Thenable<void>} A promise that will be resolved
  1896. * when the click command has completed.
  1897. */
  1898. click() {
  1899. return this.schedule_(
  1900. new command.Command(command.Name.CLICK_ELEMENT),
  1901. 'WebElement.click()');
  1902. }
  1903. /**
  1904. * Schedules a command to type a sequence on the DOM element represented by
  1905. * this instance.
  1906. *
  1907. * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
  1908. * processed in the key sequence, that key state is toggled until one of the
  1909. * following occurs:
  1910. *
  1911. * - The modifier key is encountered again in the sequence. At this point the
  1912. * state of the key is toggled (along with the appropriate keyup/down
  1913. * events).
  1914. * - The {@link input.Key.NULL} key is encountered in the sequence. When
  1915. * this key is encountered, all modifier keys current in the down state are
  1916. * released (with accompanying keyup events). The NULL key can be used to
  1917. * simulate common keyboard shortcuts:
  1918. *
  1919. * element.sendKeys("text was",
  1920. * Key.CONTROL, "a", Key.NULL,
  1921. * "now text is");
  1922. * // Alternatively:
  1923. * element.sendKeys("text was",
  1924. * Key.chord(Key.CONTROL, "a"),
  1925. * "now text is");
  1926. *
  1927. * - The end of the key sequence is encountered. When there are no more keys
  1928. * to type, all depressed modifier keys are released (with accompanying
  1929. * keyup events).
  1930. *
  1931. * If this element is a file input ({@code <input type="file">}), the
  1932. * specified key sequence should specify the path to the file to attach to
  1933. * the element. This is analogous to the user clicking "Browse..." and entering
  1934. * the path into the file select dialog.
  1935. *
  1936. * var form = driver.findElement(By.css('form'));
  1937. * var element = form.findElement(By.css('input[type=file]'));
  1938. * element.sendKeys('/path/to/file.txt');
  1939. * form.submit();
  1940. *
  1941. * For uploads to function correctly, the entered path must reference a file
  1942. * on the _browser's_ machine, not the local machine running this script. When
  1943. * running against a remote Selenium server, a {@link input.FileDetector}
  1944. * may be used to transparently copy files to the remote machine before
  1945. * attempting to upload them in the browser.
  1946. *
  1947. * __Note:__ On browsers where native keyboard events are not supported
  1948. * (e.g. Firefox on OS X), key events will be synthesized. Special
  1949. * punctuation keys will be synthesized according to a standard QWERTY en-us
  1950. * keyboard layout.
  1951. *
  1952. * @param {...(number|string|!IThenable<(number|string)>)} var_args The
  1953. * sequence of keys to type. Number keys may be referenced numerically or
  1954. * by string (1 or '1'). All arguments will be joined into a single
  1955. * sequence.
  1956. * @return {!promise.Thenable<void>} A promise that will be resolved
  1957. * when all keys have been typed.
  1958. */
  1959. sendKeys(var_args) {
  1960. let keys = Promise.all(Array.prototype.slice.call(arguments, 0)).
  1961. then(keys => {
  1962. let ret = [];
  1963. keys.forEach(key => {
  1964. let type = typeof key;
  1965. if (type === 'number') {
  1966. key = String(key);
  1967. } else if (type !== 'string') {
  1968. throw TypeError(
  1969. 'each key must be a number of string; got ' + type);
  1970. }
  1971. // The W3C protocol requires keys to be specified as an array where
  1972. // each element is a single key.
  1973. ret.push.apply(ret, key.split(''));
  1974. });
  1975. return ret;
  1976. });
  1977. if (!this.driver_.fileDetector_) {
  1978. return this.schedule_(
  1979. new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
  1980. setParameter('text', keys.then(keys => keys.join(''))).
  1981. setParameter('value', keys),
  1982. 'WebElement.sendKeys()');
  1983. }
  1984. // Suppress unhandled rejection errors until the flow executes the command.
  1985. keys.catch(function() {});
  1986. var element = this;
  1987. return this.getDriver().controlFlow().execute(function() {
  1988. return keys.then(function(keys) {
  1989. return element.driver_.fileDetector_
  1990. .handleFile(element.driver_, keys.join(''));
  1991. }).then(function(keys) {
  1992. return element.schedule_(
  1993. new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
  1994. setParameter('text', keys).
  1995. setParameter('value', keys.split('')),
  1996. 'WebElement.sendKeys()');
  1997. });
  1998. }, 'WebElement.sendKeys()');
  1999. }
  2000. /**
  2001. * Schedules a command to query for the tag/node name of this element.
  2002. * @return {!promise.Thenable<string>} A promise that will be
  2003. * resolved with the element's tag name.
  2004. */
  2005. getTagName() {
  2006. return this.schedule_(
  2007. new command.Command(command.Name.GET_ELEMENT_TAG_NAME),
  2008. 'WebElement.getTagName()');
  2009. }
  2010. /**
  2011. * Schedules a command to query for the computed style of the element
  2012. * represented by this instance. If the element inherits the named style from
  2013. * its parent, the parent will be queried for its value. Where possible, color
  2014. * values will be converted to their hex representation (e.g. #00ff00 instead
  2015. * of rgb(0, 255, 0)).
  2016. *
  2017. * _Warning:_ the value returned will be as the browser interprets it, so
  2018. * it may be tricky to form a proper assertion.
  2019. *
  2020. * @param {string} cssStyleProperty The name of the CSS style property to look
  2021. * up.
  2022. * @return {!promise.Thenable<string>} A promise that will be
  2023. * resolved with the requested CSS value.
  2024. */
  2025. getCssValue(cssStyleProperty) {
  2026. var name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY;
  2027. return this.schedule_(
  2028. new command.Command(name).
  2029. setParameter('propertyName', cssStyleProperty),
  2030. 'WebElement.getCssValue(' + cssStyleProperty + ')');
  2031. }
  2032. /**
  2033. * Schedules a command to query for the value of the given attribute of the
  2034. * element. Will return the current value, even if it has been modified after
  2035. * the page has been loaded. More exactly, this method will return the value
  2036. * of the given attribute, unless that attribute is not present, in which case
  2037. * the value of the property with the same name is returned. If neither value
  2038. * is set, null is returned (for example, the "value" property of a textarea
  2039. * element). The "style" attribute is converted as best can be to a
  2040. * text representation with a trailing semi-colon. The following are deemed to
  2041. * be "boolean" attributes and will return either "true" or null:
  2042. *
  2043. * async, autofocus, autoplay, checked, compact, complete, controls, declare,
  2044. * defaultchecked, defaultselected, defer, disabled, draggable, ended,
  2045. * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
  2046. * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
  2047. * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
  2048. * selected, spellcheck, truespeed, willvalidate
  2049. *
  2050. * Finally, the following commonly mis-capitalized attribute/property names
  2051. * are evaluated as expected:
  2052. *
  2053. * - "class"
  2054. * - "readonly"
  2055. *
  2056. * @param {string} attributeName The name of the attribute to query.
  2057. * @return {!promise.Thenable<?string>} A promise that will be
  2058. * resolved with the attribute's value. The returned value will always be
  2059. * either a string or null.
  2060. */
  2061. getAttribute(attributeName) {
  2062. return this.schedule_(
  2063. new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).
  2064. setParameter('name', attributeName),
  2065. 'WebElement.getAttribute(' + attributeName + ')');
  2066. }
  2067. /**
  2068. * Get the visible (i.e. not hidden by CSS) innerText of this element,
  2069. * including sub-elements, without any leading or trailing whitespace.
  2070. *
  2071. * @return {!promise.Thenable<string>} A promise that will be
  2072. * resolved with the element's visible text.
  2073. */
  2074. getText() {
  2075. return this.schedule_(
  2076. new command.Command(command.Name.GET_ELEMENT_TEXT),
  2077. 'WebElement.getText()');
  2078. }
  2079. /**
  2080. * Schedules a command to compute the size of this element's bounding box, in
  2081. * pixels.
  2082. * @return {!promise.Thenable<{width: number, height: number}>} A
  2083. * promise that will be resolved with the element's size as a
  2084. * {@code {width:number, height:number}} object.
  2085. */
  2086. getSize() {
  2087. return this.schedule_(
  2088. new command.Command(command.Name.GET_ELEMENT_SIZE),
  2089. 'WebElement.getSize()');
  2090. }
  2091. /**
  2092. * Schedules a command to compute the location of this element in page space.
  2093. * @return {!promise.Thenable<{x: number, y: number}>} A promise that
  2094. * will be resolved to the element's location as a
  2095. * {@code {x:number, y:number}} object.
  2096. */
  2097. getLocation() {
  2098. return this.schedule_(
  2099. new command.Command(command.Name.GET_ELEMENT_LOCATION),
  2100. 'WebElement.getLocation()');
  2101. }
  2102. /**
  2103. * Schedules a command to query whether the DOM element represented by this
  2104. * instance is enabled, as dictated by the {@code disabled} attribute.
  2105. * @return {!promise.Thenable<boolean>} A promise that will be
  2106. * resolved with whether this element is currently enabled.
  2107. */
  2108. isEnabled() {
  2109. return this.schedule_(
  2110. new command.Command(command.Name.IS_ELEMENT_ENABLED),
  2111. 'WebElement.isEnabled()');
  2112. }
  2113. /**
  2114. * Schedules a command to query whether this element is selected.
  2115. * @return {!promise.Thenable<boolean>} A promise that will be
  2116. * resolved with whether this element is currently selected.
  2117. */
  2118. isSelected() {
  2119. return this.schedule_(
  2120. new command.Command(command.Name.IS_ELEMENT_SELECTED),
  2121. 'WebElement.isSelected()');
  2122. }
  2123. /**
  2124. * Schedules a command to submit the form containing this element (or this
  2125. * element if it is a FORM element). This command is a no-op if the element is
  2126. * not contained in a form.
  2127. * @return {!promise.Thenable<void>} A promise that will be resolved
  2128. * when the form has been submitted.
  2129. */
  2130. submit() {
  2131. return this.schedule_(
  2132. new command.Command(command.Name.SUBMIT_ELEMENT),
  2133. 'WebElement.submit()');
  2134. }
  2135. /**
  2136. * Schedules a command to clear the `value` of this element. This command has
  2137. * no effect if the underlying DOM element is neither a text INPUT element
  2138. * nor a TEXTAREA element.
  2139. * @return {!promise.Thenable<void>} A promise that will be resolved
  2140. * when the element has been cleared.
  2141. */
  2142. clear() {
  2143. return this.schedule_(
  2144. new command.Command(command.Name.CLEAR_ELEMENT),
  2145. 'WebElement.clear()');
  2146. }
  2147. /**
  2148. * Schedules a command to test whether this element is currently displayed.
  2149. * @return {!promise.Thenable<boolean>} A promise that will be
  2150. * resolved with whether this element is currently visible on the page.
  2151. */
  2152. isDisplayed() {
  2153. return this.schedule_(
  2154. new command.Command(command.Name.IS_ELEMENT_DISPLAYED),
  2155. 'WebElement.isDisplayed()');
  2156. }
  2157. /**
  2158. * Take a screenshot of the visible region encompassed by this element's
  2159. * bounding rectangle.
  2160. *
  2161. * @param {boolean=} opt_scroll Optional argument that indicates whether the
  2162. * element should be scrolled into view before taking a screenshot.
  2163. * Defaults to false.
  2164. * @return {!promise.Thenable<string>} A promise that will be
  2165. * resolved to the screenshot as a base-64 encoded PNG.
  2166. */
  2167. takeScreenshot(opt_scroll) {
  2168. var scroll = !!opt_scroll;
  2169. return this.schedule_(
  2170. new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT)
  2171. .setParameter('scroll', scroll),
  2172. 'WebElement.takeScreenshot(' + scroll + ')');
  2173. }
  2174. }
  2175. /**
  2176. * WebElementPromise is a promise that will be fulfilled with a WebElement.
  2177. * This serves as a forward proxy on WebElement, allowing calls to be
  2178. * scheduled without directly on this instance before the underlying
  2179. * WebElement has been fulfilled. In other words, the following two statements
  2180. * are equivalent:
  2181. *
  2182. * driver.findElement({id: 'my-button'}).click();
  2183. * driver.findElement({id: 'my-button'}).then(function(el) {
  2184. * return el.click();
  2185. * });
  2186. *
  2187. * @implements {promise.CancellableThenable<!WebElement>}
  2188. * @final
  2189. */
  2190. class WebElementPromise extends WebElement {
  2191. /**
  2192. * @param {!WebDriver} driver The parent WebDriver instance for this
  2193. * element.
  2194. * @param {!promise.Thenable<!WebElement>} el A promise
  2195. * that will resolve to the promised element.
  2196. */
  2197. constructor(driver, el) {
  2198. super(driver, 'unused');
  2199. /**
  2200. * Cancel operation is only supported if the wrapped thenable is also
  2201. * cancellable.
  2202. * @param {(string|Error)=} opt_reason
  2203. * @override
  2204. */
  2205. this.cancel = function(opt_reason) {
  2206. if (promise.CancellableThenable.isImplementation(el)) {
  2207. /** @type {!promise.CancellableThenable} */(el).cancel(opt_reason);
  2208. }
  2209. };
  2210. /** @override */
  2211. this.then = el.then.bind(el);
  2212. /** @override */
  2213. this.catch = el.catch.bind(el);
  2214. /**
  2215. * Defers returning the element ID until the wrapped WebElement has been
  2216. * resolved.
  2217. * @override
  2218. */
  2219. this.getId = function() {
  2220. return el.then(function(el) {
  2221. return el.getId();
  2222. });
  2223. };
  2224. }
  2225. }
  2226. promise.CancellableThenable.addImplementation(WebElementPromise);
  2227. //////////////////////////////////////////////////////////////////////////////
  2228. //
  2229. // Alert
  2230. //
  2231. //////////////////////////////////////////////////////////////////////////////
  2232. /**
  2233. * Represents a modal dialog such as {@code alert}, {@code confirm}, or
  2234. * {@code prompt}. Provides functions to retrieve the message displayed with
  2235. * the alert, accept or dismiss the alert, and set the response text (in the
  2236. * case of {@code prompt}).
  2237. */
  2238. class Alert {
  2239. /**
  2240. * @param {!WebDriver} driver The driver controlling the browser this alert
  2241. * is attached to.
  2242. * @param {string} text The message text displayed with this alert.
  2243. */
  2244. constructor(driver, text) {
  2245. /** @private {!WebDriver} */
  2246. this.driver_ = driver;
  2247. /** @private {!promise.Thenable<string>} */
  2248. this.text_ = driver.controlFlow().promise(resolve => resolve(text));
  2249. }
  2250. /**
  2251. * Retrieves the message text displayed with this alert. For instance, if the
  2252. * alert were opened with alert("hello"), then this would return "hello".
  2253. *
  2254. * @return {!promise.Thenable<string>} A promise that will be
  2255. * resolved to the text displayed with this alert.
  2256. */
  2257. getText() {
  2258. return this.text_;
  2259. }
  2260. /**
  2261. * Sets the username and password in an alert prompting for credentials (such
  2262. * as a Basic HTTP Auth prompt). This method will implicitly
  2263. * {@linkplain #accept() submit} the dialog.
  2264. *
  2265. * @param {string} username The username to send.
  2266. * @param {string} password The password to send.
  2267. * @return {!promise.Thenable<void>} A promise that will be resolved when this
  2268. * command has completed.
  2269. */
  2270. authenticateAs(username, password) {
  2271. return this.driver_.schedule(
  2272. new command.Command(command.Name.SET_ALERT_CREDENTIALS),
  2273. 'WebDriver.switchTo().alert()'
  2274. + `.authenticateAs("${username}", "${password}")`);
  2275. }
  2276. /**
  2277. * Accepts this alert.
  2278. *
  2279. * @return {!promise.Thenable<void>} A promise that will be resolved
  2280. * when this command has completed.
  2281. */
  2282. accept() {
  2283. return this.driver_.schedule(
  2284. new command.Command(command.Name.ACCEPT_ALERT),
  2285. 'WebDriver.switchTo().alert().accept()');
  2286. }
  2287. /**
  2288. * Dismisses this alert.
  2289. *
  2290. * @return {!promise.Thenable<void>} A promise that will be resolved
  2291. * when this command has completed.
  2292. */
  2293. dismiss() {
  2294. return this.driver_.schedule(
  2295. new command.Command(command.Name.DISMISS_ALERT),
  2296. 'WebDriver.switchTo().alert().dismiss()');
  2297. }
  2298. /**
  2299. * Sets the response text on this alert. This command will return an error if
  2300. * the underlying alert does not support response text (e.g. window.alert and
  2301. * window.confirm).
  2302. *
  2303. * @param {string} text The text to set.
  2304. * @return {!promise.Thenable<void>} A promise that will be resolved
  2305. * when this command has completed.
  2306. */
  2307. sendKeys(text) {
  2308. return this.driver_.schedule(
  2309. new command.Command(command.Name.SET_ALERT_TEXT).
  2310. setParameter('text', text),
  2311. 'WebDriver.switchTo().alert().sendKeys(' + text + ')');
  2312. }
  2313. }
  2314. /**
  2315. * AlertPromise is a promise that will be fulfilled with an Alert. This promise
  2316. * serves as a forward proxy on an Alert, allowing calls to be scheduled
  2317. * directly on this instance before the underlying Alert has been fulfilled. In
  2318. * other words, the following two statements are equivalent:
  2319. *
  2320. * driver.switchTo().alert().dismiss();
  2321. * driver.switchTo().alert().then(function(alert) {
  2322. * return alert.dismiss();
  2323. * });
  2324. *
  2325. * @implements {promise.CancellableThenable<!webdriver.Alert>}
  2326. * @final
  2327. */
  2328. class AlertPromise extends Alert {
  2329. /**
  2330. * @param {!WebDriver} driver The driver controlling the browser this
  2331. * alert is attached to.
  2332. * @param {!promise.Thenable<!Alert>} alert A thenable
  2333. * that will be fulfilled with the promised alert.
  2334. */
  2335. constructor(driver, alert) {
  2336. super(driver, 'unused');
  2337. /**
  2338. * Cancel operation is only supported if the wrapped thenable is also
  2339. * cancellable.
  2340. * @param {(string|Error)=} opt_reason
  2341. * @override
  2342. */
  2343. this.cancel = function(opt_reason) {
  2344. if (promise.CancellableThenable.isImplementation(alert)) {
  2345. /** @type {!promise.CancellableThenable} */(alert).cancel(opt_reason);
  2346. }
  2347. };
  2348. /** @override */
  2349. this.then = alert.then.bind(alert);
  2350. /** @override */
  2351. this.catch = alert.catch.bind(alert);
  2352. /**
  2353. * Defer returning text until the promised alert has been resolved.
  2354. * @override
  2355. */
  2356. this.getText = function() {
  2357. return alert.then(function(alert) {
  2358. return alert.getText();
  2359. });
  2360. };
  2361. /**
  2362. * Defers action until the alert has been located.
  2363. * @override
  2364. */
  2365. this.authenticateAs = function(username, password) {
  2366. return alert.then(function(alert) {
  2367. return alert.authenticateAs(username, password);
  2368. });
  2369. };
  2370. /**
  2371. * Defers action until the alert has been located.
  2372. * @override
  2373. */
  2374. this.accept = function() {
  2375. return alert.then(function(alert) {
  2376. return alert.accept();
  2377. });
  2378. };
  2379. /**
  2380. * Defers action until the alert has been located.
  2381. * @override
  2382. */
  2383. this.dismiss = function() {
  2384. return alert.then(function(alert) {
  2385. return alert.dismiss();
  2386. });
  2387. };
  2388. /**
  2389. * Defers action until the alert has been located.
  2390. * @override
  2391. */
  2392. this.sendKeys = function(text) {
  2393. return alert.then(function(alert) {
  2394. return alert.sendKeys(text);
  2395. });
  2396. };
  2397. }
  2398. }
  2399. promise.CancellableThenable.addImplementation(AlertPromise);
  2400. // PUBLIC API
  2401. module.exports = {
  2402. Alert: Alert,
  2403. AlertPromise: AlertPromise,
  2404. Condition: Condition,
  2405. Logs: Logs,
  2406. Navigation: Navigation,
  2407. Options: Options,
  2408. TargetLocator: TargetLocator,
  2409. Timeouts: Timeouts,
  2410. IWebDriver: IWebDriver,
  2411. WebDriver: WebDriver,
  2412. WebElement: WebElement,
  2413. WebElementCondition: WebElementCondition,
  2414. WebElementPromise: WebElementPromise,
  2415. Window: Window
  2416. };