-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathwindow_commands.cc
2966 lines (2683 loc) · 110 KB
/
window_commands.cc
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 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/window_commands.h"
#include <stddef.h>
#include <algorithm>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "base/containers/adapters.h"
#include "base/containers/flat_set.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/test/chromedriver/basic_types.h"
#include "chrome/test/chromedriver/chrome/chrome.h"
#include "chrome/test/chromedriver/chrome/chrome_desktop_impl.h"
#include "chrome/test/chromedriver/chrome/devtools_client.h"
#include "chrome/test/chromedriver/chrome/geoposition.h"
#include "chrome/test/chromedriver/chrome/mobile_emulation_override_manager.h"
#include "chrome/test/chromedriver/chrome/network_conditions.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "chrome/test/chromedriver/chrome/ui_events.h"
#include "chrome/test/chromedriver/chrome/web_view.h"
#include "chrome/test/chromedriver/element_commands.h"
#include "chrome/test/chromedriver/element_util.h"
#include "chrome/test/chromedriver/key_converter.h"
#include "chrome/test/chromedriver/net/command_id.h"
#include "chrome/test/chromedriver/net/timeout.h"
#include "chrome/test/chromedriver/session.h"
#include "chrome/test/chromedriver/util.h"
#include "ui/gfx/geometry/point.h"
#include "url/url_util.h"
namespace {
// The error page URL was renamed in
// https://chromium-review.googlesource.com/c/580169, but because ChromeDriver
// needs to be backward-compatible with older versions of Chrome, it is
// necessary to compare against both the old and new error URL.
static const char kUnreachableWebDataURL[] = "chrome-error://chromewebdata/";
const char kDeprecatedUnreachableWebDataURL[] = "data:text/html,chromewebdata";
// Match to content/browser/devtools/devTools_session const of same name
const char kTargetClosedMessage[] = "Inspected target navigated or closed";
// TODO(crbug.com/chromedriver/2596): Remove when we stop supporting legacy
// protocol.
// Defaults to 20 years into the future when adding a cookie.
const double kDefaultCookieExpiryTime = 20*365*24*60*60;
// for pointer actions
enum class PointerActionType { NOT_INITIALIZED, PRESS, MOVE, RELEASE, IDLE };
const base::flat_set<StatusCode> kNavigationHints = {
kNoSuchExecutionContext,
kAbortedByNavigation,
};
Status GetMouseButton(const base::Value::Dict& params, MouseButton* button) {
// Default to left mouse button.
int button_num = params.FindInt("button").value_or(0);
if (button_num < 0 || button_num > 2) {
return Status(kInvalidArgument,
base::StringPrintf("invalid button: %d", button_num));
}
*button = static_cast<MouseButton>(button_num);
return Status(kOk);
}
Status IntToStringButton(int button, std::string& out) {
if (button == 0) {
out = "left";
} else if (button == 1) {
out = "middle";
} else if (button == 2) {
out = "right";
} else if (button == 3) {
out = "back";
} else if (button == 4) {
out = "forward";
} else {
return Status(kInvalidArgument,
"'button' must be an integer between 0 and 4 inclusive");
}
return Status(kOk);
}
Status GetUrl(WebView* web_view, const std::string& frame, std::string* url) {
std::unique_ptr<base::Value> value;
base::Value::List args;
Status status = web_view->CallFunction(
frame, "function() { return document.URL; }", args, &value);
if (status.IsError())
return status;
if (!value->is_string())
return Status(kUnknownError, "javascript failed to return the url");
*url = value->GetString();
return Status(kOk);
}
MouseEventType StringToMouseEventType(std::string action_type) {
if (action_type == "pointerDown")
return kPressedMouseEventType;
if (action_type == "pointerUp")
return kReleasedMouseEventType;
if (action_type == "pointerMove")
return kMovedMouseEventType;
if (action_type == "scroll")
return kWheelMouseEventType;
if (action_type == "pause")
return kPauseMouseEventType;
return kPressedMouseEventType;
}
MouseButton StringToMouseButton(std::string button_type) {
if (button_type == "left")
return kLeftMouseButton;
if (button_type == "middle")
return kMiddleMouseButton;
if (button_type == "right")
return kRightMouseButton;
if (button_type == "back")
return kBackMouseButton;
if (button_type == "forward")
return kForwardMouseButton;
return kNoneMouseButton;
}
TouchEventType StringToTouchEventType(std::string action_type) {
if (action_type == "pointerDown")
return kTouchStart;
if (action_type == "pointerUp")
return kTouchEnd;
if (action_type == "pointerMove")
return kTouchMove;
if (action_type == "pointerCancel")
return kTouchCancel;
if (action_type == "pause")
return kPause;
return kTouchStart;
}
int StringToModifierMouseButton(std::string button_type) {
if (button_type == "left")
return 1;
if (button_type == "right")
return 2;
if (button_type == "middle")
return 4;
if (button_type == "back")
return 8;
if (button_type == "forward")
return 16;
return 0;
}
int MouseButtonToButtons(MouseButton button) {
switch (button) {
case kLeftMouseButton:
return 1;
case kRightMouseButton:
return 2;
case kMiddleMouseButton:
return 4;
case kBackMouseButton:
return 8;
case kForwardMouseButton:
return 16;
default:
return 0;
}
}
int KeyToKeyModifiers(std::string key) {
if (key == "Shift")
return kShiftKeyModifierMask;
if (key == "Control")
return kControlKeyModifierMask;
if (key == "Alt")
return kAltKeyModifierMask;
if (key == "Meta")
return kMetaKeyModifierMask;
return 0;
}
PointerType StringToPointerType(std::string pointer_type) {
CHECK(pointer_type == "pen" || pointer_type == "mouse");
if (pointer_type == "pen")
return kPen;
return kMouse;
}
struct Cookie {
Cookie(const std::string& name,
const std::string& value,
const std::string& domain,
const std::string& path,
const std::string& samesite,
int64_t expiry,
bool http_only,
bool secure,
bool session)
: name(name),
value(value),
domain(domain),
path(path),
samesite(samesite),
expiry(expiry),
http_only(http_only),
secure(secure),
session(session) {}
std::string name;
std::string value;
std::string domain;
std::string path;
std::string samesite;
int64_t expiry;
bool http_only;
bool secure;
bool session;
};
base::Value::Dict CreateDictionaryFrom(const Cookie& cookie) {
base::Value::Dict dict;
dict.Set("name", cookie.name);
dict.Set("value", cookie.value);
if (!cookie.domain.empty())
dict.Set("domain", cookie.domain);
if (!cookie.path.empty())
dict.Set("path", cookie.path);
if (!cookie.session)
SetSafeInt(dict, "expiry", cookie.expiry);
dict.Set("httpOnly", cookie.http_only);
dict.Set("secure", cookie.secure);
if (!cookie.samesite.empty()) {
dict.Set("sameSite", cookie.samesite);
} else {
// The default in the standard is Lax:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
// Chrome (mostly) treats default cookies as Lax so this seems correct:
// https://chromestatus.com/feature/5088147346030592
dict.Set("sameSite", "Lax");
}
return dict;
}
Status GetVisibleCookies(Session* for_session,
WebView* web_view,
std::list<Cookie>* cookies) {
std::string current_page_url;
Status status =
GetUrl(web_view, for_session->GetCurrentFrameId(), ¤t_page_url);
if (status.IsError())
return status;
base::Value internal_cookies;
status = web_view->GetCookies(&internal_cookies, current_page_url);
if (status.IsError())
return status;
std::list<Cookie> cookies_tmp;
for (const base::Value& cookie_value : internal_cookies.GetList()) {
if (!cookie_value.is_dict())
return Status(kUnknownError, "DevTools returns a non-dictionary cookie");
const base::Value::Dict& cookie_dict = cookie_value.GetDict();
const std::string* name = cookie_dict.FindString("name");
const std::string* value = cookie_dict.FindString("value");
const std::string* domain = cookie_dict.FindString("domain");
const std::string* path = cookie_dict.FindString("path");
std::string samesite;
GetOptionalString(cookie_dict, "sameSite", &samesite);
int64_t expiry =
static_cast<int64_t>(cookie_dict.FindDouble("expires").value_or(0));
// Truncate & convert the value to an integer as required by W3C spec.
if (expiry >= (1ll << 53) || expiry <= -(1ll << 53))
expiry = 0;
bool http_only = cookie_dict.FindBool("httpOnly").value_or(false);
bool session = cookie_dict.FindBool("session").value_or(false);
bool secure = cookie_dict.FindBool("secure").value_or(false);
cookies_tmp.push_back(Cookie(*name, *value, *domain, *path, samesite,
expiry, http_only, secure, session));
}
cookies->swap(cookies_tmp);
return Status(kOk);
}
Status ScrollCoordinateInToView(
Session* session, WebView* web_view, int x, int y, int* offset_x,
int* offset_y) {
std::unique_ptr<base::Value> value;
base::Value::List args;
args.Append(x);
args.Append(y);
Status status = web_view->CallFunction(
std::string(),
"function(x, y) {"
" if (x < window.pageXOffset ||"
" x >= window.pageXOffset + window.innerWidth ||"
" y < window.pageYOffset ||"
" y >= window.pageYOffset + window.innerHeight) {"
" window.scrollTo(x - window.innerWidth/2, y - window.innerHeight/2);"
" }"
" return {"
" view_x: Math.floor(window.pageXOffset),"
" view_y: Math.floor(window.pageYOffset),"
" view_width: Math.floor(window.innerWidth),"
" view_height: Math.floor(window.innerHeight)};"
"}",
args,
&value);
if (!status.IsOk())
return status;
const base::Value::Dict& view_attrib = value->GetDict();
int view_x = view_attrib.FindInt("view_x").value_or(0);
int view_y = view_attrib.FindInt("view_y").value_or(0);
int view_width = view_attrib.FindInt("view_width").value_or(0);
int view_height = view_attrib.FindInt("view_height").value_or(0);
*offset_x = x - view_x;
*offset_y = y - view_y;
if (*offset_x < 0 || *offset_x >= view_width || *offset_y < 0 ||
*offset_y >= view_height) {
return Status(kUnknownError, "Failed to scroll coordinate into view");
}
return Status(kOk);
}
Status ExecuteTouchEvent(Session* session,
WebView* web_view,
TouchEventType type,
const base::Value::Dict& params) {
std::optional<int> x = params.FindInt("x");
std::optional<int> y = params.FindInt("y");
if (!x)
return Status(kInvalidArgument, "'x' must be an integer");
if (!y)
return Status(kInvalidArgument, "'y' must be an integer");
int relative_x = *x;
int relative_y = *y;
Status status = ScrollCoordinateInToView(session, web_view, *x, *y,
&relative_x, &relative_y);
if (!status.IsOk())
return status;
std::vector<TouchEvent> events;
events.emplace_back(type, relative_x, relative_y);
return web_view->DispatchTouchEvents(events, false);
}
Status WindowViewportSize(Session* session,
WebView* web_view,
int* inner_width,
int* inner_height) {
DCHECK(inner_width);
DCHECK(inner_height);
std::unique_ptr<base::Value> value;
base::Value::List args;
Status status =
web_view->CallFunction(std::string(),
"function() {"
" return {"
" view_width: Math.floor(window.innerWidth),"
" view_height: Math.floor(window.innerHeight)};"
"}",
args, &value);
if (!status.IsOk())
return status;
const base::Value::Dict& view_attrib = value->GetDict();
std::optional<int> maybe_inner_width = view_attrib.FindInt("view_width");
if (maybe_inner_width)
*inner_width = *maybe_inner_width;
std::optional<int> maybe_inner_height = view_attrib.FindInt("view_height");
if (maybe_inner_height)
*inner_height = *maybe_inner_height;
return Status(kOk);
}
Status ProcessPauseAction(const base::Value::Dict& action_item,
base::Value::Dict* action) {
int duration = 0;
bool has_value = false;
if (!GetOptionalInt(action_item, "duration", &duration, &has_value) ||
duration < 0)
return Status(kInvalidArgument, "'duration' must be a non-negative int");
if (has_value)
action->Set("duration", duration);
return Status(kOk);
}
Status ElementInViewCenter(Session* session,
WebView* web_view,
std::string element_id,
int* center_x,
int* center_y) {
WebPoint center_location;
Status status = GetElementLocationInViewCenter(session, web_view, element_id,
¢er_location);
if (status.IsError())
return status;
*center_x = center_location.x;
*center_y = center_location.y;
return Status(kOk);
}
int GetMouseClickCount(int last_click_count,
float x,
float y,
float last_x,
float last_y,
int button_id,
int last_button_id,
const base::TimeTicks& timestamp,
const base::TimeTicks& last_mouse_click_time) {
const int kDoubleClickTimeMS = 500;
const int kDoubleClickRange = 4;
if (last_click_count == 0)
return 1;
base::TimeDelta time_difference = timestamp - last_mouse_click_time;
if (time_difference.InMilliseconds() > kDoubleClickTimeMS)
return 1;
if (std::abs(x - last_x) > kDoubleClickRange / 2)
return 1;
if (std::abs(y - last_y) > kDoubleClickRange / 2)
return 1;
if (last_button_id != button_id)
return 1;
#if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_WIN)
// On Mac and Windows, we keep increasing the click count, but on the other
// platforms, we reset the count to 1 when it is greater than 3.
if (last_click_count >= 3)
return 1;
#endif
return last_click_count + 1;
}
const char kLandscape[] = "landscape";
const char kPortrait[] = "portrait";
Status ParseOrientation(const base::Value::Dict& params,
std::string* orientation) {
bool has_value;
if (!GetOptionalString(params, "orientation", orientation, &has_value)) {
return Status(kInvalidArgument, "'orientation' must be a string");
}
if (!has_value) {
*orientation = kPortrait;
} else if (*orientation != kPortrait && *orientation != kLandscape) {
return Status(kInvalidArgument, "'orientation' must be '" +
std::string(kPortrait) + "' or '" +
std::string(kLandscape) + "'");
}
return Status(kOk);
}
Status ParseScale(const base::Value::Dict& params, double* scale) {
bool has_value;
if (!GetOptionalDouble(params, "scale", scale, &has_value)) {
return Status(kInvalidArgument, "'scale' must be a double");
}
if (!has_value) {
*scale = 1;
} else if (*scale < 0.1 || *scale > 2) {
return Status(kInvalidArgument, "'scale' must not be < 0.1 or > 2");
}
return Status(kOk);
}
Status ParseBoolean(const base::Value::Dict& params,
const std::string& name,
bool default_value,
bool* b) {
*b = default_value;
if (!GetOptionalBool(params, name, b)) {
return Status(kInvalidArgument, "'" + name + "' must be a boolean");
}
return Status(kOk);
}
Status GetNonNegativeDouble(const base::Value::Dict& dict,
const std::string& parent,
const std::string& child,
double* attribute) {
bool has_value;
std::string attribute_str = "'" + parent + "." + child + "'";
if (!GetOptionalDouble(dict, child, attribute, &has_value)) {
return Status(kInvalidArgument, attribute_str + " must be a double");
}
if (has_value) {
*attribute = ConvertCentimeterToInch(*attribute);
if (*attribute < 0) {
return Status(kInvalidArgument,
attribute_str + " must not be less than 0");
}
}
return Status(kOk);
}
struct Page {
double width;
double height;
};
Status ParsePage(const base::Value::Dict& params, Page* page) {
bool has_value;
const base::Value::Dict* page_dict = nullptr;
if (!GetOptionalDictionary(params, "page", &page_dict, &has_value)) {
return Status(kInvalidArgument, "'page' must be an object");
}
page->width = ConvertCentimeterToInch(21.59);
page->height = ConvertCentimeterToInch(27.94);
if (!has_value)
return Status(kOk);
Status status =
GetNonNegativeDouble(*page_dict, "page", "width", &page->width);
if (status.IsError())
return status;
status = GetNonNegativeDouble(*page_dict, "page", "height", &page->height);
if (status.IsError())
return status;
return Status(kOk);
}
struct Margin {
double top;
double bottom;
double left;
double right;
};
Status ParseMargin(const base::Value::Dict& params, Margin* margin) {
bool has_value;
const base::Value::Dict* margin_dict = nullptr;
if (!GetOptionalDictionary(params, "margin", &margin_dict, &has_value)) {
return Status(kInvalidArgument, "'margin' must be an object");
}
margin->top = ConvertCentimeterToInch(1.0);
margin->bottom = ConvertCentimeterToInch(1.0);
margin->left = ConvertCentimeterToInch(1.0);
margin->right = ConvertCentimeterToInch(1.0);
if (!has_value)
return Status(kOk);
Status status =
GetNonNegativeDouble(*margin_dict, "margin", "top", &margin->top);
if (status.IsError())
return status;
status =
GetNonNegativeDouble(*margin_dict, "margin", "bottom", &margin->bottom);
if (status.IsError())
return status;
status = GetNonNegativeDouble(*margin_dict, "margin", "left", &margin->left);
if (status.IsError())
return status;
status =
GetNonNegativeDouble(*margin_dict, "margin", "right", &margin->right);
if (status.IsError())
return status;
return Status(kOk);
}
Status ParsePageRanges(const base::Value::Dict& params,
std::string* page_ranges) {
bool has_value;
const base::Value::List* page_range_list = nullptr;
if (!GetOptionalList(params, "pageRanges", &page_range_list, &has_value)) {
return Status(kInvalidArgument, "'pageRanges' must be an array");
}
if (!has_value) {
return Status(kOk);
}
std::vector<std::string> ranges;
for (const base::Value& page_range : *page_range_list) {
if (page_range.is_int()) {
if (page_range.GetInt() < 0) {
return Status(kInvalidArgument,
"a Number entry in 'pageRanges' must not be less than 0");
}
ranges.push_back(base::NumberToString(page_range.GetInt()));
} else if (page_range.is_string()) {
ranges.push_back(page_range.GetString());
} else {
return Status(kInvalidArgument,
"an entry in 'pageRanges' must be a Number or String");
}
}
*page_ranges = base::JoinString(ranges, ",");
return Status(kOk);
}
// Returns:
// 1. Optional with the default value, if there is no such a key in the
// dictionary.
// 2. Empty optional, if the key is in the dictionary, but value has
// unexpected type.
// 3. Optional with value from dictionary.
template <typename T>
std::optional<T> ParseIfInDictionary(
const base::Value::Dict& dict,
std::string_view key,
T default_value,
std::optional<T> (base::Value::*getterIfType)() const) {
const auto* val = dict.Find(key);
if (!val)
return std::make_optional(default_value);
return (val->*getterIfType)();
}
std::optional<double> ParseDoubleIfInDictionary(const base::Value::Dict& dict,
std::string_view key,
double default_value) {
return ParseIfInDictionary(dict, key, default_value,
&base::Value::GetIfDouble);
}
std::optional<int> ParseIntIfInDictionary(const base::Value::Dict& dict,
std::string_view key,
int default_value) {
return ParseIfInDictionary(dict, key, default_value, &base::Value::GetIfInt);
}
} // namespace
Status ExecuteWindowCommand(const WindowCommand& command,
Session* session,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value) {
Timeout timeout;
WebView* web_view = nullptr;
Status status = session->GetTargetWindow(&web_view);
if (status.IsError())
return status;
status = web_view->HandleReceivedEvents();
if (status.IsError())
return status;
if (web_view->IsDialogOpen()) {
std::string alert_text;
status = web_view->GetDialogMessage(alert_text);
if (status.IsError())
return status;
std::string dialog_type;
status = web_view->GetTypeOfDialog(dialog_type);
if (status.IsError()) {
return status;
}
PromptHandlerConfiguration prompt_handler_configuration;
status = session->unhandled_prompt_behavior.GetConfiguration(
dialog_type, prompt_handler_configuration);
if (status.IsError()) {
return status;
}
if (prompt_handler_configuration.type == PromptHandlerType::kAccept ||
prompt_handler_configuration.type == PromptHandlerType::kDismiss) {
status = web_view->HandleDialog(
prompt_handler_configuration.type == PromptHandlerType::kAccept,
session->prompt_text);
if (status.IsError()) {
return status;
}
}
if (prompt_handler_configuration.notify) {
return Status(kUnexpectedAlertOpen, "{Alert text : " + alert_text + "}");
}
}
Status nav_status(kOk);
for (int attempt = 0; attempt < 3; attempt++) {
if (attempt == 2) {
// Switch to main frame and retry command if subframe no longer exists.
session->SwitchToTopFrame();
}
nav_status = web_view->WaitForPendingNavigations(
session->GetCurrentFrameId(),
Timeout(session->page_load_timeout, &timeout), true);
// Impossible errors:
// * kNoSuchExecutionContext as WebView::WaitForPendingNavigations never
// returns it.
// Some possible errors:
// * kTimeout. The pending navigation has taken too long, the whole command
// has timed out.
// * kDisconnected. The connection was lost. There is no point to retry.
if (nav_status.IsError()) {
return nav_status;
}
status = command.Run(session, web_view, params, value, &timeout);
if (kNavigationHints.contains(status.code())) {
// Navigation was detected while running the command. Retry.
continue;
}
if (status.code() == kTimeout) {
// If the command timed out, let WaitForPendingNavigations cancel
// the navigation if there is any.
continue;
} else if (status.code() == kUnknownError && web_view->IsNonBlocking() &&
status.message().find(kTargetClosedMessage) !=
std::string::npos) {
// When pageload strategy is None, new navigation can occur during
// execution of a command. Retry the command.
continue;
} else if (status.code() == kDisconnected ||
status.code() == kTargetDetached) {
// Some commands, like clicking a button or link which closes the window,
// may result in a kDisconnected or kTargetDetached error code.
// |web_view| may be invalid at this point.
return status;
} else if (status.IsError()) {
// If the command failed while a new page or frame started loading, retry
// the command after the pending navigation has completed.
bool is_pending = false;
nav_status = web_view->IsPendingNavigation(&timeout, &is_pending);
if (nav_status.IsError())
return nav_status;
else if (is_pending)
continue;
}
break;
}
nav_status = web_view->WaitForPendingNavigations(
session->GetCurrentFrameId(),
Timeout(session->page_load_timeout, &timeout), true);
if (status.IsOk() && nav_status.IsError() &&
nav_status.code() != kUnexpectedAlertOpen) {
return nav_status;
}
if (status.code() == kUnexpectedAlertOpen) {
return Status(kOk);
}
if (status.code() == kUnexpectedAlertOpen_Keep) {
return Status(kUnexpectedAlertOpen, status.message());
}
if (kNavigationHints.contains(status.code())) {
// The command has failed to run due to pending navigation three times.
// Returning a "timeout" error because infinite retries would, presumably,
// never end.
return Status{kTimeout, status};
}
return status;
}
Status ExecuteGet(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
timeout->SetDuration(session->page_load_timeout);
const std::string* url = params.FindString("url");
if (!url)
return Status(kInvalidArgument, "'url' must be a string");
Status status = web_view->Load(*url, timeout);
if (status.IsError())
return status;
session->SwitchToTopFrame();
return Status(kOk);
}
Status ExecuteExecuteScript(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
const std::string* maybe_script = params.FindString("script");
if (!maybe_script)
return Status(kInvalidArgument, "'script' must be a string");
std::string script = *maybe_script;
if (script == ":takeHeapSnapshot")
return web_view->TakeHeapSnapshot(value);
if (script == ":startProfile")
return web_view->StartProfile();
if (script == ":endProfile")
return web_view->EndProfile(value);
const base::Value::List* args = params.FindList("args");
if (args == nullptr) {
return Status(kInvalidArgument, "'args' must be a list");
}
// Need to support line oriented comment
if (script.find("//") != std::string::npos)
script = script + "\n";
Status status =
web_view->CallUserSyncScript(session->GetCurrentFrameId(), script, *args,
session->script_timeout, value);
switch (status.code()) {
case kTimeout:
// If the target has been detached the script will never return
case kTargetDetached:
return Status(kScriptTimeout);
default:
return status;
}
}
Status ExecuteExecuteAsyncScript(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
const std::string* maybe_script = params.FindString("script");
if (!maybe_script)
return Status(kInvalidArgument, "'script' must be a string");
std::string script = *maybe_script;
const base::Value::List* args = params.FindList("args");
if (args == nullptr) {
return Status(kInvalidArgument, "'args' must be a list");
}
// Need to support line oriented comment
if (script.find("//") != std::string::npos)
script = script + "\n";
Status status = web_view->CallUserAsyncFunction(
session->GetCurrentFrameId(), "async function(){" + script + "}", *args,
session->script_timeout, value);
switch (status.code()) {
case kTimeout:
// Navigation has happened during script execution. Further wait would lead
// to timeout.
case kAbortedByNavigation:
return Status(kScriptTimeout);
default:
return status;
}
}
Status ExecuteNewWindow(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
std::string type;
// "type" can either be None or a string.
auto* type_param = params.Find("type");
if (!type_param || type_param->is_none()) {
// Nothing more to do
} else if (type_param->is_string()) {
type = type_param->GetString();
} else {
return Status(kInvalidArgument, "missing or invalid 'type'");
}
// By default, creates new tab.
Chrome::WindowType window_type = (type == "window")
? Chrome::WindowType::kWindow
: Chrome::WindowType::kTab;
std::string handle;
Status status = session->chrome->NewWindow(session->window, window_type, true,
session->w3c_compliant, &handle);
if (status.IsError())
return status;
base::Value::Dict dict;
dict.Set("handle", handle);
dict.Set("type",
(window_type == Chrome::WindowType::kWindow) ? "window" : "tab");
auto results = std::make_unique<base::Value>(std::move(dict));
*value = std::move(results);
return Status(kOk);
}
Status ExecuteSwitchToFrame(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
const base::Value* id = params.Find("id");
if (id == nullptr)
return Status(kInvalidArgument, "missing 'id'");
if (id->is_none()) {
session->SwitchToTopFrame();
return Status(kOk);
}
std::string script;
base::Value::List args;
const base::Value::Dict* id_dict = id->GetIfDict();
if (id_dict) {
const std::string* element_id =
id_dict->FindString(GetElementKey(session->w3c_compliant));
if (!element_id)
return Status(kInvalidArgument, "missing 'ELEMENT'");
bool is_displayed = false;
Status status =
IsElementDisplayed(session, web_view, *element_id, true, &is_displayed);
if (status.IsError())
return status;
script = "function(elem) { return elem; }";
args.Append(id_dict->Clone());
} else {
script =
"function(xpath) {"
" return document.evaluate(xpath, document, null, "
" XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;"
"}";
std::string xpath = "(/html/body//iframe|/html/frameset//frame)";
if (id->is_string()) {
std::string id_string = id->GetString();
if (session->w3c_compliant)
return Status(kInvalidArgument, "'id' can not be string");
else
xpath += base::StringPrintf(
"[@name=\"%s\" or @id=\"%s\"]", id_string.c_str(), id_string.c_str());
} else if (id->is_int()) {
int id_int = id->GetInt();
const int max_range = 65535; // 2^16 - 1
if (id_int < 0 || id_int > max_range)
return Status(kInvalidArgument, "'id' out of range");
else
xpath += base::StringPrintf("[%d]", id_int + 1);
} else {
return Status(kInvalidArgument, "invalid 'id'");
}
args.Append(xpath);
}
std::string frame;
Status status = web_view->GetFrameByFunction(
session->GetCurrentFrameId(), script, args, &frame);
if (status.IsError())
return status;
std::unique_ptr<base::Value> result;
status = web_view->CallFunction(
session->GetCurrentFrameId(), script, args, &result);
if (status.IsError())
return status;
const base::Value::Dict* element = result->GetIfDict();
if (!element)
return Status(kUnknownError, "fail to locate the sub frame element");
std::string chrome_driver_id = GenerateId();
const char kSetFrameIdentifier[] =
"function(frame, id) {"
" frame.setAttribute('cd_frame_id_', id);"
"}";
base::Value::List new_args;
new_args.Append(element->Clone());
new_args.Append(chrome_driver_id);
result.reset();
status = web_view->CallFunction(
session->GetCurrentFrameId(), kSetFrameIdentifier, new_args, &result);
if (status.IsError())
return status;
session->SwitchToSubFrame(frame, chrome_driver_id);
return Status(kOk);
}
Status ExecuteSwitchToParentFrame(Session* session,
WebView* web_view,
const base::Value::Dict& params,
std::unique_ptr<base::Value>* value,
Timeout* timeout) {
session->SwitchToParentFrame();