-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
1483 lines (1286 loc) · 37.8 KB
/
remote.go
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
// Remote Selenium client implementation.
// See https://www.w3.org/TR/webdriver for the protocol.
package webdriver
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/blang/semver"
)
// Errors returned by Selenium server.
var remoteErrors = map[int]string{
6: "invalid session ID",
7: "no such element",
8: "no such frame",
9: "unknown command",
10: "stale element reference",
11: "element not visible",
12: "invalid element state",
13: "unknown error",
15: "element is not selectable",
17: "javascript error",
19: "xpath lookup error",
21: "timeout",
23: "no such window",
24: "invalid cookie domain",
25: "unable to set cookie",
26: "unexpected alert open",
27: "no alert open",
28: "script timeout",
29: "invalid element coordinates",
32: "invalid selector",
}
func debugLog(format string, args ...interface{}) {
if !debugFlag {
return
}
fmt.Printf(format+"\n", args...)
}
// filteredURL replaces existing password from the given URL.
func filteredURL(u string) string {
// Hide password if set in URL
m, err := url.Parse(u)
if err != nil {
return ""
}
if m.User != nil {
if _, ok := m.User.Password(); ok {
m.User = url.UserPassword(m.User.Username(), "__password__")
}
}
return m.String()
}
type remoteWD struct {
id, urlPrefix string
capabilities Capabilities
w3cCompatible bool
browser string
browserVersion semver.Version
}
// HTTPClient is the default client to use to communicate with the WebDriver
// server.
var HTTPClient = http.DefaultClient
// jsonContentType is JSON content type.
const jsonContentType = "application/json"
func newRequest(method string, url string, data []byte) (*http.Request, error) {
request, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
request.Header.Add("Accept", jsonContentType)
return request, nil
}
func (wd *remoteWD) requestURL(template string, args ...interface{}) string {
return wd.urlPrefix + fmt.Sprintf(template, args...)
}
// TODO(minusnine): provide a "sessionURL" function that prepends the
// /session/<id> URL prefix and replace most requestURL (and voidCommand) calls
// with it.
type serverReply struct {
SessionID *string // SessionID can be nil.
Value json.RawMessage
// The following fields were used prior to Selenium 3.0 for error state and
// in ChromeDriver for additional information.
Status int
State string
Error
}
// Error contains information about a failure of a command. See the table of
// these strings at https://www.w3.org/TR/webdriver/#handling-errors .
//
// This error type is only returned by servers that implement the W3C
// specification.
type Error struct {
// Err contains a general error string provided by the server.
Err string `json:"error"`
// Message is a detailed, human-readable message specific to the failure.
Message string `json:"message"`
// Stacktrace may contain the server-side stacktrace where the error occurred.
Stacktrace string `json:"stacktrace"`
// HTTPCode is the HTTP status code returned by the server.
HTTPCode int
// LegacyCode is the "Response Status Code" defined in the legacy Selenium
// WebDriver JSON wire protocol. This code is only produced by older
// Selenium WebDriver versions, Chromedriver, and InternetExplorerDriver.
LegacyCode int
}
// TODO(minusnine): Make Stacktrace more descriptive. Selenium emits a list of
// objects that enumerate various fields. This is not standard, though.
// Error implements the error interface.
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Err, e.Message)
}
// execute performs an HTTP request and inspects the returned data for an error
// encoded by the remote end in a JSON structure. If no error is present, the
// entire, raw request payload is returned.
func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {
return executeCommand(method, url, data)
}
func executeCommand(method, url string, data []byte) (json.RawMessage, error) {
debugLog("-> %s %s\n%s", method, filteredURL(url), data)
request, err := newRequest(method, url, data)
if err != nil {
return nil, err
}
response, err := HTTPClient.Do(request)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(response.Body)
if debugFlag {
if err == nil {
// Pretty print the JSON response
var prettyBuf bytes.Buffer
if err = json.Indent(&prettyBuf, buf, "", " "); err == nil && prettyBuf.Len() > 0 {
buf = prettyBuf.Bytes()
}
}
debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf)
}
if err != nil {
return nil, errors.New(response.Status)
}
fullCType := response.Header.Get("Content-Type")
cType, _, err := mime.ParseMediaType(fullCType)
if err != nil {
return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType)
}
if cType != jsonContentType {
return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType)
}
reply := new(serverReply)
if err := json.Unmarshal(buf, reply); err != nil {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad server reply status: %s", response.Status)
}
return nil, err
}
if reply.Err != "" {
return nil, &reply.Error
}
// Handle the W3C-compliant error format. In the W3C spec, the error is
// embedded in the 'value' field.
if len(reply.Value) > 0 {
respErr := new(Error)
if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" {
respErr.HTTPCode = response.StatusCode
return nil, respErr
}
}
// Handle the legacy error format.
const success = 0
if reply.Status != success {
shortMsg, ok := remoteErrors[reply.Status]
if !ok {
shortMsg = fmt.Sprintf("unknown error - %d", reply.Status)
}
longMsg := new(struct {
Message string
})
if err := json.Unmarshal(reply.Value, longMsg); err != nil {
return nil, errors.New(shortMsg)
}
return nil, &Error{
Err: shortMsg,
Message: longMsg.Message,
HTTPCode: response.StatusCode,
LegacyCode: reply.Status,
}
}
return buf, nil
}
// DefaultURLPrefix is the default HTTP endpoint that offers the WebDriver API.
const DefaultURLPrefix = "http://127.0.0.1:4444/wd/hub"
// NewRemote creates new remote client, this will also start a new session.
// capabilities provides the desired capabilities. urlPrefix is the URL to the
// Selenium server, must be prefixed with protocol (http, https, ...).
//
// Providing an empty string for urlPrefix causes the DefaultURLPrefix to be
// used.
func NewRemote(capabilities Capabilities, urlPrefix string) (WebDriver, error) {
if urlPrefix == "" {
urlPrefix = DefaultURLPrefix
}
wd := &remoteWD{
urlPrefix: urlPrefix,
capabilities: capabilities,
}
if b := capabilities["browserName"]; b != nil {
wd.browser = b.(string)
}
if _, err := wd.NewSession(); err != nil {
return nil, err
}
return wd, nil
}
// DeleteSession deletes an existing session at the WebDriver instance
// specified by the urlPrefix and the session ID.
func DeleteSession(urlPrefix, id string) error {
u, err := url.Parse(urlPrefix)
if err != nil {
return err
}
u.Path = path.Join(u.Path, "session", id)
return voidCommand("DELETE", u.String(), nil)
}
func (wd *remoteWD) stringCommand(urlTemplate string) (string, error) {
url := wd.requestURL(urlTemplate, wd.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return "", err
}
reply := new(struct{ Value *string })
if err := json.Unmarshal(response, reply); err != nil {
return "", err
}
if reply.Value == nil {
return "", fmt.Errorf("nil return value")
}
return *reply.Value, nil
}
func voidCommand(method, url string, params interface{}) error {
if params == nil {
params = make(map[string]interface{})
}
data, err := json.Marshal(params)
if err != nil {
return err
}
_, err = executeCommand(method, url, data)
return err
}
func (wd *remoteWD) voidCommand(urlTemplate string, params interface{}) error {
return voidCommand("POST", wd.requestURL(urlTemplate, wd.id), params)
}
func (wd remoteWD) stringsCommand(urlTemplate string) ([]string, error) {
url := wd.requestURL(urlTemplate, wd.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
reply := new(struct{ Value []string })
if err := json.Unmarshal(response, reply); err != nil {
return nil, err
}
return reply.Value, nil
}
func (wd *remoteWD) boolCommand(urlTemplate string) (bool, error) {
url := wd.requestURL(urlTemplate, wd.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return false, err
}
reply := new(struct{ Value bool })
if err := json.Unmarshal(response, reply); err != nil {
return false, err
}
return reply.Value, nil
}
func (wd *remoteWD) Status() (*Status, error) {
url := wd.requestURL("/status")
reply, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
status := new(struct{ Value Status })
if err := json.Unmarshal(reply, status); err != nil {
return nil, err
}
return &status.Value, nil
}
// parseVersion sanitizes the browser version enough for semver.ParseTolerant
// to parse it.
func parseVersion(v string) (semver.Version, error) {
parts := strings.Split(v, ".")
var err error
for i := len(parts); i > 0; i-- {
var ver semver.Version
ver, err = semver.ParseTolerant(strings.Join(parts[:i], "."))
if err == nil {
return ver, nil
}
}
return semver.Version{}, err
}
// The list of valid, top-level capability names, according to the W3C
// specification.
//
// This must be kept in sync with the specification:
// https://www.w3.org/TR/webdriver/#capabilities
var w3cCapabilityNames = []string{
"acceptInsecureCerts",
"browserName",
"browserVersion",
"platformName",
"pageLoadStrategy",
"proxy",
"setWindowRect",
"timeouts",
"unhandledPromptBehavior",
}
var chromeCapabilityNames = []string{
// This is not a standardized top-level capability name, but Chromedriver
// expects this capability here.
// https://cs.chromium.org/chromium/src/chrome/test/chromedriver/capabilities.cc?rcl=0754b5d0aad903439a628618f0e41845f1988f0c&l=759
"loggingPrefs",
}
// Create a W3C-compatible capabilities instance.
func newW3CCapabilities(caps Capabilities) Capabilities {
isValidW3CCapability := map[string]bool{}
for _, name := range w3cCapabilityNames {
isValidW3CCapability[name] = true
}
if b, ok := caps["browserName"]; ok && b == "chrome" {
for _, name := range chromeCapabilityNames {
isValidW3CCapability[name] = true
}
}
alwaysMatch := make(Capabilities)
for name, value := range caps {
if isValidW3CCapability[name] || strings.Contains(name, ":") {
alwaysMatch[name] = value
}
}
return Capabilities{
"alwaysMatch": alwaysMatch,
}
}
func (wd *remoteWD) NewSession() (string, error) {
// Detect whether the remote end complies with the W3C specification:
// non-compliant implementations use the top-level 'desiredCapabilities' JSON
// key, whereas the specification mandates the 'capabilities' key.
//
// However, Selenium 3 currently does not implement this part of the specification.
// https://github.com/SeleniumHQ/selenium/issues/2827
//
// TODO(minusnine): audit which ones of these are still relevant. The W3C
// standard switched to the "alwaysMatch" version in February 2017.
attempts := []struct {
params map[string]interface{}
}{
{map[string]interface{}{
"capabilities": newW3CCapabilities(wd.capabilities),
"desiredCapabilities": wd.capabilities,
}},
{map[string]interface{}{
"capabilities": map[string]interface{}{
"desiredCapabilities": wd.capabilities,
},
}},
{map[string]interface{}{
"desiredCapabilities": wd.capabilities,
}}}
for i, s := range attempts {
data, err := json.Marshal(s.params)
if err != nil {
return "", err
}
response, err := wd.execute("POST", wd.requestURL("/session"), data)
if err != nil {
return "", err
}
reply := new(serverReply)
if err := json.Unmarshal(response, reply); err != nil {
if i < len(attempts) {
continue
}
return "", err
}
if reply.Status != 0 && i < len(attempts) {
continue
}
if reply.SessionID != nil {
wd.id = *reply.SessionID
}
if len(reply.Value) > 0 {
type returnedCapabilities struct {
// firefox via geckodriver: 55.0a1
BrowserVersion string
// chrome via chromedriver: 61.0.3116.0
// firefox via selenium 2: 45.9.0
// htmlunit: 9.4.3.v20170317
Version string
PageLoadStrategy string
Proxy Proxy
Timeouts struct {
Implicit float32
PageLoadLegacy float32 `json:"page load"`
PageLoad float32
Script float32
}
}
value := struct {
SessionID string
// The W3C specification moved most of the returned data into the
// "capabilities" field.
Capabilities *returnedCapabilities
// Legacy implementations returned most data directly in the "values"
// key.
returnedCapabilities
}{}
if err := json.Unmarshal(reply.Value, &value); err != nil {
return "", fmt.Errorf("error unmarshalling value: %v", err)
}
if value.SessionID != "" && wd.id == "" {
wd.id = value.SessionID
}
var caps returnedCapabilities
if value.Capabilities != nil {
caps = *value.Capabilities
wd.w3cCompatible = true
} else {
caps = value.returnedCapabilities
}
for _, s := range []string{caps.Version, caps.BrowserVersion} {
if s == "" {
continue
}
v, err := parseVersion(s)
if err != nil {
debugLog("error parsing version: %v\n", err)
continue
}
wd.browserVersion = v
}
}
return wd.id, nil
}
panic("unreachable")
}
// SessionId returns the current session ID
//
// Deprecated: This identifier is not Go-style correct. Use SessionID instead.
func (wd *remoteWD) SessionId() string {
return wd.SessionID()
}
// SessionID returns the current session ID
func (wd *remoteWD) SessionID() string {
return wd.id
}
func (wd *remoteWD) SwitchSession(sessionID string) error {
wd.id = sessionID
return nil
}
func (wd *remoteWD) Capabilities() (Capabilities, error) {
url := wd.requestURL("/session/%s", wd.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
c := new(struct{ Value Capabilities })
if err := json.Unmarshal(response, c); err != nil {
return nil, err
}
return c.Value, nil
}
func (wd *remoteWD) SetAsyncScriptTimeout(timeout time.Duration) error {
if !wd.w3cCompatible {
return wd.voidCommand("/session/%s/timeouts/async_script", map[string]uint{
"ms": uint(timeout / time.Millisecond),
})
}
return wd.voidCommand("/session/%s/timeouts", map[string]uint{
"script": uint(timeout / time.Millisecond),
})
}
func (wd *remoteWD) SetImplicitWaitTimeout(timeout time.Duration) error {
if !wd.w3cCompatible {
return wd.voidCommand("/session/%s/timeouts/implicit_wait", map[string]uint{
"ms": uint(timeout / time.Millisecond),
})
}
return wd.voidCommand("/session/%s/timeouts", map[string]uint{
"implicit": uint(timeout / time.Millisecond),
})
}
func (wd *remoteWD) SetPageLoadTimeout(timeout time.Duration) error {
if !wd.w3cCompatible {
return wd.voidCommand("/session/%s/timeouts", map[string]interface{}{
"ms": uint(timeout / time.Millisecond),
"type": "page load",
})
}
return wd.voidCommand("/session/%s/timeouts", map[string]uint{
"pageLoad": uint(timeout / time.Millisecond),
})
}
func (wd *remoteWD) Quit() error {
if wd.id == "" {
return nil
}
_, err := wd.execute("DELETE", wd.requestURL("/session/%s", wd.id), nil)
if err == nil {
wd.id = ""
}
return err
}
func (wd *remoteWD) CurrentWindowHandle() (string, error) {
if !wd.w3cCompatible {
return wd.stringCommand("/session/%s/window_handle")
}
return wd.stringCommand("/session/%s/window")
}
func (wd *remoteWD) WindowHandles() ([]string, error) {
if !wd.w3cCompatible {
return wd.stringsCommand("/session/%s/window_handles")
}
return wd.stringsCommand("/session/%s/window/handles")
}
func (wd *remoteWD) CurrentURL() (string, error) {
url := wd.requestURL("/session/%s/url", wd.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return "", err
}
reply := new(struct{ Value *string })
if err := json.Unmarshal(response, reply); err != nil {
return "", err
}
return *reply.Value, nil
}
func (wd *remoteWD) Get(url string) error {
requestURL := wd.requestURL("/session/%s/url", wd.id)
params := map[string]string{
"url": url,
}
data, err := json.Marshal(params)
if err != nil {
return err
}
_, err = wd.execute("POST", requestURL, data)
return err
}
func (wd *remoteWD) Forward() error {
return wd.voidCommand("/session/%s/forward", nil)
}
func (wd *remoteWD) Back() error {
return wd.voidCommand("/session/%s/back", nil)
}
func (wd *remoteWD) Refresh() error {
return wd.voidCommand("/session/%s/refresh", nil)
}
func (wd *remoteWD) Title() (string, error) {
return wd.stringCommand("/session/%s/title")
}
func (wd *remoteWD) PageSource() (string, error) {
return wd.stringCommand("/session/%s/source")
}
func (wd *remoteWD) find(by, value, suffix, url string) ([]byte, error) {
// The W3C specification removed the specific ID and Name locator strategies,
// instead only providing a CSS-based strategy. Emulate the old behavior to
// maintain API compatibility.
if wd.w3cCompatible {
switch by {
case ByID:
by = ByCSSSelector
value = "#" + value
case ByName:
by = ByCSSSelector
value = fmt.Sprintf("input[name=%q]", value)
}
}
params := map[string]string{
"using": by,
"value": value,
}
data, err := json.Marshal(params)
if err != nil {
return nil, err
}
if len(url) == 0 {
url = "/session/%s/element"
}
return wd.execute("POST", wd.requestURL(url+suffix, wd.id), data)
}
func (wd *remoteWD) DecodeElement(data []byte) (WebElement, error) {
reply := new(struct{ Value map[string]string })
if err := json.Unmarshal(data, &reply); err != nil {
return nil, err
}
id := elementIDFromValue(reply.Value)
if id == "" {
return nil, fmt.Errorf("invalid element returned: %+v", reply)
}
return &remoteWE{
parent: wd,
id: id,
}, nil
}
const (
// legacyWebElementIdentifier is the string constant used in the old
// WebDriver JSON protocol that is the key for the map that contains an
// unique element identifier.
legacyWebElementIdentifier = "ELEMENT"
// webElementIdentifier is the string constant defined by the W3C
// specification that is the key for the map that contains a unique element identifier.
webElementIdentifier = "element-6066-11e4-a52e-4f735466cecf"
)
func elementIDFromValue(v map[string]string) string {
for _, key := range []string{webElementIdentifier, legacyWebElementIdentifier} {
v, ok := v[key]
if !ok || v == "" {
continue
}
return v
}
return ""
}
func (wd *remoteWD) DecodeElements(data []byte) ([]WebElement, error) {
reply := new(struct{ Value []map[string]string })
if err := json.Unmarshal(data, reply); err != nil {
return nil, err
}
elems := make([]WebElement, len(reply.Value))
for i, elem := range reply.Value {
id := elementIDFromValue(elem)
if id == "" {
return nil, fmt.Errorf("invalid element returned: %+v", reply)
}
elems[i] = &remoteWE{
parent: wd,
id: id,
}
}
return elems, nil
}
func (wd *remoteWD) FindElement(by, value string) (WebElement, error) {
response, err := wd.find(by, value, "", "")
if err != nil {
return nil, err
}
return wd.DecodeElement(response)
}
func (wd *remoteWD) FindElements(by, value string) ([]WebElement, error) {
response, err := wd.find(by, value, "s", "")
if err != nil {
return nil, err
}
return wd.DecodeElements(response)
}
func (wd *remoteWD) Close() error {
url := wd.requestURL("/session/%s/window", wd.id)
_, err := wd.execute("DELETE", url, nil)
return err
}
func (wd *remoteWD) SwitchWindow(name string) error {
params := make(map[string]string)
if !wd.w3cCompatible {
params["name"] = name
} else {
params["handle"] = name
}
return wd.voidCommand("/session/%s/window", params)
}
func (wd *remoteWD) CloseWindow(name string) error {
return wd.modifyWindow(name, "DELETE", "", nil)
}
func (wd *remoteWD) MaximizeWindow(name string) error {
if !wd.w3cCompatible {
if name != "" {
var err error
name, err = wd.CurrentWindowHandle()
if err != nil {
return err
}
}
url := wd.requestURL("/session/%s/window/%s/maximize", wd.id, name)
_, err := wd.execute("POST", url, nil)
return err
}
return wd.modifyWindow(name, "POST", "maximize", map[string]string{})
}
func (wd *remoteWD) MinimizeWindow(name string) error {
return wd.modifyWindow(name, "POST", "minimize", map[string]string{})
}
func (wd *remoteWD) modifyWindow(name, verb, command string, params interface{}) error {
// The original protocol allowed for maximizing any named window. The W3C
// specification only allows the current window be be modified. Emulate the
// previous behavior by switching to the target window, maximizing the
// current window, and switching back to the original window.
var startWindow string
if name != "" && wd.w3cCompatible {
var err error
startWindow, err = wd.CurrentWindowHandle()
if err != nil {
return err
}
if name != startWindow {
if err := wd.SwitchWindow(name); err != nil {
return err
}
}
}
url := wd.requestURL("/session/%s/window", wd.id)
if command != "" {
if wd.w3cCompatible {
url = wd.requestURL("/session/%s/window/%s", wd.id, command)
} else {
url = wd.requestURL("/session/%s/window/%s/%s", wd.id, name, command)
}
}
var data []byte
if params != nil {
var err error
if data, err = json.Marshal(params); err != nil {
return err
}
}
if _, err := wd.execute(verb, url, data); err != nil {
return err
}
// TODO(minusnine): add a test for switching back to the original window.
if name != startWindow && wd.w3cCompatible {
if err := wd.SwitchWindow(startWindow); err != nil {
return err
}
}
return nil
}
func (wd *remoteWD) ResizeWindow(name string, width, height int) error {
if !wd.w3cCompatible {
return wd.modifyWindow(name, "POST", "size", map[string]int{
"width": width,
"height": height,
})
}
return wd.modifyWindow(name, "POST", "rect", map[string]float64{
"width": float64(width),
"height": float64(height),
})
}
func (wd *remoteWD) SwitchFrame(frame interface{}) error {
params := map[string]interface{}{}
switch f := frame.(type) {
case WebElement, int, nil:
params["id"] = f
case string:
if f == "" {
params["id"] = nil
} else if wd.w3cCompatible {
e, err := wd.FindElement(ByID, f)
if err != nil {
return err
}
params["id"] = e
} else { // Legacy, non W3C-spec behavior.
params["id"] = f
}
default:
return fmt.Errorf("invalid type %T", frame)
}
return wd.voidCommand("/session/%s/frame", params)
}
func (wd *remoteWD) ActiveElement() (WebElement, error) {
verb := "GET"
if wd.browser == "firefox" && wd.browserVersion.Major < 47 {
verb = "POST"
}
url := wd.requestURL("/session/%s/element/active", wd.id)
response, err := wd.execute(verb, url, nil)
if err != nil {
return nil, err
}
return wd.DecodeElement(response)
}
// ChromeDriver returns the expiration date as a float. Handle both formats
// via a type switch.
type cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
Domain string `json:"domain"`
Secure bool `json:"secure"`
Expiry interface{} `json:"expiry"`
}
func (c cookie) sanitize() Cookie {
sanitized := Cookie{
Name: c.Name,
Value: c.Value,
Path: c.Path,
Domain: c.Domain,
Secure: c.Secure,
}
switch expiry := c.Expiry.(type) {
case int:
if expiry > 0 {
sanitized.Expiry = uint(expiry)
}
case float64:
sanitized.Expiry = uint(expiry)
}
return sanitized
}
func (wd *remoteWD) GetCookie(name string) (Cookie, error) {
if wd.browser == "chrome" {
cs, err := wd.GetCookies()
if err != nil {
return Cookie{}, err
}
for _, c := range cs {
if c.Name == name {
return c, nil
}
}
return Cookie{}, errors.New("cookie not found")
}
url := wd.requestURL("/session/%s/cookie/%s", wd.id, name)
data, err := wd.execute("GET", url, nil)
if err != nil {
return Cookie{}, err
}
// GeckoDriver returns a list of cookies for this method. Try both a single
// cookie and a list.
//
// https://github.com/mozilla/geckodriver/issues/761
reply := new(struct{ Value cookie })
if err := json.Unmarshal(data, reply); err == nil {
return reply.Value.sanitize(), nil
}
listReply := new(struct{ Value []cookie })
if err := json.Unmarshal(data, listReply); err != nil {
return Cookie{}, err
}
if len(listReply.Value) == 0 {
return Cookie{}, errors.New("no cookies returned")
}
return listReply.Value[0].sanitize(), nil
}
func (wd *remoteWD) GetCookies() ([]Cookie, error) {
url := wd.requestURL("/session/%s/cookie", wd.id)
data, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
reply := new(struct{ Value []cookie })
if err := json.Unmarshal(data, reply); err != nil {
return nil, err
}
cookies := make([]Cookie, len(reply.Value))
for i, c := range reply.Value {
sanitized := Cookie{
Name: c.Name,
Value: c.Value,
Path: c.Path,
Domain: c.Domain,
Secure: c.Secure,
}
switch expiry := c.Expiry.(type) {
case int:
if expiry > 0 {