forked from florentbr/SeleniumBasic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebDriver.cs
More file actions
1022 lines (896 loc) · 35.4 KB
/
WebDriver.cs
File metadata and controls
1022 lines (896 loc) · 35.4 KB
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
using Selenium.Core;
using Selenium.Internal;
using Selenium.Serializer;
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
namespace Selenium {
/// <summary>
/// Object through which the user controls the browser.
/// </summary>
/// <example>
/// VBScript:
/// <code lang="vbs">
/// Class Script
/// Dim driver
///
/// Sub Class_Initialize
/// Set driver = CreateObject("Selenium.WebDriver")
/// driver.Start "firefox", "http://www.google.com"
/// driver.Get "/"
/// End Sub
///
/// Sub Class_Terminate
/// driver.Quit
/// End Sub
/// End Class
///
/// Set s = New Script
/// </code>
///
/// VBA:
/// <code lang="vbs">
/// Public Sub Script()
/// Dim driver As New WebDriver
/// driver.Start "firefox", "http://www.google.com"
/// driver.Get "/"
/// ...
/// driver.Quit
/// End Sub
/// </code>
/// </example>
[ProgId("Selenium.WebDriver")]
[Guid("0277FC34-FD1B-4616-BB19-E3CCFFAB4234")]
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
[Description("Defines the interface through which the user controls the browser using WebDriver")]
public class WebDriver : SearchContext, ComInterfaces._WebDriver, IDisposable {
const string RUNNING_OBJECT_NAME = "Selenium.WebDriver";
internal Capabilities Capabilities = new Capabilities();
internal Dictionary Preferences = new Dictionary();
internal List Extensions = new List();
internal List Arguments = new List();
internal string Profile = null;
internal string Binary = null;
internal bool Persistant = false;
private Timeouts timeouts = new Timeouts();
private IDriverService _service = null;
private RemoteSession _session = null;
private string _baseUrl = null;
private Proxy _proxy = null;
private COMRunningObject _comRunningObj = null;
/// <summary>
/// Creates a new WebDriver object.
/// </summary>
public WebDriver() {
UnhandledException.Initialize();
RegisterRunningObject();
COMDisposable.Subscribe(this, typeof(ComInterfaces._WebDriver));
}
public WebDriver(string browser)
: this() {
this.Capabilities.BrowserName = browser;
}
~WebDriver() {
this.Dispose();
}
/// <summary>
/// Release the resources.
/// </summary>
public void Dispose() {
if (_comRunningObj != null) {
_comRunningObj.Dispose();
_comRunningObj = null;
}
if (_service != null) {
_service.Dispose();
_service = null;
}
if (_session != null) {
_session = null;
}
}
private void RegisterRunningObject(){
if (_comRunningObj == null)
_comRunningObj = new COMRunningObject(this, RUNNING_OBJECT_NAME);
}
#region Setup
/// <summary>
///
/// </summary>
public Proxy Proxy {
get {
return _proxy ?? (_proxy = new Proxy(Capabilities));
}
}
/// <summary>
/// Set a specific profile for the firefox webdriver
/// </summary>
/// <param name="nameOrDirectory">Profil name (Firefox only) or directory (Firefox and Chrome)</param>
/// <param name="persistant">If true, the browser will be launched without a copy the profile (Firefox only)</param>
/// <remarks>The profile directory can be copied from the user temp folder (run %temp%) before the WebDriver is stopped. It's also possible to create a new Firefox profile by launching firefox with the "-p" switch (firefox.exe -p).</remarks>
/// <example>
/// <code lang="vbs">
/// Dim driver As New Selenium.FirefoxDriver
/// driver.SetProfile "Selenium" 'Firefox only. Profile created by running "..\firefox.exe -p"
/// driver.Get "http://www.google.com"
/// ...
/// </code>
/// <code lang="vbs">
/// Dim driver As New Selenium.FirefoxDriver
/// driver.SetProfile "C:\MyProfil" 'For Chrome and Firefox only
/// driver.Get "http://www.google.com"
/// ...
/// </code>
/// </example>
public void SetProfile(string nameOrDirectory, bool persistant = false) {
Profile = nameOrDirectory;
Persistant = persistant;
}
/// <summary>
/// Set a specific preference for the firefox webdriver
/// </summary>
/// <param name="key">Preference key</param>
/// <param name="value">Preference value</param>
public void SetPreference(string key, object value) {
Preferences[key] = JSON.Parse(value);
}
/// <summary>
/// Set a specific capability for the webdriver
/// </summary>
/// <param name="key">Capability key</param>
/// <param name="value">Capability value</param>
public void SetCapability(string key, object value) {
Capabilities[key] = JSON.Parse(value);
}
/// <summary>
/// Add an extension to the browser (For Firefox and Chrome only)
/// </summary>
/// <param name="extensionPath">Path to the extension</param>
public void AddExtension(string extensionPath) {
Extensions.Add(new DriverExtension(extensionPath));
}
/// <summary>
/// Add an argument to be appended to the command line to launch the browser.
/// </summary>
/// <param name="argument">Argument</param>
public void AddArgument(string argument) {
Arguments.Add(argument);
}
/// <summary>
/// Set the path to the browser executable to use
/// </summary>
/// <param name="path">Full path</param>
public void SetBinary(string path) {
if (!File.Exists(path))
throw new Errors.FileNotFoundError(path);
this.Binary = path;
}
#endregion
#region Session
internal override RemoteSession session {
get {
if (_session == null)
throw new Errors.BrowserNotStartedError();
return _session;
}
}
internal override string uri {
get {
return string.Empty;
}
}
/// <summary>
/// Starts a new Selenium testing session
/// </summary>
/// <param name="browser">Name of the browser : firefox, ie, chrome, phantomjs</param>
/// <param name="baseUrl">The base URL</param>
/// <example>
/// <code lang="vbs">
/// Dim driver As New WebDriver()
/// driver.Start "firefox", "http://www.google.com"
/// driver.Get "/"
/// </code>
/// </example>
public void Start(string browser = null, string baseUrl = null) {
try {
browser = ExpendBrowserName(browser);
switch (browser) {
case "firefox":
_service = FirefoxDriver.StartService(this);
break;
case "chrome":
_service = ChromeDriver.StartService(this);
break;
case "phantomjs":
_service = PhantomJSDriver.StartService(this);
break;
case "internet explorer":
_service = IEDriver.StartService(this);
break;
case "MicrosoftEdge":
_service = EdgeDriver.StartService(this);
break;
case "opera":
_service = OperaDriver.StartService(this);
break;
default:
throw new Errors.ArgumentError("Invalid browser name: {0}", browser);
}
this.Capabilities.BrowserName = browser;
RegisterRunningObject();
_session = new RemoteSession(_service.Uri, true, this.timeouts);
_session.Start(this.Capabilities);
if (!string.IsNullOrEmpty(baseUrl))
this.BaseUrl = baseUrl;
} catch (SeleniumException) {
throw;
} catch (Exception ex) {
throw new SeleniumException(ex);
}
}
/// <summary>
/// Starts remotely a new Selenium testing session
/// </summary>
/// <param name="executorUri">Remote executor address (ex : "http://localhost:4444/wd/hub")</param>
/// <param name="browser">Name of the browser : firefox, ie, chrome, phantomjs, htmlunit, htmlunitwithjavascript, android, ipad, opera</param>
/// <param name="version">Browser version</param>
/// <param name="platform">Platform: WINDOWS, LINUX, MAC, ANDROID...</param>
/// <example>
/// <code lang="vbs">
/// Dim driver As New WebDriver()
/// driver.StartRemotely "http://localhost:4444/wd/hub", "ie", 11
/// driver.Get "/"
/// </code>
/// </example>
public void StartRemotely(string executorUri, string browser = null, string version = null, string platform = null) {
try {
browser = ExpendBrowserName(browser);
switch (browser) {
case "firefox":
FirefoxDriver.ExtendCapabilities(this, true);
break;
case "chrome":
ChromeDriver.ExtendCapabilities(this, true);
break;
case "phantomjs":
PhantomJSDriver.ExtendCapabilities(this, true);
break;
case "internet explorer":
IEDriver.ExtendCapabilities(this, true);
break;
case "MicrosoftEdge":
EdgeDriver.ExtendCapabilities(this, true);
break;
case "opera":
OperaDriver.ExtendCapabilities(this, true);
break;
}
this.Capabilities.Platform = platform;
this.Capabilities.BrowserName = browser;
if (!string.IsNullOrEmpty(version))
this.Capabilities.BrowserVersion = version;
_session = new RemoteSession(executorUri, false, this.timeouts);
_session.Start(this.Capabilities);
RegisterRunningObject();
} catch (SeleniumException) {
throw;
} catch (Exception ex) {
throw new SeleniumException(ex);
}
}
/// <summary>
/// Close the Browser and Dispose of WebDriver
/// </summary>
public virtual void Quit() {
if (_session != null) {
try {
if (_session.IsLocal) {
if (!(_service is FirefoxService))
_session.Delete();
_service.Quit(_session.server);
} else {
_session.Delete();
}
} catch { }
}
this.Dispose();
}
private string ExpendBrowserName(string browser) {
if (string.IsNullOrEmpty(browser)) {
browser = this.Capabilities.BrowserName;
if (string.IsNullOrEmpty(browser))
throw new Errors.ArgumentError("Browser not defined");
}
string browserName = browser.ToLower();
switch (browserName) {
case "firefox":
case "ff":
return "firefox";
case "chrome":
case "cr":
return "chrome";
case "phantomjs":
case "pjs":
return "phantomjs";
case "internet explorer":
case "internetexplorer":
case "iexplore":
case "ie":
return "internet explorer";
case "microsoft edge":
case "microsoftedge":
case "edge":
return "MicrosoftEdge";
case "opera":
case "op":
return "opera";
default:
return browserName;
}
}
/// <summary>
/// Sends a customized command
/// </summary>
/// <param name="method">POST, GET or DELETE</param>
/// <param name="relativeUri">Relative URI. Ex: "/screenshot"</param>
/// <param name="param1">Optional</param>
/// <param name="value1"></param>
/// <param name="param2">Optional</param>
/// <param name="value2"></param>
/// <param name="param3">Optional</param>
/// <param name="value3"></param>
/// <param name="param4">Optional</param>
/// <param name="value4"></param>
/// <returns>Result</returns>
/// <example>
/// <code lang="vbs">
/// Set links = driver.Send("POST", "/elements", "using", "css selector", "value", "a")
/// </code>
/// </example>
public object Send(string method, string relativeUri,
string param1 = null, object value1 = null,
string param2 = null, object value2 = null,
string param3 = null, object value3 = null,
string param4 = null, object value4 = null) {
RequestMethod mth = 0;
switch (method.ToUpper()) {
case "POST": mth = RequestMethod.POST; break;
case "GET": mth = RequestMethod.GET; break;
case "DELETE": mth = RequestMethod.DELETE; break;
default:
throw new Errors.ArgumentError("Unhandled method: " + method);
}
Dictionary data = null;
if (param1 != null) {
data = new Dictionary();
data.Add(param1, value1);
if (param2 != null) {
data.Add(param2, value2);
if (param3 != null) {
data.Add(param3, value3);
if (param4 != null) {
data.Add(param4, value3);
}
}
}
}
object result = session.Send(mth, relativeUri, data);
return result;
}
#endregion
#region Interfaces
/// <summary>
/// Manage the browser settings. Need to be defined before the browser is launched
/// </summary>
public Timeouts Timeouts {
get {
return this.timeouts;
}
}
/// <summary>
/// Instructs the driver to change its settings.
/// </summary>
public Manage Manage {
get {
return this.session.manage;
}
}
/// <summary>
/// Get the actions class
/// </summary>
/// <example>
/// <code lang="vbs">
/// WebDriver driver = New WebDriver()
/// driver.start "firefox", "http://www.google.com"
/// driver.get "/"
/// driver.Actions.keyDown(Keys.Control).sendKeys("a").perform
/// </code>
/// </example>
public Actions Actions {
get {
return new Actions(this.session);
}
}
/// <summary>
/// TouchActions
/// </summary>
public TouchActions TouchActions {
get {
RemoteSession session = this.session;
return new TouchActions(session, this.TouchScreen);
}
}
/// <summary>
/// Keyboard
/// </summary>
public Keyboard Keyboard {
get {
return this.session.keyboard;
}
}
/// <summary>
/// Mouse
/// </summary>
public Mouse Mouse {
get {
return this.session.mouse;
}
}
/// <summary>
/// TouchScreen
/// </summary>
public TouchScreen TouchScreen {
get {
return this.session.touchscreen;
}
}
/// <summary>
/// Keys
/// </summary>
public Keys Keys {
get {
return this.session.keyboard.Keys;
}
}
#endregion
#region Navigation
/// <summary>
/// Base URL to use a relative URL with Get
/// </summary>
public string BaseUrl {
get {
return _baseUrl;
}
set {
_baseUrl = value.TrimEnd('/');
}
}
/// <summary>
/// Loads a web page in the current browser session. Same as Open method.
/// </summary>
/// <param name="url">URL</param>
/// <param name="timeout">Optional timeout in milliseconds. Infinite=-1</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Return true if the url was openned within the timeout, false otherwise</returns>
public bool Get(string url, int timeout = -1, bool raise = true) {
if (_session == null)
this.Start();
RemoteSession session = _session;
if (string.IsNullOrEmpty(url))
throw new Errors.ArgumentError("Argument 'url' cannot be null.");
if (timeout > 0){
session.timeouts.PageLoad = timeout;
session.Send(RequestMethod.POST, "/timeouts", "type", "page load", "ms", timeout);
}
int idx = url.IndexOf("/");
if (idx == 0) {
//relative url
if (_baseUrl == null)
throw new Errors.ArgumentError("Base URL not defined. Define a base URL or use a full URL.");
url = string.Concat(_baseUrl, url);
} else {
//absolute url
idx = url.IndexOf('/', idx + 3);
if (idx != -1) {
_baseUrl = url.Substring(0, idx - 1);
} else {
_baseUrl = url;
}
}
try {
session.Send(RequestMethod.POST, "/url", "url", url);
return true;
} catch {
if (raise)
throw;
return false;
}
}
/// <summary>
/// Get the URL the browser is currently displaying.
/// </summary>
/// <returns>Current URL</returns>
public string Url {
get {
return (string)session.Send(RequestMethod.GET, "/url");
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
/// <returns>Title of the window</returns>
public string Title {
get {
return session.windows.CurrentWindow.Title;
}
}
/// <summary>
/// Goes one step backward in the browser history.
/// </summary>
public void GoBack() {
this.session.Send(RequestMethod.POST, "/back");
}
/// <summary>
/// Goes one step forward in the browser history.
/// </summary>
public void GoForward() {
this.session.Send(RequestMethod.POST, "/forward");
}
/// <summary>
/// Refreshes the current page.
/// </summary>
public void Refresh() {
this.session.Send(RequestMethod.POST, "/refresh");
}
#endregion
#region Windows
/// <summary>
/// Gets an object allowing the user to manipulate the currently-focused browser window.
/// </summary>
public Window Window {
get {
return session.windows.CurrentWindow;
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
/// <returns><see cref="List" /></returns>
public List Windows {
get {
List windows, handles;
session.windows.ListWindows(out windows, out handles);
return windows;
}
}
/// <summary>
/// Closes the current window.
/// </summary>
public void Close() {
this.Window.Close();
}
#endregion
#region Interaction
/// <summary>
/// Sends a sequence of keystrokes to the browser.
/// </summary>
/// <param name="keysOrModifier">Sequence of keys or a modifier key(Control, Shift or Alt) if the sequence is in keysToSendEx</param>
/// <param name="keys">Optional - Sequence of keys if keysToSend contains modifier key(Control,Shift...)</param>
/// <example>
/// To Send mobile to the window :
/// <code lang="vbs">
/// driver.SendKeys "mobile"
/// </code>
/// To Send ctrl+a to the window :
/// <code lang="vbs">
/// driver.SendKeys Keys.Control, "a"
/// </code>
/// </example>
public void SendKeys(string keysOrModifier, string keys = null) {
this.session.keyboard.SendKeys(keysOrModifier, keys);
}
#endregion
#region Screenshot
/// <summary>
/// Takes the screenshot of the current window
/// </summary>
/// <param name="delay">Time to wait before taking the screenshot in milliseconds</param>
/// <returns><see cref="Image" /></returns>
public Image TakeScreenshot(int delay = 0) {
if (delay != 0)
SysWaiter.Wait(delay);
Image image = (Image)session.Send(RequestMethod.GET, "/screenshot");
return image;
}
#endregion
#region Javascript
/// <summary>
/// Execute a piece of JavaScript in the context of the currently selected frame or window
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="arguments">The arguments to the script.</param>
/// <returns>The value specified by the return statement.</returns>
/// <example>
/// <code lang="vb">
/// txt = driver.ExecuteScript("return 'xyz' + arguments[0];", "123")
/// </code>
/// </example>
public object ExecuteScript(string script, object arguments = null) {
object args_ex = FormatArguments(arguments);
object result = session.javascript.Execute(script, args_ex, true);
return result;
}
/// <summary>
/// Execute an asynchronous piece of JavaScript in the context of the current frame or window.
/// </summary>
/// <param name="script">Piece of JavaScript code to execute.</param>
/// <param name="arguments">Optional arguments for the script.</param>
/// <param name="timeout">Optional timeout in milliseconds.</param>
/// <returns>The first argument of the callback function.</returns>
/// <example>
/// <code lang="vb">
/// txt = driver.ExecuteAsyncScript("callback('xyz')");"
/// </code>
/// </example>
public object ExecuteAsyncScript(string script, object arguments = null, int timeout = -1) {
object args_ex = FormatArguments(arguments);
object result = session.javascript.ExecuteAsync(script, args_ex, true, timeout);
return result;
}
/// <summary>
/// Waits for a piece of JavaScript to return true or not null.
/// </summary>
/// <param name="script">Piece of JavaScript code to execute.</param>
/// <param name="arguments">Optional arguments for the script.</param>
/// <param name="timeout">Optional timeout in milliseconds.</param>
/// <returns>Value not null</returns>
public object WaitForScript(string script, object arguments, int timeout = -1) {
object args_ex = FormatArguments(arguments);
object result = session.javascript.WaitFor(script, args_ex, timeout);
return result;
}
private static object FormatArguments(object arguments) {
if (arguments == null) {
return new object[0];
} else if (arguments is IEnumerable && !(arguments is string || arguments is Dictionary)) {
return arguments;
} else {
return new object[] { arguments };
}
}
#endregion
#region Find Elements
/// <summary>
/// Returns the element with focus, or BODY if nothing has focus.
/// </summary>
/// <returns></returns>
public WebElement ActiveElement() {
return WebElement.GetActiveWebElement(session);
}
#endregion
#region PageSource
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
public string PageSource() {
var result = session.Send(RequestMethod.GET, "/source");
return (string)result;
}
/// <summary>
/// Returns the first occurence matching the regular expression.
/// </summary>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="group">Optional - Group number (Zero based)</param>
/// <returns>String</returns>
public string PageSourceMatch(string pattern, short group = 0) {
const string JS = "return document.body.innerHTML.match(/{0}/)[{1}]";
string code = string.Format(JS, pattern, group);
object result = session.javascript.Execute(code, null, false);
return (string)result;
}
/// <summary>
/// Returns all the occurences matching the regular expression.
/// </summary>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="group">Optional - Group number (Zero based)</param>
/// <returns>Array of strings or null</returns>
public List PageSourceMatches(string pattern, short group = 0) {
const string JS = "var r=/{0}/g,s=document.body.innerHTML,a=[],m;"
+ "while(m=r.exec(s))a.push(m[{1}]);return a;";
string code = string.Format(JS, pattern, group);
object result = session.javascript.Execute(code, null, false);
return (List)result;
}
#endregion
#region Context
/// <summary>
/// Select either the first frame on the page or the main document when a page contains iFrames.
/// </summary>
/// <returns>A WebDriver instance focused on the default frame.</returns>
public void SwitchToDefaultContent() {
this.session.frame.SwitchToDefaultContent();
}
/// <summary>
/// Switch focus to the specified window by name.
/// </summary>
/// <param name="name">The name of the window to activate</param>
/// <param name="timeout">Optional timeout in milliseconds</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Current web driver</returns>
public Window SwitchToWindowByName(string name, int timeout = -1, bool raise = true) {
try {
return session.windows.SwitchToWindowByName(name, timeout);
} catch (Errors.NoSuchWindowError) {
if (raise)
throw new Errors.NoSuchWindowError(name);
return null;
}
}
/// <summary>
/// Switch focus to the specified window by title.
/// </summary>
/// <param name="title">The title of the window to activate</param>
/// <param name="timeout">Optional timeout in milliseconds</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Current web driver</returns>
public Window SwitchToWindowByTitle(string title, int timeout = -1, bool raise = true) {
try {
return session.windows.SwitchToWindowByTitle(title, timeout);
} catch (Errors.NoSuchWindowError) {
if (raise)
throw new Errors.NoSuchWindowError(title);
return null;
}
}
/// <summary>
/// Switch the focus to the next window.
/// </summary>
/// <param name="timeout">Optional timeout in milliseconds</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true. Default is true.</param>
/// <returns>Window</returns>
public Window SwitchToNextWindow(int timeout = -1, bool raise = true) {
try {
return session.windows.SwitchToNextWindow(timeout);
} catch (Errors.NoSuchWindowError) {
if (raise)
throw;
return null;
}
}
/// <summary>
/// Switch the focus to the previous window
/// </summary>
/// <returns>Window</returns>
public Window SwitchToPreviousWindow() {
return session.windows.SwitchToPreviousWindow();
}
/// <summary>
/// Switch focus to the specified frame, by index(zero based), name or WebElement.
/// </summary>
/// <param name="identifier">The name, index(zero based) or WebElement</param>
/// <param name="timeout">Optional timeout in milliseconds</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Current web driver</returns>
public bool SwitchToFrame(object identifier, int timeout = -1, bool raise = true) {
try {
this.session.frame.SwitchToFrame(identifier, timeout);
} catch (Errors.NoSuchFrameError) {
if (raise)
throw new Errors.NoSuchFrameError(identifier);
return false;
}
return true;
}
/// <summary>
/// Select the parent frame of the currently selected frame.
/// </summary>
/// <returns>The WebDriver instance focused on the specified frame.</returns>
public void SwitchToParentFrame() {
this.session.frame.SwitchToParentFrame();
}
/// <summary>
/// Switch focus to an alert on the page.
/// </summary>
/// <param name="timeout">Optional timeout in milliseconds</param>
/// <param name="raise">Optional - Raise an exception after the timeout when true</param>
/// <returns>Focused alert</returns>
public Alert SwitchToAlert(int timeout = -1, bool raise = true) {
try {
return Alert.SwitchToAlert(session, timeout);
} catch (Errors.NoAlertPresentError) {
if (raise)
throw;
return null;
}
}
#endregion
#region Wait methods
/// <summary>
/// Wait the specified time in millisecond before executing the next command
/// </summary>
/// <param name="timems">Time to wait in millisecond</param>
public void Wait(int timems) {
SysWaiter.Wait(timems);
}
/// <summary>
/// Waits for the delegate function to return not null or true
/// </summary>
/// <typeparam name="T">Returned object or boolean</typeparam>
/// <param name="func">Delegate taking the web driver instance as argument</param>
/// <param name="timeout">Timeout in milliseconds</param>
/// <returns>Variant or boolean</returns>
public T Until<T>(Func<WebDriver, T> func, int timeout = -1) {
if (timeout == -1)
timeout = session.timeouts.timeout_implicitwait;
return Waiter.WaitUntil(func, this, timeout, 80);
}
/// <summary>
/// Waits for a function to return true. VBScript: Function WaitEx(webdriver), VBA: Function WaitEx(webdriver As WebDriver) As Boolean
/// </summary>
/// <param name="procedure">Function reference. VBScript: wd.WaitFor GetRef(\"WaitEx\") VBA: wd.WaitFor AddressOf WaitEx)</param>
/// <param name="argument">Optional - Argument to send to the function</param>
/// <param name="timeout">Optional - timeout in milliseconds</param>
/// <returns>Current WebDriver</returns>
/// VBA example:
/// <example><code lang="vbs">
/// Sub WaitForTitle(driver, argument, result)
/// result = driver.Title = argument
/// End Sub
///
/// Sub testSimple()
/// Dim driver As New FirefoxDriver
/// driver.Get "http://www.google.com"
/// driver.Until AddressOf WaitForTitle, "Google"
/// ...
/// End Sub
/// </code>
/// </example>
///
/// VBScript example:
/// <example><code lang="vbs">
/// Function WaitForTitle(driver, argument)
/// WaitForTitle = driver.Title = argument
/// End Function
///
/// Sub testSimple()
/// Dim driver As New FirefoxDriver
/// driver.Get "http://www.google.com"
/// driver.Until GetRef("WaitForTitle"), "Google", 1000
/// ...
/// End Sub
/// </code>
/// </example>
object ComInterfaces._WebDriver.Until(object procedure, object argument, int timeout) {
if (timeout == -1)
timeout = session.timeouts.timeout_implicitwait;
return COMExt.WaitUntilProc(procedure, this, argument, timeout);
}
#endregion
#region Cache
/// <summary>
/// Get the status of the html5 application cache.
/// </summary>
/// <returns>{number} Status code for application cache: {UNCACHED = 0, IDLE = 1, CHECKING = 2, DOWNLOADING = 3, UPDATE_READY = 4, OBSOLETE = 5}</returns>
public CacheState CacheStatus() {
return (CacheState)session.Send(RequestMethod.GET, "/application_cache/status");
}
#endregion