UNPKG

95.2 kBTypeScriptView Raw
1// Type definitions for Selenium WebDriverJS 4.0
2// Project: https://github.com/SeleniumHQ/selenium
3// Definitions by: Bill Armstrong <https://github.com/BillArmstrong>,
4// Yuki Kokubun <https://github.com/Kuniwak>,
5// Craig Nishina <https://github.com/cnishina>,
6// Simon Gellis <https://github.com/SupernaviX>,
7// Ben Dixon <https://github.com/bendxn>,
8// Ziyu <https://github.com/oddui>
9// Johann Wolf <https://github.com/beta-vulgaris>
10// Aleksey Chemakin <https://github.com/Dzenly>
11// David Burns <https://github.com/AutomatedTester>
12// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
13// TypeScript Version: 2.4
14
15import * as chrome from './chrome';
16import * as edge from './edge';
17import * as firefox from './firefox';
18import * as ie from './ie';
19import { By, ByHash } from './lib/by';
20import { Browser, Capability, Capabilities, ITimeouts } from './lib/capabilities';
21import * as command from './lib/command';
22import * as http from './http';
23import { Actions, Button, Key, Origin } from './lib/input';
24import { promise } from './lib/promise';
25import * as logging from './lib/logging';
26import * as until from './lib/until';
27import * as safari from './safari';
28
29export { By, ByHash } from './lib/by';
30export { Browser, Capability, Capabilities, ITimeouts } from './lib/capabilities';
31export { Actions, Button, Key, Origin } from './lib/input';
32export { promise } from './lib/promise';
33export { until };
34export { logging };
35
36/**
37 * Typings for lib/error
38 */
39export namespace error {
40 class IError extends Error {
41 constructor(message?: string);
42 message: string;
43 }
44
45 /**
46 * The base WebDriver error type. This error type is only used directly when a
47 * more appropriate category is not defined for the offending error.
48 */
49 class WebDriverError extends IError {
50 constructor(message?: string);
51 remoteStacktrace?: string;
52 }
53
54 /**
55 * Indicates a {@linkplain ./webdriver.WebElement#click click command} could
56 * not completed because the click target is obscured by other elements on the
57 * page.
58 */
59 class ElementClickInterceptedError extends WebDriverError {
60 constructor(message?: string);
61 }
62
63 /**
64 * An attempt was made to select an element that cannot be selected.
65 */
66 class ElementNotSelectableError extends WebDriverError {
67 constructor(message?: string);
68 }
69
70 /**
71 * Indicates a command could not be completed because the target element is
72 * not pointer or keyboard interactable. This will often occur if an element
73 * is present in the DOM, but not rendered (i.e. its CSS style has
74 * "display: none").
75 */
76
77 class ElementNotInteractableError extends WebDriverError {
78 constructor(message?: string);
79 }
80
81 /**
82 * Indicates a navigation event caused the browser to generate a certificate
83 * warning. This is usually caused by an expired or invalid TLS certificate.
84 */
85 class InsecureCertificateError extends WebDriverError {
86 constructor(message?: string);
87 }
88
89 /**
90 * The arguments passed to a command are either invalid or malformed.
91 */
92 class InvalidArgumentError extends WebDriverError {
93 constructor(message?: string);
94 }
95
96 /**
97 * An illegal attempt was made to set a cookie under a different domain than
98 * the current page.
99 */
100 class InvalidCookieDomainError extends WebDriverError {
101 constructor(message?: string);
102 }
103
104 /**
105 * The coordinates provided to an interactions operation are invalid.
106 */
107 class InvalidCoordinatesError extends WebDriverError {
108 constructor(message?: string);
109 }
110
111 /**
112 * An element command could not be completed because the element is in an
113 * invalid state, e.g. attempting to click an element that is no longer
114 * attached to the document.
115 */
116 class InvalidElementStateError extends WebDriverError {
117 constructor(message?: string);
118 }
119
120 /**
121 * Argument was an invalid selector.
122 */
123 class InvalidSelectorError extends WebDriverError {
124 constructor(message?: string);
125 }
126
127 /**
128 * Occurs when a command is directed to a session that does not exist.
129 */
130 class NoSuchSessionError extends WebDriverError {
131 constructor(message?: string);
132 }
133
134 /**
135 * An error occurred while executing JavaScript supplied by the user.
136 */
137 class JavascriptError extends WebDriverError {
138 constructor(message?: string);
139 }
140
141 /**
142 * The target for mouse interaction is not in the browser’s viewport and
143 * cannot be brought into that viewport.
144 */
145 class MoveTargetOutOfBoundsError extends WebDriverError {
146 constructor(message?: string);
147 }
148
149 /**
150 * An attempt was made to operate on a modal dialog when one was not open.
151 */
152 class NoSuchAlertError extends WebDriverError {
153 constructor(message?: string);
154 }
155
156 /**
157 * Indicates a named cookie could not be found in the cookie jar for the
158 * currently selected document.
159 */
160 class NoSuchCookieError extends WebDriverError {
161 constructor(message?: string);
162 }
163
164 /**
165 * An element could not be located on the page using the given search
166 * parameters.
167 */
168 class NoSuchElementError extends WebDriverError {
169 constructor(message?: string);
170 }
171
172 /**
173 * A request to switch to a frame could not be satisfied because the frame
174 * could not be found.
175 */
176 class NoSuchFrameError extends WebDriverError {
177 constructor(message?: string);
178 }
179
180 /**
181 * A request to switch to a window could not be satisfied because the window
182 * could not be found.
183 */
184 class NoSuchWindowError extends WebDriverError {
185 constructor(message?: string);
186 }
187
188 /**
189 * A script did not complete before its timeout expired.
190 */
191 class ScriptTimeoutError extends WebDriverError {
192 constructor(message?: string);
193 }
194
195 /**
196 * A new session could not be created.
197 */
198 class SessionNotCreatedError extends WebDriverError {
199 constructor(message?: string);
200 }
201
202 /**
203 * An element command failed because the referenced element is no longer
204 * attached to the DOM.
205 */
206 class StaleElementReferenceError extends WebDriverError {
207 constructor(message?: string);
208 }
209
210 /**
211 * An operation did not completErrorCodee before its timeout expired.
212 */
213 class TimeoutError extends WebDriverError {
214 constructor(message?: string);
215 }
216
217 /**
218 * A request to set a cookie’s value could not be satisfied.
219 */
220 class UnableToSetCookieError extends WebDriverError {
221 constructor(message?: string);
222 }
223
224 /**
225 * A screen capture operation was not possible.
226 */
227 class UnableToCaptureScreenError extends WebDriverError {
228 constructor(message?: string);
229 }
230
231 /**
232 * A modal dialog was open, blocking this operation.
233 */
234 class UnexpectedAlertOpenError extends WebDriverError {
235 constructor(message?: string, openAlertText?: string);
236 /**
237 * @return {(string|undefined)} The text displayed with the unhandled alert,
238 * if available.
239 */
240 getAlertText(): string;
241 }
242
243 /**
244 * A command could not be executed because the remote end is not aware of it.
245 */
246 class UnknownCommandError extends WebDriverError {
247 constructor(message?: string);
248 }
249
250 /**
251 * The requested command matched a known URL but did not match an method for
252 * that URL.
253 */
254 class UnknownMethodError extends WebDriverError {
255 constructor(message?: string);
256 }
257
258 /**
259 * Reports an unsupport operation.
260 */
261 class UnsupportedOperationError extends WebDriverError {
262 constructor(message?: string);
263 }
264
265 interface Response {
266 error: string|number;
267 message: string;
268 }
269 /**
270 * Checks a response object from a server that adheres to the W3C WebDriver
271 * protocol.
272 */
273 function checkResponse(data: Response): Response;
274
275 interface MaybeLegacyResponse {
276 status?: number;
277 value?: {message: string};
278 message?: string;
279 getAlertText?(): string;
280 }
281
282 /**
283 * Checks a legacy response from the Selenium 2.0 wire protocol for an error.
284 */
285 function checkLegacyResponse(response: MaybeLegacyResponse): MaybeLegacyResponse;
286
287 interface ErrorData {
288 error: string|number;
289 message: string;
290 [key: string]: string|number;
291 }
292
293 /**
294 * Throws an error coded from the W3C protocol. A generic error will be thrown
295 * if the provided `data` is not a valid encoded error.
296 */
297 function throwDecodedError(data: ErrorData|string): never;
298
299 interface ErrorCodeType {
300 [key: string]: number;
301 }
302
303 const ErrorCode: ErrorCodeType;
304
305 /**
306 * Lookup the err in table of errors.
307 */
308 function encodeError(err: any): {error: string, message: string};
309}
310
311type ConditionFn<T> = (webdriver: WebDriver) => T | null | Promise<T | null>;
312
313/**
314 * Defines a condition for use with WebDriver's WebDriver#wait wait command.
315 */
316export class Condition<T> {
317 /**
318 * @param {string} message A descriptive error message. Should complete the
319 * sentence 'Waiting [...]'
320 * @param {function(!WebDriver): OUT} fn The condition function to
321 * evaluate on each iteration of the wait loop.
322 * @constructor
323 */
324 constructor(message: string, fn: ConditionFn<T>);
325
326 /** @return {string} A description of this condition. */
327 description(): string;
328
329 /** @type {function(!WebDriver): OUT} */
330 fn(webdriver: WebDriver): ConditionFn<T>;
331}
332
333/**
334 * Defines a condition that will result in a {@link WebElement}.
335 *
336 * @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
337 */
338export class WebElementCondition extends Condition<WebElement> {
339 // add an unused private member so the compiler treats this
340 // class distinct from other Conditions
341 private _nominal: undefined;
342}
343
344/**
345 * x,y
346 */
347export interface ILocation {
348 x: number;
349 y: number;
350}
351
352/**
353 * width, height
354 */
355export interface ISize {
356 width: number;
357 height: number;
358}
359
360/**
361 * x,y,w,h
362 */
363export interface IRectangle {
364 x: number;
365 y: number;
366 width: number;
367 height: number;
368}
369
370/**
371 * Class for defining sequences of user touch interactions. Each sequence
372 * will not be executed until {@link #perform} is called.
373 *
374 * Example:
375 *
376 * new TouchSequence(driver).
377 * tapAndHold({x: 0, y: 0}).
378 * move({x: 3, y: 4}).
379 * release({x: 10, y: 10}).
380 * perform();
381 */
382export class TouchSequence {
383 /*
384 * @param {!WebDriver} driver The driver instance to use.
385 * @constructor
386 */
387 constructor(driver: WebDriver);
388
389 /**
390 * Executes this action sequence.
391 * @return {!Promise} A promise that will be resolved once
392 * this sequence has completed.
393 */
394 perform(): Promise<void>;
395
396 /**
397 * Taps an element.
398 *
399 * @param {!WebElement} elem The element to tap.
400 * @return {!TouchSequence} A self reference.
401 */
402 tap(elem: WebElement): TouchSequence;
403
404 /**
405 * Double taps an element.
406 *
407 * @param {!WebElement} elem The element to double tap.
408 * @return {!TouchSequence} A self reference.
409 */
410 doubleTap(elem: WebElement): TouchSequence;
411
412 /**
413 * Long press on an element.
414 *
415 * @param {!WebElement} elem The element to long press.
416 * @return {!TouchSequence} A self reference.
417 */
418 longPress(elem: WebElement): TouchSequence;
419
420 /**
421 * Touch down at the given location.
422 *
423 * @param {{ x: number, y: number }} location The location to touch down at.
424 * @return {!TouchSequence} A self reference.
425 */
426 tapAndHold(location: ILocation): TouchSequence;
427
428 /**
429 * Move a held {@linkplain #tapAndHold touch} to the specified location.
430 *
431 * @param {{x: number, y: number}} location The location to move to.
432 * @return {!TouchSequence} A self reference.
433 */
434 move(location: ILocation): TouchSequence;
435
436 /**
437 * Release a held {@linkplain #tapAndHold touch} at the specified location.
438 *
439 * @param {{x: number, y: number}} location The location to release at.
440 * @return {!TouchSequence} A self reference.
441 */
442 release(location: ILocation): TouchSequence;
443
444 /**
445 * Scrolls the touch screen by the given offset.
446 *
447 * @param {{x: number, y: number}} offset The offset to scroll to.
448 * @return {!TouchSequence} A self reference.
449 */
450 scroll(offset: IOffset): TouchSequence;
451
452 /**
453 * Scrolls the touch screen, starting on `elem` and moving by the specified
454 * offset.
455 *
456 * @param {!WebElement} elem The element where scroll starts.
457 * @param {{x: number, y: number}} offset The offset to scroll to.
458 * @return {!TouchSequence} A self reference.
459 */
460 scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence;
461
462 /**
463 * Flick, starting anywhere on the screen, at speed xspeed and yspeed.
464 *
465 * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each
466 * direction, in pixels per second.
467 * @return {!TouchSequence} A self reference.
468 */
469 flick(speed: ISpeed): TouchSequence;
470
471 /**
472 * Flick starting at elem and moving by x and y at specified speed.
473 *
474 * @param {!WebElement} elem The element where flick starts.
475 * @param {{x: number, y: number}} offset The offset to flick to.
476 * @param {number} speed The speed to flick at in pixels per second.
477 * @return {!TouchSequence} A self reference.
478 */
479 flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence;
480}
481
482/**
483 * x.y again
484 */
485export interface IOffset {
486 x: number;
487 y: number;
488}
489
490/**
491 * delta x,y
492 */
493export interface ISpeed {
494 xspeed: number;
495 yspeed: number;
496}
497
498/**
499 * Represents a modal dialog such as {@code alert}, {@code confirm}, or
500 * {@code prompt}. Provides functions to retrieve the message displayed with
501 * the alert, accept or dismiss the alert, and set the response text (in the
502 * case of {@code prompt}).
503 */
504export class Alert {
505 /**
506 * @param {!WebDriver} driver The driver controlling the browser this alert
507 * is attached to.
508 * @param {string} text The message text displayed with this alert.
509 */
510 constructor(driver: WebDriver, text: string);
511
512 // region Methods
513
514 /**
515 * Retrieves the message text displayed with this alert. For instance, if the
516 * alert were opened with alert('hello'), then this would return 'hello'.
517 * @return {!Promise} A promise that will be resolved to the
518 * text displayed with this alert.
519 */
520 getText(): Promise<string>;
521
522 /**
523 * Sets the username and password in an alert prompting for credentials (such
524 * as a Basic HTTP Auth prompt). This method will implicitly
525 * {@linkplain #accept() submit} the dialog.
526 *
527 * @param {string} username The username to send.
528 * @param {string} password The password to send.
529 * @return {!Promise<void>} A promise that will be resolved when this
530 * command has completed.
531 */
532 authenticateAs(username: string, password: string): Promise<void>;
533
534 /**
535 * Accepts this alert.
536 * @return {!Promise} A promise that will be resolved when
537 * this command has completed.
538 */
539 accept(): Promise<void>;
540
541 /**
542 * Dismisses this alert.
543 * @return {!Promise} A promise that will be resolved when
544 * this command has completed.
545 */
546 dismiss(): Promise<void>;
547
548 /**
549 * Sets the response text on this alert. This command will return an error if
550 * the underlying alert does not support response text (e.g. window.alert and
551 * window.confirm).
552 * @param {string} text The text to set.
553 * @return {!Promise} A promise that will be resolved when
554 * this command has completed.
555 */
556 sendKeys(text: string): Promise<void>;
557
558 // endregion
559}
560
561/**
562 * AlertPromise is a promise that will be fulfilled with an Alert. This promise
563 * serves as a forward proxy on an Alert, allowing calls to be scheduled
564 * directly on this instance before the underlying Alert has been fulfilled. In
565 * other words, the following two statements are equivalent:
566 *
567 * driver.switchTo().alert().dismiss();
568 * driver.switchTo().alert().then(function(alert) {
569 * return alert.dismiss();
570 * });
571 *
572 * @implements {promise.Thenable.<!Alert>}
573 * @final
574 */
575export interface AlertPromise extends Promise<Alert> {}
576
577/**
578 * Implement AlertPromise
579 */
580export class AlertPromise extends Alert {
581 /**
582 * @param {!WebDriver} driver The driver controlling the browser this
583 * alert is attached to.
584 * @param {!promise.Thenable<!Alert>} alert A thenable
585 * that will be fulfilled with the promised alert.
586 */
587 constructor(driver: WebDriver, alert: Promise<Alert>);
588}
589
590/**
591 * ProxyConfig
592 */
593export interface ProxyConfig {
594 proxyType: string;
595 proxyAutoconfigUrl?: string;
596 ftpProxy?: string;
597 httpProxy?: string;
598 sslProxy?: string;
599 noProxy?: string;
600 socksProxy?: string;
601 socksUsername?: string;
602 socksPassword?: string;
603}
604
605/**
606 * Creates new {@link WebDriver WebDriver} instances. The environment
607 * variables listed below may be used to override a builder's configuration,
608 * allowing quick runtime changes.
609 *
610 * - {@code SELENIUM_BROWSER}: defines the target browser in the form
611 * {@code browser[:version][:platform]}.
612 *
613 * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder
614 * instances. This environment variable should be set to a fully qualified
615 * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This
616 * option always takes precedence over {@code SELENIUM_SERVER_JAR}.
617 *
618 * - {@code SELENIUM_SERVER_JAR}: defines the path to the
619 * <a href='http://selenium-release.storage.googleapis.com/index.html'>
620 * standalone Selenium server</a> jar to use. The server will be started the
621 * first time a WebDriver instance and be killed when the process exits.
622 *
623 * Suppose you had mytest.js that created WebDriver with
624 *
625 * var driver = new Builder()
626 * .forBrowser('chrome')
627 * .build();
628 *
629 * This test could be made to use Firefox on the local machine by running with
630 * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to
631 * target Google Chrome on a remote machine, you can simply set the
632 * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables:
633 *
634 * SELENIUM_BROWSER=chrome:36:LINUX \
635 * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \
636 * node mytest.js
637 *
638 * You could also use a local copy of the standalone Selenium server:
639 *
640 * SELENIUM_BROWSER=chrome:36:LINUX \
641 * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \
642 * node mytest.js
643 */
644export class Builder {
645 // region Constructors
646
647 /**
648 * @constructor
649 */
650 constructor();
651
652 // endregion
653
654 // region Methods
655
656 /**
657 * Configures this builder to ignore any environment variable overrides and to
658 * only use the configuration specified through this instance's API.
659 *
660 * @return {!Builder} A self reference.
661 */
662 disableEnvironmentOverrides(): Builder;
663
664 /**
665 * Creates a new WebDriver client based on this builder's current
666 * configuration.
667 *
668 * This method will return a {@linkplain ThenableWebDriver} instance, allowing
669 * users to issue commands directly without calling `then()`. The returned
670 * thenable wraps a promise that will resolve to a concrete
671 * {@linkplain webdriver.WebDriver WebDriver} instance. The promise will be
672 * rejected if the remote end fails to create a new session.
673 *
674 * @return {!ThenableWebDriver} A new WebDriver instance.
675 * @throws {Error} If the current configuration is invalid.
676 */
677 build(): ThenableWebDriver;
678
679 /**
680 * Configures the target browser for clients created by this instance.
681 * Any calls to {@link #withCapabilities} after this function will
682 * overwrite these settings.
683 *
684 * <p>You may also define the target browser using the {@code
685 * SELENIUM_BROWSER} environment variable. If set, this environment variable
686 * should be of the form {@code browser[:[version][:platform]]}.
687 *
688 * @param {(string|Browser)} name The name of the target browser;
689 * common defaults are available on the {@link Browser} enum.
690 * @param {string=} opt_version A desired version; may be omitted if any
691 * version should be used.
692 * @param {string=} opt_platform The desired platform; may be omitted if any
693 * version may be used.
694 * @return {!Builder} A self reference.
695 */
696 forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder;
697
698 /**
699 * Returns the base set of capabilities this instance is currently configured
700 * to use.
701 * @return {!Capabilities} The current capabilities for this builder.
702 */
703 getCapabilities(): Capabilities;
704
705 /**
706 * @return {string} The URL of the WebDriver server this instance is
707 * configured to use.
708 */
709 getServerUrl(): string;
710
711 /**
712 * @return {?string} The URL of the proxy server to use for the WebDriver's
713 * HTTP connections, or `null` if not set.
714 */
715 getWebDriverProxy(): string|null;
716
717 /**
718 * Sets the default action to take with an unexpected alert before returning
719 * an error.
720 * @param {string} beahvior The desired behavior; should be 'accept',
721 * 'dismiss', or 'ignore'. Defaults to 'dismiss'.
722 * @return {!Builder} A self reference.
723 */
724 setAlertBehavior(behavior?: string): Builder;
725
726 /**
727 * Sets Chrome-specific options for drivers created by this builder. Any
728 * logging or proxy settings defined on the given options will take precedence
729 * over those set through {@link #setLoggingPrefs} and {@link #setProxy},
730 * respectively.
731 *
732 * @param {!chrome.Options} options The ChromeDriver options to use.
733 * @return {!Builder} A self reference.
734 */
735 setChromeOptions(options: chrome.Options): Builder;
736
737 /**
738 * @return {chrome.Options} the Chrome specific options currently configured
739 * for this builder.
740 */
741 getChromeOptions(): chrome.Options;
742
743 /**
744 * Sets the service builder to use for managing the chromedriver child process
745 * when creating new Chrome sessions.
746 *
747 * @param {chrome.ServiceBuilder} service the service to use.
748 * @return {!Builder} A self reference.
749 */
750 setChromeService(service: chrome.ServiceBuilder): Builder;
751
752 /**
753 * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser
754 * for drivers created by this builder. Any proxy settings defined on the
755 * given options will take precedence over those set through
756 * {@link #setProxy}.
757 *
758 * @param {!edge.Options} options The MicrosoftEdgeDriver options to use.
759 * @return {!Builder} A self reference.
760 */
761 setEdgeOptions(options: edge.Options): Builder;
762
763 /**
764 * Sets the {@link edge.ServiceBuilder} to use to manage the
765 * MicrosoftEdgeDriver child process when creating sessions locally.
766 *
767 * @param {edge.ServiceBuilder} service the service to use.
768 * @return {!Builder} a self reference.
769 */
770 setEdgeService(service: edge.ServiceBuilder): Builder;
771
772 /**
773 * Sets Firefox-specific options for drivers created by this builder. Any
774 * logging or proxy settings defined on the given options will take precedence
775 * over those set through {@link #setLoggingPrefs} and {@link #setProxy},
776 * respectively.
777 *
778 * @param {!firefox.Options} options The FirefoxDriver options to use.
779 * @return {!Builder} A self reference.
780 */
781 setFirefoxOptions(options: firefox.Options): Builder;
782
783 /**
784 * @return {firefox.Options} the Firefox specific options currently configured
785 * for this instance.
786 */
787 getFirefoxOptions(): firefox.Options;
788
789 /**
790 * Sets the {@link firefox.ServiceBuilder} to use to manage the geckodriver
791 * child process when creating Firefox sessions locally.
792 *
793 * @param {firefox.ServiceBuilder} service the service to use.
794 * @return {!Builder} a self reference.
795 */
796 setFirefoxService(service: firefox.ServiceBuilder): Builder;
797
798 /**
799 * Set Internet Explorer specific {@linkplain ie.Options options} for drivers
800 * created by this builder. Any proxy settings defined on the given options
801 * will take precedence over those set through {@link #setProxy}.
802 *
803 * @param {!ie.Options} options The IEDriver options to use.
804 * @return {!Builder} A self reference.
805 */
806 setIeOptions(options: ie.Options): Builder;
807
808 /**
809 * Sets the {@link ie.ServiceBuilder} to use to manage the geckodriver
810 * child process when creating IE sessions locally.
811 *
812 * @param {ie.ServiceBuilder} service the service to use.
813 * @return {!Builder} a self reference.
814 */
815 setIeService(service: ie.ServiceBuilder): Builder;
816
817 /**
818 * Sets the logging preferences for the created session. Preferences may be
819 * changed by repeated calls, or by calling {@link #withCapabilities}.
820 * @param {!(logging.Preferences|Object.<string, string>)} prefs The
821 * desired logging preferences.
822 * @return {!Builder} A self reference.
823 */
824 setLoggingPrefs(prefs: logging.Preferences|{}): Builder;
825
826 /**
827 * Sets the proxy configuration to use for WebDriver clients created by this
828 * builder. Any calls to {@link #withCapabilities} after this function will
829 * overwrite these settings.
830 * @param {!capabilities.ProxyConfig} config The configuration to use.
831 * @return {!Builder} A self reference.
832 */
833 setProxy(config: ProxyConfig): Builder;
834
835 /**
836 * Sets Safari specific {@linkplain safari.Options options} for drivers
837 * created by this builder. Any logging settings defined on the given options
838 * will take precedence over those set through {@link #setLoggingPrefs}.
839 *
840 * @param {!safari.Options} options The Safari options to use.
841 * @return {!Builder} A self reference.
842 */
843 setSafariOptions(options: safari.Options): Builder;
844
845 /**
846 * @return {safari.Options} the Safari specific options currently configured
847 * for this instance.
848 */
849 getSafariOptions(): safari.Options;
850
851 /**
852 * Sets the http agent to use for each request.
853 * If this method is not called, the Builder will use http.globalAgent by
854 * default.
855 *
856 * @param {http.Agent} agent The agent to use for each request.
857 * @return {!Builder} A self reference.
858 */
859 usingHttpAgent(agent: any): Builder;
860
861 /**
862 * @return {http.Agent} The http agent used for each request
863 */
864 getHttpAgent(): any|null;
865
866 /**
867 * Sets the URL of a remote WebDriver server to use. Once a remote URL has
868 * been specified, the builder direct all new clients to that server. If this
869 * method is never called, the Builder will attempt to create all clients
870 * locally.
871 *
872 * <p>As an alternative to this method, you may also set the
873 * {@code SELENIUM_REMOTE_URL} environment variable.
874 *
875 * @param {string} url The URL of a remote server to use.
876 * @return {!Builder} A self reference.
877 */
878 usingServer(url: string): Builder;
879
880 /**
881 * Sets the URL of the proxy to use for the WebDriver's HTTP connections.
882 * If this method is never called, the Builder will create a connection
883 * without a proxy.
884 *
885 * @param {string} proxy The URL of a proxy to use.
886 * @return {!Builder} A self reference.
887 */
888 usingWebDriverProxy(proxy: string): Builder;
889
890 /**
891 * Sets the desired capabilities when requesting a new session. This will
892 * overwrite any previously set capabilities.
893 * @param {!(Object|Capabilities)} capabilities The desired
894 * capabilities for a new session.
895 * @return {!Builder} A self reference.
896 */
897 withCapabilities(capabilities: {}|Capabilities): Builder;
898
899 // endregion
900}
901
902export type Locator = By | Function | ByHash;
903
904/**
905 * Describes an event listener registered on an {@linkplain EventEmitter}.
906 */
907export class Listener {
908 /**
909 * @param {!Function} fn The acutal listener function.
910 * @param {(Object|undefined)} scope The object in whose scope to invoke the
911 * listener.
912 * @param {boolean} oneshot Whether this listener should only be used once.
913 */
914 constructor(fn: Function, scope: {}, oneshot: boolean);
915}
916
917/**
918 * Object that can emit events for others to listen for. This is used instead
919 * of Closure's event system because it is much more light weight. The API is
920 * based on Node's EventEmitters.
921 */
922export class EventEmitter {
923 // region Constructors
924
925 /**
926 * @constructor
927 */
928 constructor();
929
930 // endregion
931
932 // region Methods
933
934 /**
935 * Fires an event and calls all listeners.
936 * @param {string} type The type of event to emit.
937 * @param {...*} var_args Any arguments to pass to each listener.
938 */
939 emit(type: string, ...var_args: any[]): void;
940
941 /**
942 * Returns a mutable list of listeners for a specific type of event.
943 * @param {string} type The type of event to retrieve the listeners for.
944 * @return {!Set<!Listener>} The registered listeners for the given event
945 * type.
946 */
947 listeners(type: string): any;
948
949 /**
950 * Registers a listener.
951 * @param {string} type The type of event to listen for.
952 * @param {!Function} fn The function to invoke when the event is fired.
953 * @param {Object=} opt_self The object in whose scope to invoke the listener.
954 * @param {boolean=} opt_oneshot Whether the listener should b (e removed
955 * after
956 * the first event is fired.
957 * @return {!EventEmitter} A self reference.
958 * @private
959 */
960 addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter;
961
962 /**
963 * Registers a one-time listener which will be called only the first time an
964 * event is emitted, after which it will be removed.
965 * @param {string} type The type of event to listen for.
966 * @param {!Function} fn The function to invoke when the event is fired.
967 * @param {Object=} opt_scope The object in whose scope to invoke the
968 * listener.
969 * @return {!EventEmitter} A self reference.
970 */
971 once(type: string, fn: any, opt_scope?: any): EventEmitter;
972
973 /**
974 * An alias for {@code #addListener()}.
975 * @param {string} type The type of event to listen for.
976 * @param {!Function} fn The function to invoke when the event is fired.
977 * @param {Object=} opt_scope The object in whose scope to invoke the
978 * listener.
979 * @return {!EventEmitter} A self reference.
980 */
981 on(type: string, fn: Function, opt_scope?: any): EventEmitter;
982
983 /**
984 * Removes a previously registered event listener.
985 * @param {string} type The type of event to unregister.
986 * @param {!Function} listenerFn The handler function to remove.
987 * @return {!EventEmitter} A self reference.
988 */
989 removeListener(type: string, listenerFn: Function): EventEmitter;
990
991 /**
992 * Removes all listeners for a specific type of event. If no event is
993 * specified, all listeners across all types will be removed.
994 * @param {string=} opt_type The type of event to remove listeners from.
995 * @return {!EventEmitter} A self reference.
996 */
997 removeAllListeners(opt_type?: string): EventEmitter;
998
999 // endregion
1000}
1001
1002/**
1003 * Interface for navigating back and forth in the browser history.
1004 */
1005export class Navigation {
1006 // region Constructors
1007
1008 /**
1009 * Interface for navigating back and forth in the browser history.
1010 *
1011 * This class should never be instantiated directly. Insead, obtain an
1012 * instance with
1013 *
1014 * navigate()
1015 *
1016 * @see WebDriver#navigate()
1017 */
1018 constructor(driver: WebDriver);
1019
1020 // endregion
1021
1022 // region Methods
1023
1024 /**
1025 * Schedules a command to navigate to a new URL.
1026 * @param {string} url The URL to navigate to.
1027 * @return {!Promise.<void>} A promise that will be resolved
1028 * when the URL has been loaded.
1029 */
1030 to(url: string): Promise<void>;
1031
1032 /**
1033 * Schedules a command to move backwards in the browser history.
1034 * @return {!Promise.<void>} A promise that will be resolved
1035 * when the navigation event has completed.
1036 */
1037 back(): Promise<void>;
1038
1039 /**
1040 * Schedules a command to move forwards in the browser history.
1041 * @return {!Promise.<void>} A promise that will be resolved
1042 * when the navigation event has completed.
1043 */
1044 forward(): Promise<void>;
1045
1046 /**
1047 * Schedules a command to refresh the current page.
1048 * @return {!Promise.<void>} A promise that will be resolved
1049 * when the navigation event has completed.
1050 */
1051 refresh(): Promise<void>;
1052
1053 // endregion
1054}
1055
1056export interface IWebDriverOptionsCookie {
1057 /**
1058 * The name of the cookie.
1059 */
1060 name: string;
1061
1062 /**
1063 * The cookie value.
1064 */
1065 value: string;
1066
1067 /**
1068 * The cookie path. Defaults to "/" when adding a cookie.
1069 */
1070 path?: string;
1071
1072 /**
1073 * The domain the cookie is visible to. Defaults to the current browsing
1074 * context's document's URL when adding a cookie.
1075 */
1076 domain?: string;
1077
1078 /**
1079 * Whether the cookie is a secure cookie. Defaults to false when adding a new
1080 * cookie.
1081 */
1082 secure?: boolean;
1083
1084 /**
1085 * Whether the cookie is an HTTP only cookie. Defaults to false when adding a
1086 * new cookie.
1087 */
1088 httpOnly?: boolean;
1089
1090 /**
1091 * When the cookie expires.
1092 *
1093 * When {@linkplain Options#addCookie() adding a cookie}, this may be
1094 * specified in _seconds_ since Unix epoch (January 1, 1970). The expiry will
1095 * default to 20 years in the future if omitted.
1096 *
1097 * The expiry is always returned in seconds since epoch when
1098 * {@linkplain Options#getCookies() retrieving cookies} from the browser.
1099 *
1100 * @type {(!Date|number|undefined)}
1101 */
1102 expiry?: number|Date;
1103}
1104
1105export interface IWebDriverCookie extends IWebDriverOptionsCookie {
1106 /**
1107 * When the cookie expires.
1108 *
1109 * The expiry is always returned in seconds since epoch when
1110 * {@linkplain Options#getCookies() retrieving cookies} from the browser.
1111 *
1112 * @type {(!number|undefined)}
1113 */
1114 expiry?: number;
1115}
1116
1117/**
1118 * Provides methods for managing browser and driver state.
1119 */
1120export class Options {
1121 // region Constructors
1122
1123 /**
1124 * @param {!WebDriver} driver The parent driver.
1125 * @constructor
1126 */
1127 constructor(driver: WebDriver);
1128
1129 // endregion
1130
1131 // region Methods
1132
1133 /**
1134 * Schedules a command to add a cookie.
1135 * @param {IWebDriverOptionsCookie} spec Defines the cookie to add.
1136 * @return {!Promise<void>} A promise that will be resolved
1137 * when the cookie has been added to the page.
1138 * @throws {error.InvalidArgumentError} if any of the cookie parameters are
1139 * invalid.
1140 * @throws {TypeError} if `spec` is not a cookie object.
1141 */
1142 addCookie(spec: IWebDriverOptionsCookie): Promise<void>;
1143
1144 /**
1145 * Schedules a command to delete all cookies visible to the current page.
1146 * @return {!Promise} A promise that will be resolved when all
1147 * cookies have been deleted.
1148 */
1149 deleteAllCookies(): Promise<void>;
1150
1151 /**
1152 * Schedules a command to delete the cookie with the given name. This command
1153 * is a no-op if there is no cookie with the given name visible to the current
1154 * page.
1155 * @param {string} name The name of the cookie to delete.
1156 * @return {!Promise} A promise that will be resolved when the
1157 * cookie has been deleted.
1158 */
1159 deleteCookie(name: string): Promise<void>;
1160
1161 /**
1162 * Schedules a command to retrieve all cookies visible to the current page.
1163 * Each cookie will be returned as a JSON object as described by the WebDriver
1164 * wire protocol.
1165 * @return {!Promise} A promise that will be resolved with the
1166 * cookies visible to the current page.
1167 * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object
1168 */
1169 getCookies(): Promise<IWebDriverCookie[]>;
1170
1171 /**
1172 * Schedules a command to retrieve the cookie with the given name. Returns
1173 * null if there is no such cookie. The cookie will be returned as a JSON
1174 * object as described by the WebDriver wire protocol.
1175 * @param {string} name The name of the cookie to retrieve.
1176 * @return {!Promise} A promise that will be resolved with the
1177 * named cookie, or {@code null} if there is no such cookie.
1178 * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object
1179 */
1180 getCookie(name: string): Promise<IWebDriverCookie>;
1181
1182 /**
1183 * @return {!Logs} The interface for managing driver
1184 * logs.
1185 */
1186 logs(): Logs;
1187
1188 /**
1189 * The current timeouts
1190 */
1191 getTimeouts(): Promise<ITimeouts>;
1192
1193 /**
1194 * Set current timeouts
1195 */
1196 setTimeouts(timeouts: ITimeouts): Promise<void>;
1197
1198 /**
1199 * @return {!Window} The interface for managing the
1200 * current window.
1201 */
1202 window(): Window;
1203
1204 // endregion
1205}
1206
1207/**
1208 * An interface for managing the current window.
1209 */
1210export class Window {
1211 // region Constructors
1212
1213 /**
1214 * @param {!WebDriver} driver The parent driver.
1215 * @constructor
1216 */
1217 constructor(driver: WebDriver);
1218
1219 // endregion
1220
1221 // region Methods
1222
1223 /**
1224 * Retrieves the window's current position, relative to the top left corner of
1225 * the screen.
1226 * @return {!Promise} A promise that will be resolved with the
1227 * window's position in the form of a {x:number, y:number} object literal.
1228 */
1229 getPosition(): Promise<ILocation>;
1230
1231 /**
1232 * Repositions the current window.
1233 * @param {number} x The desired horizontal position, relative to the left
1234 * side of the screen.
1235 * @param {number} y The desired vertical position, relative to the top of the
1236 * of the screen.
1237 * @return {!Promise} A promise that will be resolved when the
1238 * command has completed.
1239 */
1240 setPosition(x: number, y: number): Promise<void>;
1241
1242 /**
1243 * Retrieves the window's current size.
1244 * @return {!Promise} A promise that will be resolved with the
1245 * window's size in the form of a {width:number, height:number} object
1246 * literal.
1247 */
1248 getSize(): Promise<ISize>;
1249
1250 /**
1251 * Resizes the current window.
1252 * @param {number} width The desired window width.
1253 * @param {number} height The desired window height.
1254 * @return {!Promise} A promise that will be resolved when the
1255 * command has completed.
1256 */
1257 setSize(width: number, height: number): Promise<void>;
1258
1259 /**
1260 * Returns the current top-level window's size and position.
1261 */
1262 getRect(): Promise<IRectangle>;
1263
1264 /**
1265 * Sets the current top-level window's size and position. You may update
1266 * just the size by omitting `x` & `y`, or just the position by omitting
1267 * `width` & `height` options.
1268 */
1269 setRect({x, y, width, height}: Partial<IRectangle>): Promise<IRectangle>;
1270
1271 /**
1272 * Maximizes the current window.
1273 * @return {!Promise} A promise that will be resolved when the
1274 * command has completed.
1275 */
1276 maximize(): Promise<void>;
1277
1278 // endregion
1279}
1280
1281/**
1282 * Interface for managing WebDriver log records.
1283 */
1284export class Logs {
1285 // region Constructors
1286
1287 /**
1288 * @param {!WebDriver} driver The parent driver.
1289 * @constructor
1290 */
1291 constructor(driver: WebDriver);
1292
1293 // endregion
1294
1295 // region
1296
1297 /**
1298 * Fetches available log entries for the given type.
1299 *
1300 * <p/>Note that log buffers are reset after each call, meaning that
1301 * available log entries correspond to those entries not yet returned for a
1302 * given log type. In practice, this means that this call will return the
1303 * available log entries since the last call, or from the start of the
1304 * session.
1305 *
1306 * @param {!logging.Type} type The desired log type.
1307 * @return {!Promise.<!Array.<!logging.Entry>>} A
1308 * promise that will resolve to a list of log entries for the specified
1309 * type.
1310 */
1311 get(type: string): Promise<logging.Entry[]>;
1312
1313 /**
1314 * Retrieves the log types available to this driver.
1315 * @return {!Promise.<!Array.<!logging.Type>>} A
1316 * promise that will resolve to a list of available log types.
1317 */
1318 getAvailableLogTypes(): Promise<string[]>;
1319
1320 // endregion
1321}
1322
1323/**
1324 * An interface for changing the focus of the driver to another frame or window.
1325 */
1326export class TargetLocator {
1327 // region Constructors
1328
1329 /**
1330 * @param {!WebDriver} driver The parent driver.
1331 * @constructor
1332 */
1333 constructor(driver: WebDriver);
1334
1335 // endregion
1336
1337 // region Methods
1338
1339 /**
1340 * Schedules a command retrieve the {@code document.activeElement} element on
1341 * the current document, or {@code document.body} if activeElement is not
1342 * available.
1343 * @return {!WebElement} The active element.
1344 */
1345 activeElement(): WebElementPromise;
1346
1347 /**
1348 * Schedules a command to switch focus of all future commands to the first
1349 * frame on the page.
1350 * @return {!Promise} A promise that will be resolved when the
1351 * driver has changed focus to the default content.
1352 */
1353 defaultContent(): Promise<void>;
1354
1355 /**
1356 * Changes the focus of all future commands to another frame on the page. The
1357 * target frame may be specified as one of the following:
1358 *
1359 * - A number that specifies a (zero-based) index into [window.frames](
1360 * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
1361 * - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
1362 * DOM element.
1363 * - The `null` value, to select the topmost frame on the page. Passing `null`
1364 * is the same as calling {@link #defaultContent defaultContent()}.
1365 *
1366 * If the specified frame can not be found, the returned promise will be
1367 * rejected with a {@linkplain error.NoSuchFrameError}.
1368 *
1369 * @param {(number|WebElement|null)} id The frame locator.
1370 * @return {!Promise<void>} A promise that will be resolved
1371 * when the driver has changed focus to the specified frame.
1372 */
1373 frame(id: number|WebElement|null): Promise<void>;
1374
1375 /**
1376 * Changes the focus of all future commands to the parent frame of the
1377 * currently selected frame. This command has no effect if the driver is
1378 * already focused on the top-level browsing context.
1379 *
1380 * @return {!Promise<void>} A promise that will be resolved when the command
1381 * has completed.
1382 */
1383 parentFrame(): Promise<void>;
1384
1385 /**
1386 * Schedules a command to switch the focus of all future commands to another
1387 * window. Windows may be specified by their {@code window.name} attribute or
1388 * by its handle (as returned by {@link WebDriver#getWindowHandles}).
1389 *
1390 * If the specified window cannot be found, the returned promise will be
1391 * rejected with a {@linkplain error.NoSuchWindowError}.
1392 *
1393 * @param {string} nameOrHandle The name or window handle of the window to
1394 * switch focus to.
1395 * @return {!Promise<void>} A promise that will be resolved
1396 * when the driver has changed focus to the specified window.
1397 */
1398 window(nameOrHandle: string): Promise<void>;
1399
1400 /**
1401 * Creates a new browser window and switches the focus for future
1402 * commands of this driver to the new window.
1403 *
1404 * @param {string} typeHint 'window' or 'tab'. The created window is not
1405 * guaranteed to be of the requested type; if the driver does not support
1406 * the requested type, a new browser window will be created of whatever type
1407 * the driver does support.
1408 * @return {!Promise<void>} A promise that will be resolved
1409 * when the driver has changed focus to the new window.
1410 */
1411 newWindow(typeHint: string): Promise<void>;
1412
1413 /**
1414 * Schedules a command to change focus to the active modal dialog, such as
1415 * those opened by `window.alert()`, `window.confirm()`, and
1416 * `window.prompt()`. The returned promise will be rejected with a
1417 * {@linkplain error.NoSuchAlertError} if there are no open alerts.
1418 *
1419 * @return {!AlertPromise} The open alert.
1420 */
1421 alert(): AlertPromise;
1422
1423 // endregion
1424}
1425
1426/**
1427 * Used with {@link WebElement#sendKeys WebElement#sendKeys} on file
1428 * input elements ({@code <input type='file'>}) to detect when the entered key
1429 * sequence defines the path to a file.
1430 *
1431 * By default, {@linkplain WebElement WebElement's} will enter all
1432 * key sequences exactly as entered. You may set a
1433 * {@linkplain WebDriver#setFileDetector file detector} on the parent
1434 * WebDriver instance to define custom behavior for handling file elements. Of
1435 * particular note is the {@link selenium-webdriver/remote.FileDetector}, which
1436 * should be used when running against a remote
1437 * [Selenium Server](http://docs.seleniumhq.org/download/).
1438 */
1439export class FileDetector {
1440 /** @constructor */
1441 constructor();
1442
1443 /**
1444 * Handles the file specified by the given path, preparing it for use with
1445 * the current browser. If the path does not refer to a valid file, it will
1446 * be returned unchanged, otherwisee a path suitable for use with the current
1447 * browser will be returned.
1448 *
1449 * This default implementation is a no-op. Subtypes may override this
1450 * function for custom tailored file handling.
1451 *
1452 * @param {!WebDriver} driver The driver for the current browser.
1453 * @param {string} path The path to process.
1454 * @return {!Promise<string>} A promise for the processed
1455 * file path.
1456 * @package
1457 */
1458 handleFile(driver: WebDriver, path: string): Promise<string>;
1459}
1460
1461export type CreateSessionCapabilities =
1462 Capabilities | {desired?: Capabilities, required?: Capabilities};
1463
1464/**
1465 * Creates a new WebDriver client, which provides control over a browser.
1466 *
1467 * Every WebDriver command returns a {@code Promise} that
1468 * represents the result of that command. Callbacks may be registered on this
1469 * object to manipulate the command result or catch an expected error. Any
1470 * commands scheduled with a callback are considered sub-commands and will
1471 * execute before the next command in the current frame. For example:
1472 *
1473 * var message = [];
1474 * driver.call(message.push, message, 'a').then(function() {
1475 * driver.call(message.push, message, 'b');
1476 * });
1477 * driver.call(message.push, message, 'c');
1478 * driver.call(function() {
1479 * alert('message is abc? ' + (message.join('') == 'abc'));
1480 * });
1481 *
1482 */
1483export class WebDriver {
1484 // region Constructors
1485
1486 /**
1487 * @param {!(Session|Promise<!Session>)} session Either a
1488 * known session or a promise that will be resolved to a session.
1489 * @param {!command.Executor} executor The executor to use when sending
1490 * commands to the browser.
1491 */
1492 constructor(session: Session|Promise<Session>, executor: http.Executor);
1493
1494 // endregion
1495
1496 // region StaticMethods
1497
1498 /**
1499 * Creates a new WebDriver session.
1500 *
1501 * By default, the requested session `capabilities` are merely "desired" and
1502 * the remote end will still create a new session even if it cannot satisfy
1503 * all of the requested capabilities. You can query which capabilities a
1504 * session actually has using the
1505 * {@linkplain #getCapabilities() getCapabilities()} method on the returned
1506 * WebDriver instance.
1507 *
1508 * To define _required capabilities_, provide the `capabilities` as an object
1509 * literal with `required` and `desired` keys. The `desired` key may be
1510 * omitted if all capabilities are required, and vice versa. If the server
1511 * cannot create a session with all of the required capabilities, it will
1512 * return an {@linkplain error.SessionNotCreatedError}.
1513 *
1514 * let required = new Capabilities().set('browserName', 'firefox');
1515 * let desired = new Capabilities().set('version', '45');
1516 * let driver = WebDriver.createSession(executor, {required, desired});
1517 *
1518 * This function will always return a WebDriver instance. If there is an error
1519 * creating the session, such as the aforementioned SessionNotCreatedError,
1520 * the driver will have a rejected {@linkplain #getSession session} promise.
1521 * It is recommended that this promise is left _unhandled_ so it will
1522 * propagate through the {@linkplain promise.ControlFlow control flow} and
1523 * cause subsequent commands to fail.
1524 *
1525 * let required = Capabilities.firefox();
1526 * let driver = WebDriver.createSession(executor, {required});
1527 *
1528 * // If the createSession operation failed, then this command will also
1529 * // also fail, propagating the creation failure.
1530 * driver.get('http://www.google.com').catch(e => console.log(e));
1531 *
1532 * @param {!command.Executor} executor The executor to create the new session
1533 * with.
1534 * @param {(!Capabilities|
1535 * {desired: (Capabilities|undefined),
1536 * required: (Capabilities|undefined)})} capabilities The desired
1537 * capabilities for the new session.
1538 * @param {promise.ControlFlow=} opt_flow The control flow all driver
1539 * commands should execute under, including the initial session creation.
1540 * Defaults to the {@link promise.controlFlow() currently active}
1541 * control flow.
1542 * @param {(function(new: WebDriver,
1543 * !IThenable<!Session>,
1544 * !command.Executor,
1545 * promise.ControlFlow=))=} opt_ctor
1546 * A reference to the constructor of the specific type of WebDriver client
1547 * to instantiate. Will create a vanilla {@linkplain WebDriver} instance
1548 * if a constructor is not provided.
1549 * @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when
1550 * the newly created session is terminated. This should be used to clean
1551 * up any resources associated with the session.
1552 * @return {!WebDriver} The driver for the newly created session.
1553 */
1554 // This method's arguments are untyped so that its overloads can have correct
1555 // types. Typescript doesn't allow static methods to be overridden with
1556 // incompatible signatures.
1557 static createSession(...var_args: any[]): WebDriver;
1558
1559 // endregion
1560
1561 // region Methods
1562
1563 /**
1564 * Schedules a {@link command.Command} to be executed by this driver's
1565 * {@link command.Executor}.
1566 *
1567 * @param {!command.Command} command The command to schedule.
1568 * @param {string} description A description of the command for debugging.
1569 * @return {!Promise<T>} A promise that will be resolved
1570 * with the command result.
1571 * @template T
1572 */
1573 execute<T>(command: command.Command, description?: string): Promise<T>;
1574
1575 /**
1576 * Sets the {@linkplain input.FileDetector file detector} that should be
1577 * used with this instance.
1578 * @param {input.FileDetector} detector The detector to use or {@code null}.
1579 */
1580 setFileDetector(detector: FileDetector): void;
1581
1582 getExecutor(): command.Executor;
1583
1584 /**
1585 * @return {!Promise.<!Session>} A promise for this
1586 * client's session.
1587 */
1588 getSession(): Promise<Session>;
1589
1590 /**
1591 * @return {!Promise.<!Capabilities>} A promise
1592 * that will resolve with the this instance's capabilities.
1593 */
1594 getCapabilities(): Promise<Capabilities>;
1595
1596 /**
1597 * Schedules a command to quit the current session. After calling quit, this
1598 * instance will be invalidated and may no longer be used to issue commands
1599 * against the browser.
1600 * @return {!Promise.<void>} A promise that will be resolved
1601 * when the command has completed.
1602 */
1603 quit(): Promise<void>;
1604
1605 /**
1606 * Creates a new action sequence using this driver. The sequence will not be
1607 * scheduled for execution until {@link actions.ActionSequence#perform} is
1608 * called. Example:
1609 *
1610 * driver.actions().
1611 * mouseDown(element1).
1612 * mouseMove(element2).
1613 * mouseUp().
1614 * perform();
1615 *
1616 * @return {!actions.ActionSequence} A new action sequence for this instance.
1617 */
1618 actions(options?: {async: boolean, bridge: boolean}|{async: boolean}|{bridge: boolean}): Actions;
1619
1620 /**
1621 * Schedules a command to execute JavaScript in the context of the currently
1622 * selected frame or window. The script fragment will be executed as the body
1623 * of an anonymous function. If the script is provided as a function object,
1624 * that function will be converted to a string for injection into the target
1625 * window.
1626 *
1627 * Any arguments provided in addition to the script will be included as script
1628 * arguments and may be referenced using the {@code arguments} object.
1629 * Arguments may be a boolean, number, string, or {@code WebElement}.
1630 * Arrays and objects may also be used as script arguments as long as each
1631 * item adheres to the types previously mentioned.
1632 *
1633 * The script may refer to any variables accessible from the current window.
1634 * Furthermore, the script will execute in the window's context, thus
1635 * {@code document} may be used to refer to the current document. Any local
1636 * variables will not be available once the script has finished executing,
1637 * though global variables will persist.
1638 *
1639 * If the script has a return value (i.e. if the script contains a return
1640 * statement), then the following steps will be taken for resolving this
1641 * functions return value:
1642 *
1643 * - For a HTML element, the value will resolve to a
1644 * {@link WebElement}
1645 * - Null and undefined return values will resolve to null</li>
1646 * - Booleans, numbers, and strings will resolve as is</li>
1647 * - Functions will resolve to their string representation</li>
1648 * - For arrays and objects, each member item will be converted according to
1649 * the rules above
1650 *
1651 * @param {!(string|Function)} script The script to execute.
1652 * @param {...*} var_args The arguments to pass to the script.
1653 * @return {!Promise.<T>} A promise that will resolve to the
1654 * scripts return value.
1655 * @template T
1656 */
1657 executeScript<T>(script: string|Function, ...var_args: any[]): Promise<T>;
1658
1659 /**
1660 * Schedules a command to execute asynchronous JavaScript in the context of
1661 * the currently selected frame or window. The script fragment will be
1662 * executed as the body of an anonymous function. If the script is provided as
1663 * a function object, that function will be converted to a string for
1664 * injection into the target window.
1665 *
1666 * Any arguments provided in addition to the script will be included as script
1667 * arguments and may be referenced using the {@code arguments} object.
1668 * Arguments may be a boolean, number, string, or {@code WebElement}.
1669 * Arrays and objects may also be used as script arguments as long as each
1670 * item adheres to the types previously mentioned.
1671 *
1672 * Unlike executing synchronous JavaScript with {@link #executeScript},
1673 * scripts executed with this function must explicitly signal they are
1674 * finished by invoking the provided callback. This callback will always be
1675 * injected into the executed function as the last argument, and thus may be
1676 * referenced with {@code arguments[arguments.length - 1]}. The following
1677 * steps will be taken for resolving this functions return value against the
1678 * first argument to the script's callback function:
1679 *
1680 * - For a HTML element, the value will resolve to a
1681 * {@link WebElement}
1682 * - Null and undefined return values will resolve to null
1683 * - Booleans, numbers, and strings will resolve as is
1684 * - Functions will resolve to their string representation
1685 * - For arrays and objects, each member item will be converted according to
1686 * the rules above
1687 *
1688 * __Example #1:__ Performing a sleep that is synchronized with the currently
1689 * selected window:
1690 *
1691 * var start = new Date().getTime();
1692 * driver.executeAsyncScript(
1693 * 'window.setTimeout(arguments[arguments.length - 1], 500);').
1694 * then(function() {
1695 * console.log(
1696 * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
1697 * });
1698 *
1699 * __Example #2:__ Synchronizing a test with an AJAX application:
1700 *
1701 * var button = driver.findElement(By.id('compose-button'));
1702 * button.click();
1703 * driver.executeAsyncScript(
1704 * 'var callback = arguments[arguments.length - 1];' +
1705 * 'mailClient.getComposeWindowWidget().onload(callback);');
1706 * driver.switchTo().frame('composeWidget');
1707 * driver.findElement(By.id('to')).sendKeys('dog@example.com');
1708 *
1709 * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
1710 * this example, the inject script is specified with a function literal. When
1711 * using this format, the function is converted to a string for injection, so
1712 * it should not reference any symbols not defined in the scope of the page
1713 * under test.
1714 *
1715 * driver.executeAsyncScript(function() {
1716 * var callback = arguments[arguments.length - 1];
1717 * var xhr = new XMLHttpRequest();
1718 * xhr.open('GET', '/resource/data.json', true);
1719 * xhr.onreadystatechange = function() {
1720 * if (xhr.readyState == 4) {
1721 * callback(xhr.responseText);
1722 * }
1723 * }
1724 * xhr.send('');
1725 * }).then(function(str) {
1726 * console.log(JSON.parse(str)['food']);
1727 * });
1728 *
1729 * @param {!(string|Function)} script The script to execute.
1730 * @param {...*} var_args The arguments to pass to the script.
1731 * @return {!Promise.<T>} A promise that will resolve to the
1732 * scripts return value.
1733 * @template T
1734 */
1735 executeAsyncScript<T>(script: string|Function, ...var_args: any[]): Promise<T>;
1736
1737 /**
1738 * Schedules a command to wait for a condition to hold. The condition may be
1739 * specified by a {@link Condition}, as a custom function, or
1740 * as a {@link Promise}.
1741 *
1742 * For a {@link Condition} or function, the wait will repeatedly
1743 * evaluate the condition until it returns a truthy value. If any errors occur
1744 * while evaluating the condition, they will be allowed to propagate. In the
1745 * event a condition returns a {@link Promise promise}, the
1746 * polling loop will wait for it to be resolved and use the resolved value for
1747 * whether the condition has been satisified. Note the resolution time for
1748 * a promise is factored into whether a wait has timed out.
1749 *
1750 * Note, if the provided condition is a {@link WebElementCondition}, then
1751 * the wait will return a {@link WebElementPromise} that will resolve to the
1752 * element that satisified the condition.
1753 *
1754 * *Example:* waiting up to 10 seconds for an element to be present and
1755 * visible on the page.
1756 *
1757 * var button = driver.wait(until.elementLocated(By.id('foo'), 10000);
1758 * button.click();
1759 *
1760 * This function may also be used to block the command flow on the resolution
1761 * of a {@link Promise promise}. When given a promise, the
1762 * command will simply wait for its resolution before completing. A timeout
1763 * may be provided to fail the command if the promise does not resolve before
1764 * the timeout expires.
1765 *
1766 * *Example:* Suppose you have a function, `startTestServer`, that returns a
1767 * promise for when a server is ready for requests. You can block a
1768 * `WebDriver` client on this promise with:
1769 *
1770 * var started = startTestServer();
1771 * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
1772 * driver.get(getServerUrl());
1773 *
1774 * @param {!WebElementCondition} condition The condition to
1775 * wait on, defined as a promise, condition object, or a function to
1776 * evaluate as a condition.
1777 * @param {number=} opt_timeout How long to wait for the condition to be true.
1778 * @param {string=} opt_message An optional message to use if the wait times
1779 * out.
1780 * @return {!WebElementPromise} A promise that will be fulfilled
1781 * with the first truthy value returned by the condition function, or
1782 * rejected if the condition times out.
1783 * @template T
1784 */
1785 wait(condition: WebElementCondition, opt_timeout?: number, opt_message?: string):
1786 WebElementPromise;
1787
1788 /**
1789 * Schedules a command to wait for a condition to hold. The condition may be
1790 * specified by a {@link webdriver.Condition}, as a custom function, or
1791 * as a {@link Promise}.
1792 *
1793 * For a {@link webdriver.Condition} or function, the wait will repeatedly
1794 * evaluate the condition until it returns a truthy value. If any errors occur
1795 * while evaluating the condition, they will be allowed to propagate. In the
1796 * event a condition returns a {@link Promise promise}, the
1797 * polling loop will wait for it to be resolved and use the resolved value for
1798 * whether the condition has been satisified. Note the resolution time for
1799 * a promise is factored into whether a wait has timed out.
1800 *
1801 * Note, if the provided condition is a {@link WebElementCondition}, then
1802 * the wait will return a {@link WebElementPromise} that will resolve to the
1803 * element that satisified the condition.
1804 *
1805 * *Example:* waiting up to 10 seconds for an element to be present and
1806 * visible on the page.
1807 *
1808 * var button = driver.wait(until.elementLocated(By.id('foo'), 10000);
1809 * button.click();
1810 *
1811 * This function may also be used to block the command flow on the resolution
1812 * of a {@link Promise promise}. When given a promise, the
1813 * command will simply wait for its resolution before completing. A timeout
1814 * may be provided to fail the command if the promise does not resolve before
1815 * the timeout expires.
1816 *
1817 * *Example:* Suppose you have a function, `startTestServer`, that returns a
1818 * promise for when a server is ready for requests. You can block a
1819 * `WebDriver` client on this promise with:
1820 *
1821 * var started = startTestServer();
1822 * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
1823 * driver.get(getServerUrl());
1824 *
1825 * @param {!(Promise<T>|
1826 * Condition<T>|
1827 * function(!WebDriver): T)} condition The condition to
1828 * wait on, defined as a promise, condition object, or a function to
1829 * evaluate as a condition.
1830 * @param {number=} opt_timeout How long to wait for the condition to be true.
1831 * @param {string=} opt_message An optional message to use if the wait times
1832 * out.
1833 * @return {!Promise<T>} A promise that will be fulfilled
1834 * with the first truthy value returned by the condition function, or
1835 * rejected if the condition times out.
1836 * @template T
1837 */
1838 wait<T>(
1839 condition: PromiseLike<T>|Condition<T>|((driver: WebDriver) => T | PromiseLike<T>)|Function,
1840 opt_timeout?: number, opt_message?: string): Promise<T>;
1841
1842 /**
1843 * Schedules a command to make the driver sleep for the given amount of time.
1844 * @param {number} ms The amount of time, in milliseconds, to sleep.
1845 * @return {!Promise.<void>} A promise that will be resolved
1846 * when the sleep has finished.
1847 */
1848 sleep(ms: number): Promise<void>;
1849
1850 /**
1851 * Schedules a command to retrieve they current window handle.
1852 * @return {!Promise.<string>} A promise that will be
1853 * resolved with the current window handle.
1854 */
1855 getWindowHandle(): Promise<string>;
1856
1857 /**
1858 * Schedules a command to retrieve the current list of available window
1859 * handles.
1860 * @return {!Promise.<!Array.<string>>} A promise that will
1861 * be resolved with an array of window handles.
1862 */
1863 getAllWindowHandles(): Promise<string[]>;
1864
1865 /**
1866 * Schedules a command to retrieve the current page's source. The page source
1867 * returned is a representation of the underlying DOM: do not expect it to be
1868 * formatted or escaped in the same way as the response sent from the web
1869 * server.
1870 * @return {!Promise.<string>} A promise that will be
1871 * resolved with the current page source.
1872 */
1873 getPageSource(): Promise<string>;
1874
1875 /**
1876 * Schedules a command to close the current window.
1877 * @return {!Promise.<void>} A promise that will be resolved
1878 * when this command has completed.
1879 */
1880 close(): Promise<void>;
1881
1882 /**
1883 * Schedules a command to navigate to the given URL.
1884 * @param {string} url The fully qualified URL to open.
1885 * @return {!Promise.<void>} A promise that will be resolved
1886 * when the document has finished loading.
1887 */
1888 get(url: string): Promise<void>;
1889
1890 /**
1891 * Schedules a command to retrieve the URL of the current page.
1892 * @return {!Promise.<string>} A promise that will be
1893 * resolved with the current URL.
1894 */
1895 getCurrentUrl(): Promise<string>;
1896
1897 /**
1898 * Schedules a command to retrieve the current page's title.
1899 * @return {!Promise.<string>} A promise that will be
1900 * resolved with the current page's title.
1901 */
1902 getTitle(): Promise<string>;
1903
1904 /**
1905 * Schedule a command to find an element on the page. If the element cannot be
1906 * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned
1907 * by the driver. Unlike other commands, this error cannot be suppressed. In
1908 * other words, scheduling a command to find an element doubles as an assert
1909 * that the element is present on the page. To test whether an element is
1910 * present on the page, use {@link #findElements}.
1911 *
1912 * The search criteria for an element may be defined using one of the
1913 * factories in the {@link By} namespace, or as a short-hand
1914 * {@link By.Hash} object. For example, the following two statements
1915 * are equivalent:
1916 *
1917 * var e1 = driver.findElement(By.id('foo'));
1918 * var e2 = driver.findElement({id:'foo'});
1919 *
1920 * You may also provide a custom locator function, which takes as input this
1921 * instance and returns a {@link WebElement}, or a promise that will resolve
1922 * to a WebElement. If the returned promise resolves to an array of
1923 * WebElements, WebDriver will use the first element. For example, to find the
1924 * first visible link on a page, you could write:
1925 *
1926 * var link = driver.findElement(firstVisibleLink);
1927 *
1928 * function firstVisibleLink(driver) {
1929 * var links = driver.findElements(By.tagName('a'));
1930 * return promise.filter(links, function(link) {
1931 * return link.isDisplayed();
1932 * });
1933 * }
1934 *
1935 * @param {!(by.By|Function)} locator The locator to use.
1936 * @return {!WebElementPromise} A WebElement that can be used to issue
1937 * commands against the located element. If the element is not found, the
1938 * element will be invalidated and all scheduled commands aborted.
1939 */
1940 findElement(locator: Locator): WebElementPromise;
1941
1942 /**
1943 * Schedule a command to search for multiple elements on the page.
1944 *
1945 * @param {!(by.By|Function)} locator The locator to use.
1946 * @return {!Promise.<!Array.<!WebElement>>} A
1947 * promise that will resolve to an array of WebElements.
1948 */
1949 findElements(locator: Locator): Promise<WebElement[]>;
1950
1951 /**
1952 * Schedule a command to take a screenshot. The driver makes a best effort to
1953 * return a screenshot of the following, in order of preference:
1954 *
1955 * 1. Entire page
1956 * 2. Current window
1957 * 3. Visible portion of the current frame
1958 * 4. The entire display containing the browser
1959 *
1960 * @return {!Promise<string>} A promise that will be
1961 * resolved to the screenshot as a base-64 encoded PNG.
1962 */
1963 takeScreenshot(): Promise<string>;
1964
1965 /**
1966 * @return {!Options} The options interface for this
1967 * instance.
1968 */
1969 manage(): Options;
1970
1971 /**
1972 * @return {!Navigation} The navigation interface for this
1973 * instance.
1974 */
1975 navigate(): Navigation;
1976
1977 /**
1978 * @return {!TargetLocator} The target locator interface for
1979 * this instance.
1980 */
1981 switchTo(): TargetLocator;
1982
1983 // endregion
1984}
1985
1986/**
1987 * A thenable wrapper around a {@linkplain webdriver.IWebDriver IWebDriver}
1988 * instance that allows commands to be issued directly instead of having to
1989 * repeatedly call `then`:
1990 *
1991 * let driver = new Builder().build();
1992 * driver.then(d => d.get(url)); // You can do this...
1993 * driver.get(url); // ...or this
1994 *
1995 * If the driver instance fails to resolve (e.g. the session cannot be created),
1996 * every issued command will fail.
1997 *
1998 * @extends {webdriver.IWebDriver}
1999 * @extends {Promise<!webdriver.IWebDriver>}
2000 * @interface
2001 */
2002export interface ThenableWebDriver extends WebDriver, Promise<WebDriver> {}
2003
2004export interface IWebElementId { [ELEMENT: string]: string; }
2005
2006/**
2007 * Represents a DOM element. WebElements can be found by searching from the
2008 * document root using a {@code WebDriver} instance, or by searching
2009 * under another {@code WebElement}:
2010 * <pre><code>
2011 * driver.get('http://www.google.com');
2012 * var searchForm = driver.findElement(By.tagName('form'));
2013 * var searchBox = searchForm.findElement(By.name('q'));
2014 * searchBox.sendKeys('webdriver');
2015 * </code></pre>
2016 *
2017 * The WebElement is implemented as a promise for compatibility with the promise
2018 * API. It will always resolve itself when its internal state has been fully
2019 * resolved and commands may be issued against the element. This can be used to
2020 * catch errors when an element cannot be located on the page:
2021 * <pre><code>
2022 * driver.findElement(By.id('not-there')).then(function(element) {
2023 * alert('Found an element that was not expected to be there!');
2024 * }, function(error) {
2025 * alert('The element was not found, as expected');
2026 * });
2027 * </code></pre>
2028 */
2029export interface IWebElement {
2030 // region Methods
2031
2032 /**
2033 * Schedules a command to click on this element.
2034 * @return {!Promise} A promise that will be resolved when
2035 * the click command has completed.
2036 */
2037 click(): Promise<void>;
2038
2039 /**
2040 * Schedules a command to type a sequence on the DOM element represented by
2041 * this instance.
2042 *
2043 * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
2044 * processed in the key sequence, that key state is toggled until one of the
2045 * following occurs:
2046 *
2047 * - The modifier key is encountered again in the sequence. At this point the
2048 * state of the key is toggled (along with the appropriate keyup/down
2049 * events).
2050 * - The {@link input.Key.NULL} key is encountered in the sequence. When
2051 * this key is encountered, all modifier keys current in the down state are
2052 * released (with accompanying keyup events). The NULL key can be used to
2053 * simulate common keyboard shortcuts:
2054 *
2055 * element.sendKeys('text was',
2056 * Key.CONTROL, 'a', Key.NULL,
2057 * 'now text is');
2058 * // Alternatively:
2059 * element.sendKeys('text was',
2060 * Key.chord(Key.CONTROL, 'a'),
2061 * 'now text is');
2062 *
2063 * - The end of the key sequence is encountered. When there are no more keys
2064 * to type, all depressed modifier keys are released (with accompanying
2065 * keyup events).
2066 *
2067 * If this element is a file input ({@code <input type='file'>}), the
2068 * specified key sequence should specify the path to the file to attach to
2069 * the element. This is analogous to the user clicking 'Browse...' and
2070 * entering the path into the file select dialog.
2071 *
2072 * var form = driver.findElement(By.css('form'));
2073 * var element = form.findElement(By.css('input[type=file]'));
2074 * element.sendKeys('/path/to/file.txt');
2075 * form.submit();
2076 *
2077 * For uploads to function correctly, the entered path must reference a file
2078 * on the _browser's_ machine, not the local machine running this script. When
2079 * running against a remote Selenium server, a {@link input.FileDetector}
2080 * may be used to transparently copy files to the remote machine before
2081 * attempting to upload them in the browser.
2082 *
2083 * __Note:__ On browsers where native keyboard events are not supported
2084 * (e.g. Firefox on OS X), key events will be synthesized. Special
2085 * punctuation keys will be synthesized according to a standard QWERTY en-us
2086 * keyboard layout.
2087 *
2088 * @param {...(number|string|!IThenable<(number|string)>)} var_args The
2089 * sequence of keys to type. Number keys may be referenced numerically or
2090 * by string (1 or '1'). All arguments will be joined into a single
2091 * sequence.
2092 * @return {!Promise} A promise that will be resolved when all
2093 * keys have been typed.
2094 */
2095 sendKeys(...var_args: Array<number|string|Promise<string|number>>): Promise<void>;
2096
2097 /**
2098 * Schedules a command to query for the tag/node name of this element.
2099 * @return {!Promise} A promise that will be resolved with the
2100 * element's tag name.
2101 */
2102 getTagName(): Promise<string>;
2103
2104 /**
2105 * Schedules a command to query for the computed style of the element
2106 * represented by this instance. If the element inherits the named style from
2107 * its parent, the parent will be queried for its value. Where possible,
2108 * color values will be converted to their hex representation (e.g. #00ff00
2109 * instead of rgb(0, 255, 0)). <p/> <em>Warning:</em> the value returned will
2110 * be as the browser interprets it, so it may be tricky to form a proper
2111 * assertion.
2112 *
2113 * @param {string} cssStyleProperty The name of the CSS style property to look
2114 * up.
2115 * @return {!Promise} A promise that will be resolved with the
2116 * requested CSS value.
2117 */
2118 getCssValue(cssStyleProperty: string): Promise<string>;
2119
2120 /**
2121 * Schedules a command to query for the value of the given attribute of the
2122 * element. Will return the current value even if it has been modified after
2123 * the page has been loaded. More exactly, this method will return the value
2124 * of the given attribute, unless that attribute is not present, in which case
2125 * the value of the property with the same name is returned. If neither value
2126 * is set, null is returned. The 'style' attribute is converted as best can be
2127 * to a text representation with a trailing semi-colon. The following are
2128 * deemed to be 'boolean' attributes and will be returned as thus:
2129 *
2130 * <p>async, autofocus, autoplay, checked, compact, complete, controls,
2131 * declare, defaultchecked, defaultselected, defer, disabled, draggable,
2132 * ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap,
2133 * itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate,
2134 * nowrap, open, paused, pubdate, readonly, required, reversed, scoped,
2135 * seamless, seeking, selected, spellcheck, truespeed, willvalidate
2136 *
2137 * <p>Finally, the following commonly mis-capitalized attribute/property names
2138 * are evaluated as expected:
2139 * <ul>
2140 * <li>'class'
2141 * <li>'readonly'
2142 * </ul>
2143 * @param {string} attributeName The name of the attribute to query.
2144 * @return {!Promise} A promise that will be resolved with the
2145 * attribute's value.
2146 */
2147 getAttribute(attributeName: string): Promise<string>;
2148
2149 /**
2150 * Get the visible (i.e. not hidden by CSS) innerText of this element,
2151 * including sub-elements, without any leading or trailing whitespace.
2152 * @return {!Promise} A promise that will be resolved with the
2153 * element's visible text.
2154 */
2155 getText(): Promise<string>;
2156
2157 /**
2158 * Schedules a command to compute the size of this element's bounding box, in
2159 * pixels.
2160 * @return {!Promise} A promise that will be resolved with the
2161 * element's size as a {@code {width:number, height:number}} object.
2162 */
2163 getSize(): Promise<ISize>;
2164
2165 /**
2166 * Returns an object describing an element's location, in pixels relative to
2167 * the document element, and the element's size in pixels.
2168 */
2169 getRect(): Promise<IRectangle>;
2170
2171 /**
2172 * Schedules a command to compute the location of this element in page space.
2173 * @return {!Promise} A promise that will be resolved to the
2174 * element's location as a {@code {x:number, y:number}} object.
2175 */
2176 getLocation(): Promise<ILocation>;
2177
2178 /**
2179 * Schedules a command to query whether the DOM element represented by this
2180 * instance is enabled, as dicted by the {@code disabled} attribute.
2181 * @return {!Promise} A promise that will be resolved with
2182 * whether this element is currently enabled.
2183 */
2184 isEnabled(): Promise<boolean>;
2185
2186 /**
2187 * Schedules a command to query whether this element is selected.
2188 * @return {!Promise} A promise that will be resolved with
2189 * whether this element is currently selected.
2190 */
2191 isSelected(): Promise<boolean>;
2192
2193 /**
2194 * Schedules a command to submit the form containing this element (or this
2195 * element if it is a FORM element). This command is a no-op if the element is
2196 * not contained in a form.
2197 * @return {!Promise} A promise that will be resolved when
2198 * the form has been submitted.
2199 */
2200 submit(): Promise<void>;
2201
2202 /**
2203 * Schedules a command to clear the {@code value} of this element. This
2204 * command has no effect if the underlying DOM element is neither a text INPUT
2205 * element nor a TEXTAREA element.
2206 * @return {!Promise} A promise that will be resolved when
2207 * the element has been cleared.
2208 */
2209 clear(): Promise<void>;
2210
2211 /**
2212 * Schedules a command to test whether this element is currently displayed.
2213 * @return {!Promise} A promise that will be resolved with
2214 * whether this element is currently visible on the page.
2215 */
2216 isDisplayed(): Promise<boolean>;
2217
2218 /**
2219 * @return {!Promise.<WebElement.Id>} A promise
2220 * that resolves to this element's JSON representation as defined by the
2221 * WebDriver wire protocol.
2222 * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
2223 */
2224 getId(): Promise<IWebElementId>;
2225
2226 // endregion
2227}
2228
2229export interface IWebElementFinders {
2230 /**
2231 * Schedule a command to find a descendant of this element. If the element
2232 * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will
2233 * be returned by the driver. Unlike other commands, this error cannot be
2234 * suppressed. In other words, scheduling a command to find an element doubles
2235 * as an assert that the element is present on the page. To test whether an
2236 * element is present on the page, use {@code #findElements}.
2237 *
2238 * <p>The search criteria for an element may be defined using one of the
2239 * factories in the {@link By} namespace, or as a short-hand
2240 * {@link By.Hash} object. For example, the following two statements
2241 * are equivalent:
2242 * <code><pre>
2243 * var e1 = element.findElement(By.id('foo'));
2244 * var e2 = element.findElement({id:'foo'});
2245 * </pre></code>
2246 *
2247 * <p>You may also provide a custom locator function, which takes as input
2248 * this WebDriver instance and returns a {@link WebElement}, or a
2249 * promise that will resolve to a WebElement. For example, to find the first
2250 * visible link on a page, you could write:
2251 * <code><pre>
2252 * var link = element.findElement(firstVisibleLink);
2253 *
2254 * function firstVisibleLink(element) {
2255 * var links = element.findElements(By.tagName('a'));
2256 * return promise.filter(links, function(link) {
2257 * return links.isDisplayed();
2258 * }).then(function(visibleLinks) {
2259 * return visibleLinks[0];
2260 * });
2261 * }
2262 * </pre></code>
2263 *
2264 * @param {!(Locator|By.Hash|Function)} locator The
2265 * locator strategy to use when searching for the element.
2266 * @return {!WebElement} A WebElement that can be used to issue
2267 * commands against the located element. If the element is not found, the
2268 * element will be invalidated and all scheduled commands aborted.
2269 */
2270 findElement(locator: Locator): WebElementPromise;
2271
2272 /**
2273 * Schedules a command to find all of the descendants of this element that
2274 * match the given search criteria.
2275 *
2276 * @param {!(Locator|By.Hash|Function)} locator The
2277 * locator strategy to use when searching for the elements.
2278 * @return {!Promise.<!Array.<!WebElement>>} A
2279 * promise that will resolve to an array of WebElements.
2280 */
2281 findElements(locator: Locator): Promise<WebElement[]>;
2282}
2283
2284/**
2285 * Defines an object that can be asynchronously serialized to its WebDriver
2286 * wire representation.
2287 *
2288 * @constructor
2289 * @template T
2290 */
2291export interface Serializable<T> {
2292 /**
2293 * Returns either this instance's serialized represention, if immediately
2294 * available, or a promise for its serialized representation. This function is
2295 * conceptually equivalent to objects that have a {@code toJSON()} property,
2296 * except the serialize() result may be a promise or an object containing a
2297 * promise (which are not directly JSON friendly).
2298 *
2299 * @return {!(T|IThenable.<!T>)} This instance's serialized wire format.
2300 */
2301 serialize(): T|Promise<T>;
2302}
2303
2304/**
2305 * Represents a DOM element. WebElements can be found by searching from the
2306 * document root using a {@link WebDriver} instance, or by searching
2307 * under another WebElement:
2308 *
2309 * driver.get('http://www.google.com');
2310 * var searchForm = driver.findElement(By.tagName('form'));
2311 * var searchBox = searchForm.findElement(By.name('q'));
2312 * searchBox.sendKeys('webdriver');
2313 *
2314 * The WebElement is implemented as a promise for compatibility with the promise
2315 * API. It will always resolve itself when its internal state has been fully
2316 * resolved and commands may be issued against the element. This can be used to
2317 * catch errors when an element cannot be located on the page:
2318 *
2319 * driver.findElement(By.id('not-there')).then(function(element) {
2320 * alert('Found an element that was not expected to be there!');
2321 * }, function(error) {
2322 * alert('The element was not found, as expected');
2323 * });
2324 *
2325 * @extends {Serializable.<WebElement.Id>}
2326 */
2327export class WebElement implements Serializable<IWebElementId> {
2328 /**
2329 * @param {!WebDriver} driver the parent WebDriver instance for this element.
2330 * @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
2331 * the underlying DOM element.
2332 */
2333 constructor(driver: WebDriver, id: Promise<string>|string);
2334
2335 /**
2336 * @param {string} id The raw ID.
2337 * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key.
2338 * @return {!Object} The element ID for use with WebDriver's wire protocol.
2339 */
2340 static buildId(id: string, opt_noLegacy?: boolean): IWebElementId;
2341
2342 /**
2343 * Extracts the encoded WebElement ID from the object.
2344 *
2345 * @param {?} obj The object to extract the ID from.
2346 * @return {string} the extracted ID.
2347 * @throws {TypeError} if the object is not a valid encoded ID.
2348 */
2349 static extractId(obj: IWebElementId): string;
2350
2351 /**
2352 * @param {?} obj the object to test.
2353 * @return {boolean} whether the object is a valid encoded WebElement ID.
2354 */
2355 static isId(obj: IWebElementId): boolean;
2356
2357 /**
2358 * Compares two WebElements for equality.
2359 *
2360 * @param {!WebElement} a A WebElement.
2361 * @param {!WebElement} b A WebElement.
2362 * @return {!Promise<boolean>} A promise that will be
2363 * resolved to whether the two WebElements are equal.
2364 */
2365 static equals(a: WebElement, b: WebElement): Promise<boolean>;
2366
2367 /**
2368 * @return {!WebDriver} The parent driver for this instance.
2369 */
2370 getDriver(): WebDriver;
2371
2372 /**
2373 * @return {!Promise<string>} A promise that resolves to
2374 * the server-assigned opaque ID assigned to this element.
2375 */
2376 getId(): Promise<string>;
2377
2378 /**
2379 * Schedule a command to find a descendant of this element. If the element
2380 * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will
2381 * be returned by the driver. Unlike other commands, this error cannot be
2382 * suppressed. In other words, scheduling a command to find an element doubles
2383 * as an assert that the element is present on the page. To test whether an
2384 * element is present on the page, use {@link #findElements}.
2385 *
2386 * The search criteria for an element may be defined using one of the
2387 * factories in the {@link By} namespace, or as a short-hand
2388 * {@link By.Hash} object. For example, the following two statements
2389 * are equivalent:
2390 *
2391 * var e1 = element.findElement(By.id('foo'));
2392 * var e2 = element.findElement({id:'foo'});
2393 *
2394 * You may also provide a custom locator function, which takes as input
2395 * this WebDriver instance and returns a {@link WebElement}, or a
2396 * promise that will resolve to a WebElement. For example, to find the first
2397 * visible link on a page, you could write:
2398 *
2399 * var link = element.findElement(firstVisibleLink);
2400 *
2401 * function firstVisibleLink(element) {
2402 * var links = element.findElements(By.tagName('a'));
2403 * return promise.filter(links, function(link) {
2404 * return links.isDisplayed();
2405 * }).then(function(visibleLinks) {
2406 * return visibleLinks[0];
2407 * });
2408 * }
2409 *
2410 * @param {!(by.By|Function)} locator The locator strategy to use when
2411 * searching for the element.
2412 * @return {!WebElementPromise} A WebElement that can be used to issue
2413 * commands against the located element. If the element is not found, the
2414 * element will be invalidated and all scheduled commands aborted.
2415 */
2416 findElement(locator: Locator): WebElementPromise;
2417
2418 /**
2419 * Schedules a command to find all of the descendants of this element that
2420 * match the given search criteria.
2421 *
2422 * @param {!(by.By|Function)} locator The locator strategy to use when
2423 * searching for the element.
2424 * @return {!Promise<!Array<!WebElement>>} A
2425 * promise that will resolve to an array of WebElements.
2426 */
2427 findElements(locator: Locator): Promise<WebElement[]>;
2428
2429 /**
2430 * Schedules a command to click on this element.
2431 * @return {!Promise.<void>} A promise that will be resolved
2432 * when the click command has completed.
2433 */
2434 click(): Promise<void>;
2435
2436 /**
2437 * Schedules a command to type a sequence on the DOM element represented by
2438 * this promsieinstance.
2439 *
2440 * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
2441 * processed in the keysequence, that key state is toggled until one of the
2442 * following occurs:
2443 *
2444 * - The modifier key is encountered again in the sequence. At this point the
2445 * state of the key is toggled (along with the appropriate keyup/down
2446 * events).
2447 * - The {@link Key.NULL} key is encountered in the sequence. When
2448 * this key is encountered, all modifier keys current in the down state are
2449 * released (with accompanying keyup events). The NULL key can be used to
2450 * simulate common keyboard shortcuts:
2451 *
2452 * element.sendKeys('text was',
2453 * Key.CONTROL, 'a', Key.NULL,
2454 * 'now text is');
2455 * // Alternatively:
2456 * element.sendKeys('text was',
2457 * Key.chord(Key.CONTROL, 'a'),
2458 * 'now text is');
2459 *
2460 * - The end of the keysequence is encountered. When there are no more keys
2461 * to type, all depressed modifier keys are released (with accompanying
2462 * keyup events).
2463 *
2464 * If this element is a file input ({@code <input type='file'>}), the
2465 * specified key sequence should specify the path to the file to attach to
2466 * the element. This is analgous to the user clicking 'Browse...' and entering
2467 * the path into the file select dialog.
2468 *
2469 * var form = driver.findElement(By.css('form'));
2470 * var element = form.findElement(By.css('input[type=file]'));
2471 * element.sendKeys('/path/to/file.txt');
2472 * form.submit();
2473 *
2474 * For uploads to function correctly, the entered path must reference a file
2475 * on the _browser's_ machine, not the local machine running this script. When
2476 * running against a remote Selenium server, a {@link FileDetector}
2477 * may be used to transparently copy files to the remote machine before
2478 * attempting to upload them in the browser.
2479 *
2480 * __Note:__ On browsers where native keyboard events are not supported
2481 * (e.g. Firefox on OS X), key events will be synthesized. Special
2482 * punctionation keys will be synthesized according to a standard QWERTY en-us
2483 * keyboard layout.
2484 *
2485 * @param {...(string|!Promise<string>)} var_args The sequence
2486 * of keys to type. All arguments will be joined into a single sequence.
2487 * @return {!Promise.<void>} A promise that will be resolved
2488 * when all keys have been typed.
2489 */
2490 sendKeys(...var_args: Array<string|number|Promise<string|number>>): Promise<void>;
2491
2492 /**
2493 * Schedules a command to query for the tag/node name of this element.
2494 * @return {!Promise.<string>} A promise that will be
2495 * resolved with the element's tag name.
2496 */
2497 getTagName(): Promise<string>;
2498
2499 /**
2500 * Schedules a command to query for the computed style of the element
2501 * represented by this instance. If the element inherits the named style from
2502 * its parent, the parent will be queried for its value. Where possible,
2503 * color values will be converted to their hex representation (e.g. #00ff00
2504 * instead of rgb(0, 255, 0)).
2505 *
2506 * _Warning:_ the value returned will be as the browser interprets it, so
2507 * it may be tricky to form a proper assertion.
2508 *
2509 * @param {string} cssStyleProperty The name of the CSS style property to look
2510 * up.
2511 * @return {!Promise<string>} A promise that will be
2512 * resolved with the requested CSS value.
2513 */
2514 getCssValue(cssStyleProperty: string): Promise<string>;
2515
2516 /**
2517 * Schedules a command to query for the value of the given attribute of the
2518 * element. Will return the current value, even if it has been modified after
2519 * the page has been loaded. More exactly, this method will return the value
2520 * of the given attribute, unless that attribute is not present, in which case
2521 * the value of the property with the same name is returned. If neither value
2522 * is set, null is returned (for example, the 'value' property of a textarea
2523 * element). The 'style' attribute is converted as best can be to a
2524 * text representation with a trailing semi-colon. The following are deemed to
2525 * be 'boolean' attributes and will return either 'true' or null:
2526 *
2527 * async, autofocus, autoplay, checked, compact, complete, controls, declare,
2528 * defaultchecked, defaultselected, defer, disabled, draggable, ended,
2529 * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
2530 * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
2531 * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
2532 * selected, spellcheck, truespeed, willvalidate
2533 *
2534 * Finally, the following commonly mis-capitalized attribute/property names
2535 * are evaluated as expected:
2536 *
2537 * - 'class'
2538 * - 'readonly'
2539 *
2540 * @param {string} attributeName The name of the attribute to query.
2541 * @return {!Promise.<?string>} A promise that will be
2542 * resolved with the attribute's value. The returned value will always be
2543 * either a string or null.
2544 */
2545 getAttribute(attributeName: string): Promise<string>;
2546
2547 /**
2548 * Get the visible (i.e. not hidden by CSS) innerText of this element,
2549 * including sub-elements, without any leading or trailing whitespace.
2550 * @return {!Promise.<string>} A promise that will be
2551 * resolved with the element's visible text.
2552 */
2553 getText(): Promise<string>;
2554
2555 /**
2556 * DEPRECATED 3.0
2557 * Schedules a command to compute the size of this element's bounding box, in
2558 * pixels.
2559 * @return {!Promise.<{width: number, height: number}>} A
2560 * promise that will be resolved with the element's size as a
2561 * {@code {width:number, height:number}} object.
2562 */
2563 getSize(): Promise<ISize>;
2564
2565 /**
2566 * Returns an object describing an element's location, in pixels relative to
2567 * the document element, and the element's size in pixels.
2568 */
2569 getRect(): Promise<IRectangle>;
2570
2571 /**
2572 * DEPRECATED 3.0
2573 * Schedules a command to compute the location of this element in page space.
2574 * @return {!Promise.<{x: number, y: number}>} A promise that
2575 * will be resolved to the element's location as a
2576 * {@code {x:number, y:number}} object.
2577 */
2578 getLocation(): Promise<ILocation>;
2579
2580 /**
2581 * Schedules a command to query whether the DOM element represented by this
2582 * instance is enabled, as dicted by the {@code disabled} attribute.
2583 * @return {!Promise.<boolean>} A promise that will be
2584 * resolved with whether this element is currently enabled.
2585 */
2586 isEnabled(): Promise<boolean>;
2587
2588 /**
2589 * Schedules a command to query whether this element is selected.
2590 * @return {!Promise.<boolean>} A promise that will be
2591 * resolved with whether this element is currently selected.
2592 */
2593 isSelected(): Promise<boolean>;
2594
2595 /**
2596 * Schedules a command to submit the form containing this element (or this
2597 * element if it is a FORM element). This command is a no-op if the element is
2598 * not contained in a form.
2599 * @return {!Promise.<void>} A promise that will be resolved
2600 * when the form has been submitted.
2601 */
2602 submit(): Promise<void>;
2603
2604 /**
2605 * Schedules a command to clear the `value` of this element. This command has
2606 * no effect if the underlying DOM element is neither a text INPUT element
2607 * nor a TEXTAREA element.
2608 * @return {!Promise<void>} A promise that will be resolved
2609 * when the element has been cleared.
2610 */
2611 clear(): Promise<void>;
2612
2613 /**
2614 * Schedules a command to test whether this element is currently displayed.
2615 * @return {!Promise.<boolean>} A promise that will be
2616 * resolved with whether this element is currently visible on the page.
2617 */
2618 isDisplayed(): Promise<boolean>;
2619
2620 /**
2621 * Take a screenshot of the visible region encompassed by this element's
2622 * bounding rectangle.
2623 *
2624 * @param {boolean=} opt_scroll Optional argument that indicates whether the
2625 * element should be scrolled into view before taking a screenshot.
2626 * Defaults to false.
2627 * @return {!Promise<string>} A promise that will be
2628 * resolved to the screenshot as a base-64 encoded PNG.
2629 */
2630 takeScreenshot(opt_scroll?: boolean): Promise<string>;
2631
2632 /** @override */
2633 serialize(): Promise<IWebElementId>;
2634}
2635
2636/**
2637 * WebElementPromise is a promise that will be fulfilled with a WebElement.
2638 * This serves as a forward proxy on WebElement, allowing calls to be
2639 * scheduled without directly on this instance before the underlying
2640 * WebElement has been fulfilled. In other words, the following two statements
2641 * are equivalent:
2642 * <pre><code>
2643 * driver.findElement({id: 'my-button'}).click();
2644 * driver.findElement({id: 'my-button'}).then(function(el) {
2645 * return el.click();
2646 * });
2647 * </code></pre>
2648 *
2649 * @param {!WebDriver} driver The parent WebDriver instance for this
2650 * element.
2651 * @param {!Promise.<!WebElement>} el A promise
2652 * that will resolve to the promised element.
2653 * @constructor
2654 * @extends {WebElement}
2655 * @implements {promise.Thenable.<!WebElement>}
2656 * @final
2657 */
2658export interface WebElementPromise extends Promise<WebElement> {}
2659
2660/**
2661 * Implement WebElementPromise
2662 */
2663export class WebElementPromise extends WebElement {
2664 /**
2665 * @param {!WebDriver} driver The parent WebDriver instance for this
2666 * element.
2667 * @param {!Promise<!WebElement>} el A promise
2668 * that will resolve to the promised element.
2669 */
2670 constructor(driver: WebDriver, el: Promise<WebElement>);
2671}
2672
2673/**
2674 * Contains information about a WebDriver session.
2675 */
2676export class Session {
2677 // region Constructors
2678
2679 /**
2680 * @param {string} id The session ID.
2681 * @param {!(Object|Capabilities)} capabilities The session
2682 * capabilities.
2683 * @constructor
2684 */
2685 constructor(id: string, capabilities: Capabilities|{});
2686
2687 // endregion
2688
2689 // region Methods
2690
2691 /**
2692 * @return {string} This session's ID.
2693 */
2694 getId(): string;
2695
2696 /**
2697 * @return {!Capabilities} This session's capabilities.
2698 */
2699 getCapabilities(): Capabilities;
2700
2701 /**
2702 * Retrieves the value of a specific capability.
2703 * @param {string} key The capability to retrieve.
2704 * @return {*} The capability value.
2705 */
2706 getCapability(key: string): any;
2707
2708 /**
2709 * Returns the JSON representation of this object, which is just the string
2710 * session ID.
2711 * @return {string} The JSON representation of this Session.
2712 */
2713 toJSON(): string;
2714
2715 // endregion
2716}
2717
\No newline at end of file