-
-
Notifications
You must be signed in to change notification settings - Fork 8k
/
webdriver.js
2347 lines (2063 loc) · 81.8 KB
/
webdriver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The heart of the WebDriver JavaScript API.
*/
goog.provide('webdriver.Alert');
goog.provide('webdriver.AlertPromise');
goog.provide('webdriver.UnhandledAlertError');
goog.provide('webdriver.WebDriver');
goog.provide('webdriver.WebElement');
goog.provide('webdriver.WebElementPromise');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
goog.require('bot.response');
goog.require('goog.array');
goog.require('goog.object');
goog.require('webdriver.ActionSequence');
goog.require('webdriver.Command');
goog.require('webdriver.CommandName');
goog.require('webdriver.Key');
goog.require('webdriver.Locator');
goog.require('webdriver.Session');
goog.require('webdriver.logging');
goog.require('webdriver.promise');
goog.require('webdriver.until');
//////////////////////////////////////////////////////////////////////////////
//
// webdriver.WebDriver
//
//////////////////////////////////////////////////////////////////////////////
/**
* Creates a new WebDriver client, which provides control over a browser.
*
* Every WebDriver command returns a {@code webdriver.promise.Promise} that
* represents the result of that command. Callbacks may be registered on this
* object to manipulate the command result or catch an expected error. Any
* commands scheduled with a callback are considered sub-commands and will
* execute before the next command in the current frame. For example:
* <pre><code>
* var message = [];
* driver.call(message.push, message, 'a').then(function() {
* driver.call(message.push, message, 'b');
* });
* driver.call(message.push, message, 'c');
* driver.call(function() {
* alert('message is abc? ' + (message.join('') == 'abc'));
* });
* </code></pre>
*
* @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a
* known session or a promise that will be resolved to a session.
* @param {!webdriver.CommandExecutor} executor The executor to use when
* sending commands to the browser.
* @param {webdriver.promise.ControlFlow=} opt_flow The flow to
* schedule commands through. Defaults to the active flow object.
* @constructor
*/
webdriver.WebDriver = function(session, executor, opt_flow) {
/** @private {!(webdriver.Session|webdriver.promise.Promise)} */
this.session_ = session;
/** @private {!webdriver.CommandExecutor} */
this.executor_ = executor;
/** @private {!webdriver.promise.ControlFlow} */
this.flow_ = opt_flow || webdriver.promise.controlFlow();
};
/**
* Creates a new WebDriver client for an existing session.
* @param {!webdriver.CommandExecutor} executor Command executor to use when
* querying for session details.
* @param {string} sessionId ID of the session to attach to.
* @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver
* commands should execute under. Defaults to the
* {@link webdriver.promise.controlFlow() currently active} control flow.
* @return {!webdriver.WebDriver} A new client for the specified session.
*/
webdriver.WebDriver.attachToSession = function(executor, sessionId, opt_flow) {
return webdriver.WebDriver.acquireSession_(executor,
new webdriver.Command(webdriver.CommandName.DESCRIBE_SESSION).
setParameter('sessionId', sessionId),
'WebDriver.attachToSession()',
opt_flow);
};
/**
* Creates a new WebDriver session.
* @param {!webdriver.CommandExecutor} executor The executor to create the new
* session with.
* @param {!webdriver.Capabilities} desiredCapabilities The desired
* capabilities for the new session.
* @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver
* commands should execute under, including the initial session creation.
* Defaults to the {@link webdriver.promise.controlFlow() currently active}
* control flow.
* @return {!webdriver.WebDriver} The driver for the newly created session.
*/
webdriver.WebDriver.createSession = function(
executor, desiredCapabilities, opt_flow) {
return webdriver.WebDriver.acquireSession_(executor,
new webdriver.Command(webdriver.CommandName.NEW_SESSION).
setParameter('desiredCapabilities', desiredCapabilities),
'WebDriver.createSession()',
opt_flow);
};
/**
* Sends a command to the server that is expected to return the details for a
* {@link webdriver.Session}. This may either be an existing session, or a
* newly created one.
* @param {!webdriver.CommandExecutor} executor Command executor to use when
* querying for session details.
* @param {!webdriver.Command} command The command to send to fetch the session
* details.
* @param {string} description A descriptive debug label for this action.
* @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver
* commands should execute under. Defaults to the
* {@link webdriver.promise.controlFlow() currently active} control flow.
* @return {!webdriver.WebDriver} A new WebDriver client for the session.
* @private
*/
webdriver.WebDriver.acquireSession_ = function(
executor, command, description, opt_flow) {
var flow = opt_flow || webdriver.promise.controlFlow();
var session = flow.execute(function() {
return webdriver.WebDriver.executeCommand_(executor, command).
then(function(response) {
bot.response.checkResponse(response);
return new webdriver.Session(response['sessionId'],
response['value']);
});
}, description);
return new webdriver.WebDriver(session, executor, flow);
};
/**
* Converts an object to its JSON representation in the WebDriver wire protocol.
* When converting values of type object, the following steps will be taken:
* <ol>
* <li>if the object is a WebElement, the return value will be the element's
* server ID</li>
* <li>if the object provides a "toJSON" function, the return value of this
* function will be returned</li>
* <li>otherwise, the value of each key will be recursively converted according
* to the rules above.</li>
* </ol>
*
* @param {*} obj The object to convert.
* @return {!webdriver.promise.Promise.<?>} A promise that will resolve to the
* input value's JSON representation.
* @private
* @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
*/
webdriver.WebDriver.toWireValue_ = function(obj) {
if (webdriver.promise.isPromise(obj)) {
return obj.then(webdriver.WebDriver.toWireValue_);
}
return webdriver.promise.fulfilled(convertValue(obj));
function convertValue(value) {
switch (goog.typeOf(value)) {
case 'array':
return convertKeys(value, true);
case 'object':
if (value instanceof webdriver.WebElement) {
return value.getId();
}
if (goog.isFunction(value.toJSON)) {
return value.toJSON();
}
if (goog.isNumber(value.nodeType) && goog.isString(value.nodeName)) {
throw new TypeError(
'Invalid argument type: ' + value.nodeName +
'(' + value.nodeType + ')');
}
return convertKeys(value, false);
case 'function':
return '' + value;
case 'undefined':
return null;
default:
return value;
}
}
function convertKeys(obj, isArray) {
var numKeys = isArray ? obj.length : goog.object.getCount(obj);
var ret = isArray ? new Array(numKeys) : {};
if (!numKeys) {
return webdriver.promise.fulfilled(ret);
}
var numResolved = 0;
var done = webdriver.promise.defer();
// forEach will stop iteration at undefined, where we want to convert
// these to null and keep iterating.
var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) {
var n = arr.length;
for (var i = 0; i < n; i++) {
fn(arr[i], i);
}
};
forEachKey(obj, function(value, key) {
if (webdriver.promise.isPromise(value)) {
value.then(webdriver.WebDriver.toWireValue_).
then(setValue, done.reject);
} else {
webdriver.promise.asap(convertValue(value), setValue, done.reject);
}
function setValue(value) {
ret[key] = value;
maybeFulfill();
}
});
return done.promise;
function maybeFulfill() {
if (++numResolved === numKeys) {
done.fulfill(ret);
}
}
}
};
/**
* Converts a value from its JSON representation according to the WebDriver wire
* protocol. Any JSON object containing a
* {@code webdriver.WebElement.ELEMENT_KEY} key will be decoded to a
* {@code webdriver.WebElement} object. All other values will be passed through
* as is.
* @param {!webdriver.WebDriver} driver The driver instance to use as the
* parent of any unwrapped {@code webdriver.WebElement} values.
* @param {*} value The value to convert.
* @return {*} The converted value.
* @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
* @private
*/
webdriver.WebDriver.fromWireValue_ = function(driver, value) {
if (goog.isArray(value)) {
value = goog.array.map(/**@type {goog.array.ArrayLike}*/ (value),
goog.partial(webdriver.WebDriver.fromWireValue_, driver));
} else if (value && goog.isObject(value) && !goog.isFunction(value)) {
if (webdriver.WebElement.ELEMENT_KEY in value) {
value = new webdriver.WebElement(driver, value);
} else {
value = goog.object.map(/**@type {!Object}*/ (value),
goog.partial(webdriver.WebDriver.fromWireValue_, driver));
}
}
return value;
};
/**
* Translates a command to its wire-protocol representation before passing it
* to the given {@code executor} for execution.
* @param {!webdriver.CommandExecutor} executor The executor to use.
* @param {!webdriver.Command} command The command to execute.
* @return {!webdriver.promise.Promise} A promise that will resolve with the
* command response.
* @private
*/
webdriver.WebDriver.executeCommand_ = function(executor, command) {
return webdriver.WebDriver.toWireValue_(command.getParameters()).
then(function(parameters) {
command.setParameters(parameters);
return webdriver.promise.checkedNodeCall(
goog.bind(executor.execute, executor, command));
});
};
/**
* @return {!webdriver.promise.ControlFlow} The control flow used by this
* instance.
*/
webdriver.WebDriver.prototype.controlFlow = function() {
return this.flow_;
};
/**
* Schedules a {@code webdriver.Command} to be executed by this driver's
* {@code webdriver.CommandExecutor}.
* @param {!webdriver.Command} command The command to schedule.
* @param {string} description A description of the command for debugging.
* @return {!webdriver.promise.Promise.<T>} A promise that will be resolved
* with the command result.
* @template T
*/
webdriver.WebDriver.prototype.schedule = function(command, description) {
var self = this;
checkHasNotQuit();
command.setParameter('sessionId', this.session_);
// If any of the command parameters are rejected promises, those
// rejections may be reported as unhandled before the control flow
// attempts to execute the command. To ensure parameters errors
// propagate through the command itself, we resolve all of the
// command parameters now, but suppress any errors until the ControlFlow
// actually executes the command. This addresses scenarios like catching
// an element not found error in:
//
// driver.findElement(By.id('foo')).click().thenCatch(function(e) {
// if (e.code === bot.ErrorCode.NO_SUCH_ELEMENT) {
// // Do something.
// }
// });
var prepCommand = webdriver.WebDriver.toWireValue_(command.getParameters());
prepCommand.thenCatch(goog.nullFunction);
var flow = this.flow_;
var executor = this.executor_;
return flow.execute(function() {
// A call to WebDriver.quit() may have been scheduled in the same event
// loop as this |command|, which would prevent us from detecting that the
// driver has quit above. Therefore, we need to make another quick check.
// We still check above so we can fail as early as possible.
checkHasNotQuit();
// Retrieve resolved command parameters; any previously suppressed errors
// will now propagate up through the control flow as part of the command
// execution.
return prepCommand.then(function(parameters) {
command.setParameters(parameters);
return webdriver.promise.checkedNodeCall(
goog.bind(executor.execute, executor, command));
});
}, description).then(function(response) {
try {
bot.response.checkResponse(response);
} catch (ex) {
var value = response['value'];
if (ex.code === bot.ErrorCode.UNEXPECTED_ALERT_OPEN) {
var text = value && value['alert'] ? value['alert']['text'] : '';
throw new webdriver.UnhandledAlertError(ex.message, text,
new webdriver.Alert(self, text));
}
throw ex;
}
return webdriver.WebDriver.fromWireValue_(self, response['value']);
});
function checkHasNotQuit() {
if (!self.session_) {
throw new Error('This driver instance does not have a valid session ID ' +
'(did you call WebDriver.quit()?) and may no longer be ' +
'used.');
}
}
};
// ----------------------------------------------------------------------------
// Client command functions:
// ----------------------------------------------------------------------------
/**
* @return {!webdriver.promise.Promise.<!webdriver.Session>} A promise for this
* client's session.
*/
webdriver.WebDriver.prototype.getSession = function() {
return webdriver.promise.when(this.session_);
};
/**
* @return {!webdriver.promise.Promise.<!webdriver.Capabilities>} A promise
* that will resolve with the this instance's capabilities.
*/
webdriver.WebDriver.prototype.getCapabilities = function() {
return webdriver.promise.when(this.session_, function(session) {
return session.getCapabilities();
});
};
/**
* Schedules a command to quit the current session. After calling quit, this
* instance will be invalidated and may no longer be used to issue commands
* against the browser.
* @return {!webdriver.promise.Promise.<void>} A promise that will be resolved
* when the command has completed.
*/
webdriver.WebDriver.prototype.quit = function() {
var result = this.schedule(
new webdriver.Command(webdriver.CommandName.QUIT),
'WebDriver.quit()');
// Delete our session ID when the quit command finishes; this will allow us to
// throw an error when attemnpting to use a driver post-quit.
return result.thenFinally(goog.bind(function() {
delete this.session_;
}, this));
};
/**
* Creates a new action sequence using this driver. The sequence will not be
* scheduled for execution until {@link webdriver.ActionSequence#perform} is
* called. Example:
* <pre><code>
* driver.actions().
* mouseDown(element1).
* mouseMove(element2).
* mouseUp().
* perform();
* </code></pre>
* @return {!webdriver.ActionSequence} A new action sequence for this instance.
*/
webdriver.WebDriver.prototype.actions = function() {
return new webdriver.ActionSequence(this);
};
/**
* Schedules a command to execute JavaScript in the context of the currently
* selected frame or window. The script fragment will be executed as the body
* of an anonymous function. If the script is provided as a function object,
* that function will be converted to a string for injection into the target
* window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the {@code arguments} object.
* Arguments may be a boolean, number, string, or {@code webdriver.WebElement}.
* Arrays and objects may also be used as script arguments as long as each item
* adheres to the types previously mentioned.
*
* The script may refer to any variables accessible from the current window.
* Furthermore, the script will execute in the window's context, thus
* {@code document} may be used to refer to the current document. Any local
* variables will not be available once the script has finished executing,
* though global variables will persist.
*
* If the script has a return value (i.e. if the script contains a return
* statement), then the following steps will be taken for resolving this
* functions return value:
* <ul>
* <li>For a HTML element, the value will resolve to a
* {@code webdriver.WebElement}</li>
* <li>Null and undefined return values will resolve to null</li>
* <li>Booleans, numbers, and strings will resolve as is</li>
* <li>Functions will resolve to their string representation</li>
* <li>For arrays and objects, each member item will be converted according to
* the rules above</li>
* </ul>
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} var_args The arguments to pass to the script.
* @return {!webdriver.promise.Promise.<T>} A promise that will resolve to the
* scripts return value.
* @template T
*/
webdriver.WebDriver.prototype.executeScript = function(script, var_args) {
if (goog.isFunction(script)) {
script = 'return (' + script + ').apply(null, arguments);';
}
var args = arguments.length > 1 ? goog.array.slice(arguments, 1) : [];
return this.schedule(
new webdriver.Command(webdriver.CommandName.EXECUTE_SCRIPT).
setParameter('script', script).
setParameter('args', args),
'WebDriver.executeScript()');
};
/**
* Schedules a command to execute asynchronous JavaScript in the context of the
* currently selected frame or window. The script fragment will be executed as
* the body of an anonymous function. If the script is provided as a function
* object, that function will be converted to a string for injection into the
* target window.
*
* Any arguments provided in addition to the script will be included as script
* arguments and may be referenced using the {@code arguments} object.
* Arguments may be a boolean, number, string, or {@code webdriver.WebElement}.
* Arrays and objects may also be used as script arguments as long as each item
* adheres to the types previously mentioned.
*
* Unlike executing synchronous JavaScript with
* {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with
* this function must explicitly signal they are finished by invoking the
* provided callback. This callback will always be injected into the
* executed function as the last argument, and thus may be referenced with
* {@code arguments[arguments.length - 1]}. The following steps will be taken
* for resolving this functions return value against the first argument to the
* script's callback function:
* <ul>
* <li>For a HTML element, the value will resolve to a
* {@code webdriver.WebElement}</li>
* <li>Null and undefined return values will resolve to null</li>
* <li>Booleans, numbers, and strings will resolve as is</li>
* <li>Functions will resolve to their string representation</li>
* <li>For arrays and objects, each member item will be converted according to
* the rules above</li>
* </ul>
*
* Example #1: Performing a sleep that is synchronized with the currently
* selected window:
* <code><pre>
* var start = new Date().getTime();
* driver.executeAsyncScript(
* 'window.setTimeout(arguments[arguments.length - 1], 500);').
* then(function() {
* console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
* });
* </pre></code>
*
* Example #2: Synchronizing a test with an AJAX application:
* <code><pre>
* var button = driver.findElement(By.id('compose-button'));
* button.click();
* driver.executeAsyncScript(
* 'var callback = arguments[arguments.length - 1];' +
* 'mailClient.getComposeWindowWidget().onload(callback);');
* driver.switchTo().frame('composeWidget');
* driver.findElement(By.id('to')).sendKeys('dog@example.com');
* </pre></code>
*
* Example #3: Injecting a XMLHttpRequest and waiting for the result. In this
* example, the inject script is specified with a function literal. When using
* this format, the function is converted to a string for injection, so it
* should not reference any symbols not defined in the scope of the page under
* test.
* <code><pre>
* driver.executeAsyncScript(function() {
* var callback = arguments[arguments.length - 1];
* var xhr = new XMLHttpRequest();
* xhr.open("GET", "/resource/data.json", true);
* xhr.onreadystatechange = function() {
* if (xhr.readyState == 4) {
* callback(xhr.responseText);
* }
* }
* xhr.send('');
* }).then(function(str) {
* console.log(JSON.parse(str)['food']);
* });
* </pre></code>
*
* @param {!(string|Function)} script The script to execute.
* @param {...*} var_args The arguments to pass to the script.
* @return {!webdriver.promise.Promise.<T>} A promise that will resolve to the
* scripts return value.
* @template T
*/
webdriver.WebDriver.prototype.executeAsyncScript = function(script, var_args) {
if (goog.isFunction(script)) {
script = 'return (' + script + ').apply(null, arguments);';
}
return this.schedule(
new webdriver.Command(webdriver.CommandName.EXECUTE_ASYNC_SCRIPT).
setParameter('script', script).
setParameter('args', goog.array.slice(arguments, 1)),
'WebDriver.executeScript()');
};
/**
* Schedules a command to execute a custom function.
* @param {function(...): (T|webdriver.promise.Promise.<T>)} fn The function to
* execute.
* @param {Object=} opt_scope The object in whose scope to execute the function.
* @param {...*} var_args Any arguments to pass to the function.
* @return {!webdriver.promise.Promise.<T>} A promise that will be resolved'
* with the function's result.
* @template T
*/
webdriver.WebDriver.prototype.call = function(fn, opt_scope, var_args) {
var args = goog.array.slice(arguments, 2);
var flow = this.flow_;
return flow.execute(function() {
return webdriver.promise.fullyResolved(args).then(function(args) {
if (webdriver.promise.isGenerator(fn)) {
args.unshift(fn, opt_scope);
return webdriver.promise.consume.apply(null, args);
}
return fn.apply(opt_scope, args);
});
}, 'WebDriver.call(' + (fn.name || 'function') + ')');
};
/**
* Schedules a command to wait for a condition to hold, as defined by some
* user supplied function. If any errors occur while evaluating the wait, they
* will be allowed to propagate.
*
* <p>In the event a condition returns a {@link webdriver.promise.Promise}, the
* polling loop will wait for it to be resolved and use the resolved value for
* evaluating whether the condition has been satisfied. The resolution time for
* a promise is factored into whether a wait has timed out.
*
* @param {!(webdriver.until.Condition.<T>|
* function(!webdriver.WebDriver): T)} condition Either a condition
* object, or a function to evaluate as a condition.
* @param {number} timeout How long to wait for the condition to be true.
* @param {string=} opt_message An optional message to use if the wait times
* out.
* @return {!webdriver.promise.Promise.<T>} A promise that will be fulfilled
* with the first truthy value returned by the condition function, or
* rejected if the condition times out.
* @template T
*/
webdriver.WebDriver.prototype.wait = function(
condition, timeout, opt_message) {
var message = opt_message;
var fn = /** @type {!Function} */(condition);
if (condition instanceof webdriver.until.Condition) {
message = message || condition.description();
fn = condition.fn;
}
var driver = this;
return this.flow_.wait(function() {
if (webdriver.promise.isGenerator(fn)) {
return webdriver.promise.consume(fn, null, [driver]);
}
return fn(driver);
}, timeout, message);
};
/**
* Schedules a command to make the driver sleep for the given amount of time.
* @param {number} ms The amount of time, in milliseconds, to sleep.
* @return {!webdriver.promise.Promise.<void>} A promise that will be resolved
* when the sleep has finished.
*/
webdriver.WebDriver.prototype.sleep = function(ms) {
return this.flow_.timeout(ms, 'WebDriver.sleep(' + ms + ')');
};
/**
* Schedules a command to retrieve they current window handle.
* @return {!webdriver.promise.Promise.<string>} A promise that will be
* resolved with the current window handle.
*/
webdriver.WebDriver.prototype.getWindowHandle = function() {
return this.schedule(
new webdriver.Command(webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE),
'WebDriver.getWindowHandle()');
};
/**
* Schedules a command to retrieve the current list of available window handles.
* @return {!webdriver.promise.Promise.<!Array.<string>>} A promise that will
* be resolved with an array of window handles.
*/
webdriver.WebDriver.prototype.getAllWindowHandles = function() {
return this.schedule(
new webdriver.Command(webdriver.CommandName.GET_WINDOW_HANDLES),
'WebDriver.getAllWindowHandles()');
};
/**
* Schedules a command to retrieve the current page's source. The page source
* returned is a representation of the underlying DOM: do not expect it to be
* formatted or escaped in the same way as the response sent from the web
* server.
* @return {!webdriver.promise.Promise.<string>} A promise that will be
* resolved with the current page source.
*/
webdriver.WebDriver.prototype.getPageSource = function() {
return this.schedule(
new webdriver.Command(webdriver.CommandName.GET_PAGE_SOURCE),
'WebDriver.getAllWindowHandles()');
};
/**
* Schedules a command to close the current window.
* @return {!webdriver.promise.Promise.<void>} A promise that will be resolved
* when this command has completed.
*/
webdriver.WebDriver.prototype.close = function() {
return this.schedule(new webdriver.Command(webdriver.CommandName.CLOSE),
'WebDriver.close()');
};
/**
* Schedules a command to navigate to the given URL.
* @param {string} url The fully qualified URL to open.
* @return {!webdriver.promise.Promise.<void>} A promise that will be resolved
* when the document has finished loading.
*/
webdriver.WebDriver.prototype.get = function(url) {
return this.navigate().to(url);
};
/**
* Schedules a command to retrieve the URL of the current page.
* @return {!webdriver.promise.Promise.<string>} A promise that will be
* resolved with the current URL.
*/
webdriver.WebDriver.prototype.getCurrentUrl = function() {
return this.schedule(
new webdriver.Command(webdriver.CommandName.GET_CURRENT_URL),
'WebDriver.getCurrentUrl()');
};
/**
* Schedules a command to retrieve the current page's title.
* @return {!webdriver.promise.Promise.<string>} A promise that will be
* resolved with the current page's title.
*/
webdriver.WebDriver.prototype.getTitle = function() {
return this.schedule(new webdriver.Command(webdriver.CommandName.GET_TITLE),
'WebDriver.getTitle()');
};
/**
* Schedule a command to find an element on the page. If the element cannot be
* found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned
* by the driver. Unlike other commands, this error cannot be suppressed. In
* other words, scheduling a command to find an element doubles as an assert
* that the element is present on the page. To test whether an element is
* present on the page, use {@link #isElementPresent} instead.
*
* <p>The search criteria for an element may be defined using one of the
* factories in the {@link webdriver.By} namespace, or as a short-hand
* {@link webdriver.By.Hash} object. For example, the following two statements
* are equivalent:
* <code><pre>
* var e1 = driver.findElement(By.id('foo'));
* var e2 = driver.findElement({id:'foo'});
* </pre></code>
*
* <p>You may also provide a custom locator function, which takes as input
* this WebDriver instance and returns a {@link webdriver.WebElement}, or a
* promise that will resolve to a WebElement. For example, to find the first
* visible link on a page, you could write:
* <code><pre>
* var link = driver.findElement(firstVisibleLink);
*
* function firstVisibleLink(driver) {
* var links = driver.findElements(By.tagName('a'));
* return webdriver.promise.filter(links, function(link) {
* return links.isDisplayed();
* }).then(function(visibleLinks) {
* return visibleLinks[0];
* });
* }
* </pre></code>
*
* <p>When running in the browser, a WebDriver cannot manipulate DOM elements
* directly; it may do so only through a {@link webdriver.WebElement} reference.
* This function may be used to generate a WebElement from a DOM element. A
* reference to the DOM element will be stored in a known location and this
* driver will attempt to retrieve it through {@link #executeScript}. If the
* element cannot be found (eg, it belongs to a different document than the
* one this instance is currently focused on), a
* {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned.
*
* @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The
* locator to use.
* @return {!webdriver.WebElement} A WebElement that can be used to issue
* commands against the located element. If the element is not found, the
* element will be invalidated and all scheduled commands aborted.
*/
webdriver.WebDriver.prototype.findElement = function(locator) {
var id;
if ('nodeType' in locator && 'ownerDocument' in locator) {
var element = /** @type {!Element} */ (locator);
id = this.findDomElement_(element).then(function(element) {
if (!element) {
throw new bot.Error(bot.ErrorCode.NO_SUCH_ELEMENT,
'Unable to locate element. Is WebDriver focused on its ' +
'ownerDocument\'s frame?');
}
return element;
});
} else {
locator = webdriver.Locator.checkLocator(locator);
if (goog.isFunction(locator)) {
id = this.findElementInternal_(locator, this);
} else {
var command = new webdriver.Command(webdriver.CommandName.FIND_ELEMENT).
setParameter('using', locator.using).
setParameter('value', locator.value);
id = this.schedule(command, 'WebDriver.findElement(' + locator + ')');
}
}
return new webdriver.WebElementPromise(this, id);
};
/**
* @param {!Function} locatorFn The locator function to use.
* @param {!(webdriver.WebDriver|webdriver.WebElement)} context The search
* context.
* @return {!webdriver.promise.Promise.<!webdriver.WebElement>} A
* promise that will resolve to a list of WebElements.
* @private
*/
webdriver.WebDriver.prototype.findElementInternal_ = function(
locatorFn, context) {
return this.call(goog.partial(locatorFn, context)).then(function(result) {
if (goog.isArray(result)) {
result = result[0];
}
if (!(result instanceof webdriver.WebElement)) {
throw new TypeError('Custom locator did not return a WebElement');
}
return result;
});
};
/**
* Locates a DOM element so that commands may be issued against it using the
* {@link webdriver.WebElement} class. This is accomplished by storing a
* reference to the element in an object on the element's ownerDocument.
* {@link #executeScript} will then be used to create a WebElement from this
* reference. This requires this driver to currently be focused on the
* ownerDocument's window+frame.
* @param {!Element} element The element to locate.
* @return {!webdriver.promise.Promise.<webdriver.WebElement>} A promise that
* will be fulfilled with the located element, or null if the element
* could not be found.
* @private
*/
webdriver.WebDriver.prototype.findDomElement_ = function(element) {
var doc = element.ownerDocument;
var store = doc['$webdriver$'] = doc['$webdriver$'] || {};
var id = Math.floor(Math.random() * goog.now()).toString(36);
store[id] = element;
element[id] = id;
function cleanUp() {
delete store[id];
}
function lookupElement(id) {
var store = document['$webdriver$'];
if (!store) {
return null;
}
var element = store[id];
if (!element || element[id] !== id) {
return null;
}
return element;
}
/** @type {!webdriver.promise.Promise.<webdriver.WebElement>} */
var foundElement = this.executeScript(lookupElement, id);
foundElement.thenFinally(cleanUp);
return foundElement;
};
/**
* Schedules a command to test if an element is present on the page.
*
* <p>If given a DOM element, this function will check if it belongs to the
* document the driver is currently focused on. Otherwise, the function will
* test if at least one element can be found with the given search criteria.
*
* @param {!(webdriver.Locator|webdriver.By.Hash|Element|
* Function)} locatorOrElement The locator to use, or the actual
* DOM element to be located by the server.
* @return {!webdriver.promise.Promise.<boolean>} A promise that will resolve
* with whether the element is present on the page.
*/
webdriver.WebDriver.prototype.isElementPresent = function(locatorOrElement) {
if ('nodeType' in locatorOrElement && 'ownerDocument' in locatorOrElement) {
return this.findDomElement_(/** @type {!Element} */ (locatorOrElement)).
then(function(result) { return !!result; });
} else {
return this.findElements.apply(this, arguments).then(function(result) {
return !!result.length;
});
}
};
/**
* Schedule a command to search for multiple elements on the page.
*
* @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator
* strategy to use when searching for the element.
* @return {!webdriver.promise.Promise.<!Array.<!webdriver.WebElement>>} A
* promise that will resolve to an array of WebElements.
*/
webdriver.WebDriver.prototype.findElements = function(locator) {
locator = webdriver.Locator.checkLocator(locator);
if (goog.isFunction(locator)) {
return this.findElementsInternal_(locator, this);
} else {
var command = new webdriver.Command(webdriver.CommandName.FIND_ELEMENTS).
setParameter('using', locator.using).
setParameter('value', locator.value);
return this.schedule(command, 'WebDriver.findElements(' + locator + ')');
}
};
/**
* @param {!Function} locatorFn The locator function to use.
* @param {!(webdriver.WebDriver|webdriver.WebElement)} context The search
* context.
* @return {!webdriver.promise.Promise.<!Array.<!webdriver.WebElement>>} A
* promise that will resolve to an array of WebElements.
* @private
*/
webdriver.WebDriver.prototype.findElementsInternal_ = function(
locatorFn, context) {
return this.call(goog.partial(locatorFn, context)).then(function(result) {
if (result instanceof webdriver.WebElement) {
return [result];
}
if (!goog.isArray(result)) {
return [];
}
return goog.array.filter(result, function(item) {
return item instanceof webdriver.WebElement;
});
});
};
/**
* Schedule a command to take a screenshot. The driver makes a best effort to
* return a screenshot of the following, in order of preference:
* <ol>
* <li>Entire page
* <li>Current window
* <li>Visible portion of the current frame
* <li>The screenshot of the entire display containing the browser
* </ol>
*
* @return {!webdriver.promise.Promise.<string>} A promise that will be
* resolved to the screenshot as a base-64 encoded PNG.
*/
webdriver.WebDriver.prototype.takeScreenshot = function() {
return this.schedule(new webdriver.Command(webdriver.CommandName.SCREENSHOT),
'WebDriver.takeScreenshot()');
};
/**
* @return {!webdriver.WebDriver.Options} The options interface for this
* instance.
*/
webdriver.WebDriver.prototype.manage = function() {
return new webdriver.WebDriver.Options(this);
};
/**
* @return {!webdriver.WebDriver.Navigation} The navigation interface for this
* instance.
*/
webdriver.WebDriver.prototype.navigate = function() {
return new webdriver.WebDriver.Navigation(this);
};