-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathSession.ts
2553 lines (2320 loc) · 75.6 KB
/
Session.ts
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
import Element, { ElementOrElementId } from './Element';
import Server from './Server';
import findDisplayed from './lib/findDisplayed';
import { Task, CancellablePromise, partial } from '@theintern/common';
import statusCodes from './lib/statusCodes';
import Locator, { toW3cLocator, Strategy } from './lib/Locator';
import {
forCommand as utilForCommand,
manualFindByLinkText,
sleep,
toExecuteString,
} from './lib/util';
import waitForDeleted from './lib/waitForDeleted';
import {
Capabilities,
Geolocation,
LogEntry,
WebDriverCookie,
WebDriverResponse,
} from './interfaces';
/**
* A Session represents a connection to a remote environment that can be driven
* programmatically.
*/
export default class Session extends Locator<
CancellablePromise<Element>,
CancellablePromise<Element[]>,
CancellablePromise<void>
> {
private _sessionId: string;
private _server: Server;
private _capabilities: Capabilities;
private _closedWindows: any = null;
// TODO: Timeouts are held so that we can fiddle with the implicit wait
// timeout to add efficient `waitFor` and `waitForDeleted` convenience
// methods. Technically only the implicit timeout is necessary.
private _timeouts: { [key: string]: CancellablePromise<number> } = {};
private _movedToElement = false;
private _lastMousePosition: any = null;
private _lastAltitude: any = null;
private _nextRequest: CancellablePromise<any> | undefined;
/**
* A Session represents a connection to a remote environment that can be
* driven programmatically.
*
* @param sessionId The ID of the session, as provided by the remote.
* @param server The server that the session belongs to.
* @param capabilities A map of bugs and features that the remote
* environment exposes.
*/
constructor(sessionId: string, server: Server, capabilities: Capabilities) {
super();
this._sessionId = sessionId;
this._server = server;
this._capabilities = capabilities;
this._closedWindows = {};
this._timeouts = {
script: Task.resolve(0),
implicit: Task.resolve(0),
'page load': Task.resolve(Infinity),
};
}
/**
* Information about the available features and bugs in the remote
* environment.
*/
get capabilities() {
return this._capabilities;
}
/**
* The current session ID.
*/
get sessionId() {
return this._sessionId;
}
/**
* The Server that the session runs on.
*/
get server() {
return this._server;
}
/**
* Delegates the HTTP request for a method to the underlying
* [[Server.Server]] object.
*/
private _delegateToServer<T>(
method: 'post' | 'get' | 'delete',
path: string,
requestData: any,
pathParts?: string[]
): CancellablePromise<T> {
path = 'session/' + this._sessionId + (path ? '/' + path : '');
if (
method === 'post' &&
!requestData &&
this.capabilities.brokenEmptyPost
) {
requestData = {};
}
let cancelled = false;
return new Task<T>(
(resolve) => {
// The promise is cleared from `_nextRequest` once it has been
// resolved in order to avoid infinitely long chains of promises
// retaining values that are not used any more
let thisRequest: CancellablePromise<any> | undefined;
const clearNextRequest = () => {
if (this._nextRequest === thisRequest) {
this._nextRequest = undefined;
}
};
const runRequest = () => {
// `runRequest` is normally called once the previous request is
// finished. If this request is cancelled before the previous
// request is finished, then it should simply never run. (This
// Task will have been rejected already by the cancellation.)
if (cancelled) {
clearNextRequest();
return;
}
const response = this._server[method]<WebDriverResponse>(
path,
requestData,
pathParts
).then((response) => response.value);
// safePromise is simply a promise based on the response that
// is guaranteed to resolve -- it is only used for promise
// chain management
const safePromise = response.catch((_error) => {});
safePromise.then(clearNextRequest);
// The value of the response always needs to be taken directly
// from the server call rather than from the chained
// `_nextRequest` promise, since if an undefined value is
// returned by the server call and that value is returned
// through `finally(runRequest)`, the *previous* Task’s
// resolved value will be used as the resolved value, which is
// wrong
resolve(response);
return safePromise;
};
// At least ChromeDriver 2.19 will just hard close connections if
// parallel requests are made to the server, so any request sent to
// the server for a given session must be serialised. Other servers
// like Selendroid have been known to have issues with parallel
// requests as well, so serialisation is applied universally, even
// though it has negative performance implications
if (this._nextRequest) {
thisRequest = this._nextRequest =
this._nextRequest.finally(runRequest);
} else {
thisRequest = this._nextRequest = runRequest();
}
},
() => (cancelled = true)
);
}
serverGet<T>(path: string, requestData?: any, pathParts?: string[]) {
return this._delegateToServer<T>('get', path, requestData, pathParts);
}
serverPost<T>(path: string, requestData?: any, pathParts?: string[]) {
return this._delegateToServer<T>('post', path, requestData, pathParts);
}
serverDelete<T>(path: string, requestData?: any, pathParts?: string[]) {
return this._delegateToServer<T>('delete', path, requestData, pathParts);
}
/**
* Gets the current value of a timeout for the session.
*
* @param type The type of timeout to retrieve. One of 'script',
* 'implicit', or 'page load'.
* @returns The timeout, in milliseconds.
*/
getTimeout(type: Timeout): CancellablePromise<number> {
if (this.capabilities.supportsGetTimeouts) {
return this.serverGet<WebDriverTimeouts>('timeouts').then((timeouts) =>
type === 'page load' ? timeouts.pageLoad : timeouts[type]
);
} else {
return this._timeouts[type];
}
}
/**
* Sets the value of a timeout for the session.
*
* @param type The type of timeout to set. One of 'script', 'implicit', or
* 'page load'.
*
* @param ms The length of time to use for the timeout, in milliseconds. A
* value of 0 will cause operations to time out immediately.
*/
setTimeout(type: Timeout, ms: number): CancellablePromise<void> {
// Infinity cannot be serialised by JSON
if (ms === Infinity) {
// It seems that at least ChromeDriver 2.10 has a limit here that
// is near the 32-bit signed integer limit, and IEDriverServer
// 2.42.2 has an even lower limit; 2.33 hours should be infinite
// enough for testing
ms = Math.pow(2, 23) - 1;
}
// If the target doesn't support a timeout of 0, use 1.
if (this.capabilities.brokenZeroTimeout && ms === 0) {
ms = 1;
}
// Set both JSONWireProtocol and WebDriver properties in the data object
let data = this.capabilities.usesWebDriverTimeouts
? {
[type === 'page load' ? 'pageLoad' : type]: ms,
}
: {
type,
ms,
};
const promise = this.serverPost<void>('timeouts', data).catch((error) => {
// Appium as of April 2014 complains that `timeouts` is
// unsupported, so try the more specific endpoints if they exist
if (error.name === 'UnknownCommand') {
if (type === 'script') {
return this.serverPost<void>('timeouts/async_script', {
ms: ms,
});
} else if (type === 'implicit') {
return this.serverPost<void>('timeouts/implicit_wait', {
ms: ms,
});
}
} else if (
!this.capabilities.usesWebDriverTimeouts &&
// At least Chrome 60+
(/Missing 'type' parameter/.test(error.message) ||
// At least Safari 10+
/Unknown timeout type/.test(error.message) ||
// IE11
/Invalid timeout type specified/.test(error.message))
) {
this.capabilities.usesWebDriverTimeouts = true;
return this.setTimeout(type, ms);
}
throw error;
});
this._timeouts[type] = promise.then(() => ms).catch(() => 0);
return promise;
}
/**
* Gets the identifier for the window that is currently focused.
*
* @returns A window handle identifier that can be used with other window
* handling functions.
*/
getCurrentWindowHandle(): CancellablePromise<string> {
const endpoint = this.capabilities.usesWebDriverWindowHandleCommands
? 'window'
: 'window_handle';
return this.serverGet<string>(endpoint)
.then((handle) => {
if (
this.capabilities.brokenDeleteWindow &&
this._closedWindows[handle]
) {
const error: SessionError = new Error();
error.status = '23';
error.name = statusCodes[error.status][0];
error.message = statusCodes[error.status][1];
throw error;
}
return handle;
})
.catch((error) => {
if (
// At least Edge 44.17763 returns an UnknownError when it doesn't
// support /window_handle, whereas most drivers return an
// UnknownCommand error.
/^Unknown/.test(error.name) &&
!this.capabilities.usesWebDriverWindowHandleCommands
) {
this.capabilities.usesWebDriverWindowHandleCommands = true;
return this.getCurrentWindowHandle();
}
throw error;
});
}
/**
* Gets a list of identifiers for all currently open windows.
*/
getAllWindowHandles(): CancellablePromise<string[]> {
const endpoint = this.capabilities.usesWebDriverWindowHandleCommands
? 'window/handles'
: 'window_handles';
return this.serverGet<string[]>(endpoint)
.then((handles: string[]) => {
if (this.capabilities.brokenDeleteWindow) {
return handles.filter((handle) => {
return !this._closedWindows[handle];
});
}
return handles;
})
.catch((error) => {
if (
error.name === 'UnknownCommand' &&
!this.capabilities.usesWebDriverWindowHandleCommands
) {
this.capabilities.usesWebDriverWindowHandleCommands = true;
return this.getAllWindowHandles();
}
throw error;
});
}
/**
* Gets the URL that is loaded in the focused window/frame.
*/
getCurrentUrl() {
return this.serverGet<string>('url');
}
/**
* Navigates the focused window/frame to a new URL.
*/
get(url: string) {
this._movedToElement = false;
if (this.capabilities.brokenMouseEvents) {
this._lastMousePosition = { x: 0, y: 0 };
}
return this.serverPost<void>('url', { url: url });
}
/**
* Navigates the focused window/frame forward one page using the browser’s
* navigation history.
*/
goForward() {
// TODO: SPEC: Seems like this and `back` should return the newly
// navigated URL.
return this.serverPost<void>('forward');
}
/**
* Navigates the focused window/frame back one page using the browser’s
* navigation history.
*/
goBack() {
// TODO: SPEC: Seems like this and `back` should return the newly
// navigated URL.
return this.serverPost<void>('back');
}
/**
* Reloads the current browser window/frame.
*/
refresh() {
if (this.capabilities.brokenRefresh) {
return this.execute<void>('location.reload();');
}
return this.serverPost<void>('refresh');
}
/**
* Executes JavaScript code within the focused window/frame. The code
* should return a value synchronously.
*
* See [[Session.Session.executeAsync]] to execute code that returns values
* asynchronously.
*
* @param script The code to execute. This function will always be
* converted to a string, sent to the remote environment, and reassembled
* as a new anonymous function on the remote end. This means that you
* cannot access any variables through closure. If your code needs to get
* data from variables on the local end, they should be passed using
* `args`.
*
* @param args An array of arguments that will be passed to the executed
* code. Only values that can be serialised to JSON, plus
* [[Element.Element]] objects, can be specified as arguments.
*
* @returns The value returned by the remote code. Only values that can be
* serialised to JSON, plus DOM elements, can be returned.
*/
execute<T>(script: Function | string, args?: any[]): CancellablePromise<T> {
// At least FirefoxDriver 2.40.0 will throw a confusing
// NullPointerException if args is not an array; provide a friendlier
// error message to users that accidentally pass a non-array
if (typeof args !== 'undefined' && !Array.isArray(args)) {
throw new Error('Arguments passed to execute must be an array');
}
const endpoint = this.capabilities.usesWebDriverExecuteSync
? 'execute/sync'
: 'execute';
let result = this.serverPost<T>(endpoint, {
script: toExecuteString(script),
args: args || [],
})
.then((value) => convertToElements(this, value), fixExecuteError)
.catch((error) => {
if (
error.detail.error === 'unknown command' &&
!this.capabilities.usesWebDriverExecuteSync
) {
this.capabilities.usesWebDriverExecuteSync = true;
return this.execute(script, args);
}
throw error;
});
if (this.capabilities.brokenExecuteUndefinedReturn) {
result = result.then((value) => (value == null ? null : value));
}
return result;
}
/**
* Executes JavaScript code within the focused window/frame. The code must
* invoke the provided callback in order to signal that it has completed
* execution.
*
* See [[Session.Session.execute]] to execute code that returns values
* synchronously.
*
* See [[Session.Session.setExecuteAsyncTimeout]] to set the time until an
* asynchronous script is considered timed out.
*
* @param script The code to execute. This function will always be
* converted to a string, sent to the remote environment, and reassembled
* as a new anonymous function on the remote end. This means that you
* cannot access any variables through closure. If your code needs to get
* data from variables on the local end, they should be passed using
* `args`.
*
* @param args An array of arguments that will be passed to the executed
* code. Only values that can be serialised to JSON, plus
* [[Element.Element]] objects, can be specified as arguments. In addition
* to these arguments, a callback function will always be passed as the
* final argument to the function specified in `script`. This callback
* function must be invoked in order to signal that execution has
* completed. The return value of the execution, if any, should be passed
* to this callback function.
*
* @returns The value returned by the remote code. Only values that can be
* serialised to JSON, plus DOM elements, can be returned.
*/
executeAsync<T>(
script: Function | string,
args?: any[]
): CancellablePromise<T> {
// At least FirefoxDriver 2.40.0 will throw a confusing
// NullPointerException if args is not an array; provide a friendlier
// error message to users that accidentally pass a non-array
if (typeof args !== 'undefined' && !Array.isArray(args)) {
throw new Error('Arguments passed to executeAsync must be an array');
}
const endpoint = this.capabilities.usesWebDriverExecuteAsync
? 'execute/async'
: 'execute_async';
return this.serverPost<T>(endpoint, {
script: toExecuteString(script),
args: args || [],
})
.then(partial(convertToElements, this), fixExecuteError)
.catch((error) => {
if (
error.detail.error === 'unknown command' &&
!this.capabilities.usesWebDriverExecuteAsync
) {
this.capabilities.usesWebDriverExecuteAsync = true;
return this.executeAsync<T>(script, args);
}
// At least Safari 11, Jan 2019 will throw Timeout errors rather than
// ScriptTimeout errors for script timeouts
if (error.name === 'Timeout') {
error.name = 'ScriptTimeout';
}
throw error;
});
}
/**
* Gets a screenshot of the focused window and returns it in PNG format.
*
* @returns A buffer containing a PNG image.
*/
takeScreenshot() {
return this.serverGet<string>('screenshot').then((data) =>
Buffer.from(data, 'base64')
);
}
/**
* Gets a list of input method editor engines available to the remote
* environment. As of April 2014, no known remote environments support IME
* functions.
*/
getAvailableImeEngines() {
return this.serverGet<string[]>('ime/available_engines');
}
/**
* Gets the currently active input method editor for the remote environment.
* As of April 2014, no known remote environments support IME functions.
*/
getActiveImeEngine() {
return this.serverGet<string>('ime/active_engine');
}
/**
* Returns whether or not an input method editor is currently active in the
* remote environment. As of April 2014, no known remote environments
* support IME functions.
*/
isImeActivated() {
return this.serverGet<boolean>('ime/activated');
}
/**
* Deactivates any active input method editor in the remote environment.
* As of April 2014, no known remote environments support IME functions.
*/
deactivateIme() {
return this.serverPost<void>('ime/deactivate');
}
/**
* Activates an input method editor in the remote environment.
* As of April 2014, no known remote environments support IME functions.
*
* @param engine The type of IME to activate.
*/
activateIme(engine: string) {
return this.serverPost<void>('ime/activate', { engine: engine });
}
/**
* Switches the currently focused frame to a new frame.
*
* @param id The frame to switch to. In most environments, a number or
* string value corresponds to a key in the `window.frames` object of the
* currently active frame. If `null`, the topmost (default) frame will be
* used. If an Element is provided, it must correspond to a `<frame>` or
* `<iframe>` element.
*/
switchToFrame(
id: string | number | Element | null
): CancellablePromise<void> {
if (this.capabilities.usesWebDriverFrameId && typeof id === 'string') {
return this.findById(id).then((element) =>
this.serverPost<void>('frame', { id: element })
);
}
return this.serverPost<void>('frame', { id: id }).catch((error) => {
if (
this.capabilities.usesWebDriverFrameId == null &&
(error.name === 'InvalidArgument' ||
// An earlier version of the W3C spec said to return a NoSuchFrame
// error for invalid IDs, and at least chromedriver in Jan 2019 used
// this behavior.
error.name === 'NoSuchFrame' ||
// At least geckodriver 0.24.0 throws an UnknownCommand error
// with a message about an invalid tag name rather than a NoSuchFrame
// error (see https://github.com/mozilla/geckodriver/issues/1456)
/any variant of untagged/.test(error.detail.message) ||
// At least chromedriver 96 throws an UnknownCommand error with a
// message about an invalid argument rather than an InvalidArgument
// error
/invalid argument/.test(error.detail.message))
) {
this.capabilities.usesWebDriverFrameId = true;
return this.switchToFrame(id);
}
throw error;
});
}
/**
* Switches the currently focused window to a new window.
*
* @param handle The handle of the window to switch to. In mobile
* environments and environments based on the W3C WebDriver standard, this
* should be a handle as returned by
* [[Session.Session.getAllWindowHandles]].
*
* In environments using the JsonWireProtocol, this value corresponds to
* the `window.name` property of a window.
*/
switchToWindow(handle: string) {
// const handleProperty = this.capabilities.=== 'selendroid' &&
let data: { [key: string]: string } = { name: handle };
if (this.capabilities.usesHandleParameter) {
data = { handle };
}
return this.serverPost<void>('window', data);
}
/**
* Switches the currently focused frame to the parent of the currently
* focused frame.
*/
switchToParentFrame(): CancellablePromise<void> {
if (this.capabilities.brokenParentFrameSwitch) {
return this.execute<Element>('return window.parent.frameElement;').then(
(parent) => {
// TODO: Using `null` if no parent frame was returned keeps
// the request from being invalid, but may be incorrect and
// may cause incorrect frame retargeting on certain
// platforms; At least Selendroid 0.9.0 fails both commands
return this.switchToFrame(parent || null);
}
);
} else {
return this.serverPost<void>('frame/parent').catch((error) => {
if (this.capabilities.scriptedParentFrameCrashesBrowser) {
throw error;
}
this.capabilities.brokenParentFrameSwitch = true;
return this.switchToParentFrame();
});
}
}
/**
* Closes the currently focused window. In most environments, after the
* window has been closed, it is necessary to explicitly switch to whatever
* window is now focused.
*/
closeCurrentWindow() {
const self = this;
function manualClose() {
return self.getCurrentWindowHandle().then(function (handle: any) {
return self.execute('window.close();').then(function () {
self._closedWindows[handle] = true;
});
});
}
if (this.capabilities.brokenDeleteWindow) {
return manualClose();
}
return this.serverDelete<void>('window').catch((error) => {
// ios-driver 0.6.6-SNAPSHOT April 2014 does not implement close
// window command
if (
error.name === 'UnknownCommand' &&
!this.capabilities.brokenDeleteWindow
) {
this.capabilities.brokenDeleteWindow = true;
return manualClose();
}
throw error;
});
}
/**
* Sets the dimensions of a window.
*
* @param windowHandle The name of the window to resize. See
* [[Session.Session.switchToWindow]] to learn about valid window names.
* Omit this argument to resize the currently focused window.
*
* @param width The new width of the window, in CSS pixels.
*
* @param height The new height of the window, in CSS pixels.
*/
setWindowSize(width: number, height: number): CancellablePromise<void>;
setWindowSize(
windowHandle: string,
width: number,
height: number
): CancellablePromise<void>;
setWindowSize(...args: any[]) {
let [windowHandle, width, height] = args;
if (typeof height === 'undefined') {
height = width;
width = windowHandle;
windowHandle = null;
}
const data = { width, height };
if (this.capabilities.usesWebDriverWindowCommands) {
const setWindowSize = () =>
this.getWindowPosition().then((position) =>
this.setWindowRect({
// At least Firefox + geckodriver 0.17.0 requires all 4 rect
// parameters have values
x: position.x,
y: position.y,
width: data.width,
height: data.height,
})
);
if (windowHandle == null) {
return setWindowSize();
} else {
// User provided a window handle; get the current handle,
// switch to the new one, get the size, then switch back to the
// original handle.
let error: Error;
return this.getCurrentWindowHandle().then((originalHandle) => {
return this.switchToWindow(windowHandle)
.then(() => setWindowSize())
.catch((_error) => {
error = _error;
})
.then(() => this.switchToWindow(originalHandle))
.then(() => {
if (error) {
throw error;
}
});
});
}
} else {
if (windowHandle == null) {
windowHandle = 'current';
}
return this.serverPost<void>('window/$0/size', { width, height }, [
windowHandle,
]);
}
}
/**
* Gets the dimensions of a window.
*
* @param windowHandle The name of the window to query. See
* [[Session.Session.switchToWindow]] to learn about valid window names.
* Omit this argument to query the currently focused window.
*
* @returns An object describing the width and height of the window, in CSS
* pixels.
*/
getWindowSize(windowHandle?: string) {
if (this.capabilities.usesWebDriverWindowCommands) {
const getWindowSize = () =>
this.getWindowRect().then((rect) => ({
width: rect.width,
height: rect.height,
}));
if (windowHandle == null) {
return getWindowSize();
} else {
// User provided a window handle; get the current handle,
// switch to the new one, get the size, then switch back to the
// original handle.
let error: Error;
let size: { width: number; height: number };
return this.getCurrentWindowHandle().then((originalHandle) => {
return this.switchToWindow(windowHandle!)
.then(() => getWindowSize())
.then(
(_size) => {
size = _size;
},
(_error) => {
error = _error;
}
)
.then(() => this.switchToWindow(originalHandle))
.then(() => {
if (error) {
throw error;
}
return size;
});
});
}
} else {
if (windowHandle == null) {
windowHandle = 'current';
}
return this.serverGet<{
width: number;
height: number;
}>('window/$0/size', null, [windowHandle]);
}
}
/**
* Return the current window's rectangle (size and position).
*/
getWindowRect() {
return this.serverGet<{
width: number;
height: number;
x: number;
y: number;
}>('window/rect');
}
/**
* Set the current window's rectangle (size and position).
*
* @param rect The windows rectangle. This may contain all 4 properties, or
* just x & y, or just width & height.
*/
setWindowRect(rect: { x: number; y: number; width: number; height: number }) {
return this.serverPost<void>('window/rect', rect);
}
/**
* Sets the position of a window.
*
* Note that this method is not part of the W3C WebDriver standard.
*
* @param windowHandle The name of the window to move. See
* [[Session.Session.switchToWindow]] to learn about valid window names.
* Omit this argument to move the currently focused window.
*
* @param x The screen x-coordinate to move to, in CSS pixels, relative to
* the left edge of the primary monitor.
*
* @param y The screen y-coordinate to move to, in CSS pixels, relative to
* the top edge of the primary monitor.
*/
setWindowPosition(x: number, y: number): CancellablePromise<void>;
setWindowPosition(
windowHandle: string,
x: number,
y: number
): CancellablePromise<void>;
setWindowPosition(...args: any[]) {
let [windowHandle, x, y] = args;
if (typeof y === 'undefined') {
y = x;
x = windowHandle;
windowHandle = null;
}
if (this.capabilities.usesWebDriverWindowCommands) {
// At least Firefox + geckodriver 0.17.0 requires all 4 rect
// parameters have values
return this.getWindowSize().then((size) => {
const data = { x, y, width: size.width, height: size.height };
if (windowHandle == null) {
return this.setWindowRect(data);
} else {
// User provided a window handle; get the current handle,
// switch to the new one, get the size, then switch back to the
// original handle.
let error: Error;
return this.getCurrentWindowHandle().then((originalHandle) => {
if (originalHandle === windowHandle) {
this.setWindowRect(data);
} else {
return this.switchToWindow(windowHandle)
.then(() => this.setWindowRect(data))
.catch((_error) => {
error = _error;
})
.then(() => this.switchToWindow(originalHandle))
.then(() => {
if (error) {
throw error;
}
});
}
});
}
});
} else {
if (windowHandle == null) {
windowHandle = 'current';
}
return this.serverPost<void>('window/$0/position', { x, y }, [
windowHandle,
]);
}
}
/**
* Gets the position of a window.
*
* Note that this method is not part of the W3C WebDriver standard.
*
* @param windowHandle The name of the window to query. See
* [[Session.Session.switchToWindow]] to learn about valid window names.
* Omit this argument to query the currently focused window.
*
* @returns An object describing the position of the window, in CSS pixels,
* relative to the top-left corner of the primary monitor. If a secondary
* monitor exists above or to the left of the primary monitor, these values
* will be negative.
*/
getWindowPosition(windowHandle?: string) {
if (this.capabilities.usesWebDriverWindowCommands) {
const getWindowPosition = () =>
this.getWindowRect().then(({ x, y }) => {
return { x, y };
});
if (windowHandle == null) {
return getWindowPosition();
} else {
// User provided a window handle; get the current handle,
// switch to the new one, get the position, then switch back to
// the original handle.
let error: Error;
let position: { x: number; y: number };
return this.getCurrentWindowHandle().then((originalHandle) => {
return this.switchToWindow(windowHandle!)
.then(() => getWindowPosition())
.then(
(_position) => {
position = _position;
},
(_error) => {
error = _error;
}
)
.then(() => this.switchToWindow(originalHandle))
.then(() => {
if (error) {
throw error;
}
return position;
});
});
}
} else {
if (typeof windowHandle === 'undefined') {
windowHandle = 'current';
}
return this.serverGet<{
x: number;
y: number;
}>('window/$0/position', null, [windowHandle]).then((position) => {
// At least Firefox + geckodriver 0.19.0 will return a full
// rectangle for the position command.
return {
x: position.x,
y: position.y,
};
});
}
}
/**
* Maximises a window according to the platform’s window system behaviour.
*
* @param windowHandle The name of the window to resize. See
* [[Session.Session.switchToWindow]] to learn about valid window names.
* Omit this argument to resize the currently focused window.
*/
maximizeWindow(windowHandle?: string) {
if (this.capabilities.usesWebDriverWindowCommands) {
// at least chromedriver 96 requires a body to be sent with a
// `window/maximize` command
const maximizeWindow = () => this.serverPost<void>('window/maximize', {});
if (windowHandle == null) {
return maximizeWindow();
} else {