summaryrefslogtreecommitdiff
path: root/Userland/Services/WebContent/WebDriverConnection.cpp
blob: bd32b97ea12346f02c33a9754933dcf4e5a5c229 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
/*
 * Copyright (c) 2022, Florent Castelli <florent.castelli@gmail.com>
 * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
 * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
 * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
 * Copyright (c) 2022-2023, Tim Flynn <trflynn89@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
#include <AK/Time.h>
#include <AK/Vector.h>
#include <LibJS/Runtime/JSONObject.h>
#include <LibJS/Runtime/Value.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/StyleProperties.h>
#include <LibWeb/CSS/StyleValue.h>
#include <LibWeb/Cookie/Cookie.h>
#include <LibWeb/Cookie/ParsedCookie.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/NodeFilter.h>
#include <LibWeb/DOM/NodeIterator.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/Geometry/DOMRect.h>
#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/Focus.h>
#include <LibWeb/HTML/FormAssociatedElement.h>
#include <LibWeb/HTML/HTMLDataListElement.h>
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLOptGroupElement.h>
#include <LibWeb/HTML/HTMLOptionElement.h>
#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/Timer.h>
#include <LibWeb/UIEvents/MouseEvent.h>
#include <LibWeb/WebDriver/ExecuteScript.h>
#include <LibWeb/WebDriver/Screenshot.h>
#include <WebContent/WebDriverConnection.h>

namespace WebContent {

// https://w3c.github.io/webdriver/#dfn-serialized-cookie
static JsonValue serialize_cookie(Web::Cookie::Cookie const& cookie)
{
    JsonObject serialized_cookie;
    serialized_cookie.set("name"sv, cookie.name);
    serialized_cookie.set("value"sv, cookie.value);
    serialized_cookie.set("path"sv, cookie.path);
    serialized_cookie.set("domain"sv, cookie.domain);
    serialized_cookie.set("secure"sv, cookie.secure);
    serialized_cookie.set("httpOnly"sv, cookie.http_only);
    serialized_cookie.set("expiry"sv, cookie.expiry_time.to_seconds());
    serialized_cookie.set("sameSite"sv, Web::Cookie::same_site_to_string(cookie.same_site));

    return serialized_cookie;
}

static JsonValue serialize_rect(Gfx::IntRect const& rect)
{
    JsonObject serialized_rect = {};
    serialized_rect.set("x", rect.x());
    serialized_rect.set("y", rect.y());
    serialized_rect.set("width", rect.width());
    serialized_rect.set("height", rect.height());

    return serialized_rect;
}

static Gfx::IntRect compute_window_rect(Web::Page const& page)
{
    return {
        page.window_position().x(),
        page.window_position().y(),
        page.window_size().width(),
        page.window_size().height()
    };
}

// https://w3c.github.io/webdriver/#dfn-calculate-the-absolute-position
static Gfx::IntPoint calculate_absolute_position_of_element(Web::Page const& page, JS::NonnullGCPtr<Web::Geometry::DOMRect> rect)
{
    // 1. Let rect be the value returned by calling getBoundingClientRect().

    // 2. Let window be the associated window of current top-level browsing context.
    auto const* window = page.top_level_browsing_context().active_window();

    // 3. Let x be (scrollX of window + rect’s x coordinate).
    auto x = (window ? static_cast<int>(window->scroll_x()) : 0) + static_cast<int>(rect->x());

    // 4. Let y be (scrollY of window + rect’s y coordinate).
    auto y = (window ? static_cast<int>(window->scroll_y()) : 0) + static_cast<int>(rect->y());

    // 5. Return a pair of (x, y).
    return { x, y };
}

static Gfx::IntRect calculate_absolute_rect_of_element(Web::Page const& page, Web::DOM::Element const& element)
{
    auto bounding_rect = element.get_bounding_client_rect();
    auto coordinates = calculate_absolute_position_of_element(page, bounding_rect);

    return {
        coordinates.x(),
        coordinates.y(),
        static_cast<int>(bounding_rect->width()),
        static_cast<int>(bounding_rect->height())
    };
}

// https://w3c.github.io/webdriver/#dfn-get-or-create-a-web-element-reference
static DeprecatedString get_or_create_a_web_element_reference(Web::DOM::Node const& element)
{
    // FIXME: 1. For each known element of the current browsing context’s list of known elements:
    // FIXME:     1. If known element equals element, return success with known element’s web element reference.
    // FIXME: 2. Add element to the list of known elements of the current browsing context.
    // FIXME: 3. Return success with the element’s web element reference.

    return DeprecatedString::number(element.id());
}

// https://w3c.github.io/webdriver/#dfn-web-element-reference-object
static JsonObject web_element_reference_object(Web::DOM::Node const& element)
{
    // https://w3c.github.io/webdriver/#dfn-web-element-identifier
    static DeprecatedString const web_element_identifier = "element-6066-11e4-a52e-4f735466cecf"sv;

    // 1. Let identifier be the web element identifier.
    auto identifier = web_element_identifier;

    // 2. Let reference be the result of get or create a web element reference given element.
    auto reference = get_or_create_a_web_element_reference(element);

    // 3. Return a JSON Object initialized with a property with name identifier and value reference.
    JsonObject object;
    object.set("name"sv, identifier);
    object.set("value"sv, reference);
    return object;
}

// https://w3c.github.io/webdriver/#dfn-get-a-known-connected-element
static ErrorOr<Web::DOM::Element*, Web::WebDriver::Error> get_known_connected_element(StringView element_id)
{
    // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference().
    //       For now the element is only represented by its ID.
    auto element = element_id.to_int();
    if (!element.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an integer");

    auto* node = Web::DOM::Node::from_id(*element);

    if (!node || !node->is_element())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, DeprecatedString::formatted("Could not find element with ID: {}", element_id));

    return static_cast<Web::DOM::Element*>(node);
}

// https://w3c.github.io/webdriver/#dfn-get-or-create-a-shadow-root-reference
static DeprecatedString get_or_create_a_shadow_root_reference(Web::DOM::ShadowRoot const& shadow_root)
{
    // FIXME: 1. For each known shadow root of the current browsing context’s list of known shadow roots:
    // FIXME:     1. If known shadow root equals shadow root, return success with known shadow root’s shadow root reference.
    // FIXME: 2. Add shadow to the list of known shadow roots of the current browsing context.
    // FIXME: 3. Return success with the shadow’s shadow root reference.

    return DeprecatedString::number(shadow_root.id());
}

// https://w3c.github.io/webdriver/#dfn-shadow-root-reference-object
static JsonObject shadow_root_reference_object(Web::DOM::ShadowRoot const& shadow_root)
{
    // https://w3c.github.io/webdriver/#dfn-shadow-root-identifier
    static DeprecatedString const shadow_root_identifier = "shadow-6066-11e4-a52e-4f735466cecf"sv;

    // 1. Let identifier be the shadow root identifier.
    auto identifier = shadow_root_identifier;

    // 2. Let reference be the result of get or create a shadow root reference given shadow root.
    auto reference = get_or_create_a_shadow_root_reference(shadow_root);

    // 3. Return a JSON Object initialized with a property with name identifier and value reference.
    JsonObject object;
    object.set("name"sv, move(identifier));
    object.set("value"sv, move(reference));
    return object;
}

// https://w3c.github.io/webdriver/#dfn-get-a-known-shadow-root
static ErrorOr<Web::DOM::ShadowRoot*, Web::WebDriver::Error> get_known_shadow_root(StringView shadow_id)
{
    // NOTE: The whole concept of "known shadow roots" is not implemented yet. See get_or_create_a_shadow_root_reference().
    //       For now the shadow root is only represented by its ID.
    auto shadow_root = shadow_id.to_int();
    if (!shadow_root.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Shadow ID is not an integer");

    auto* node = Web::DOM::Node::from_id(*shadow_root);

    if (!node || !node->is_shadow_root())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, DeprecatedString::formatted("Could not find shadow root with ID: {}", shadow_id));

    return static_cast<Web::DOM::ShadowRoot*>(node);
}

// https://w3c.github.io/webdriver/#dfn-scrolls-into-view
static ErrorOr<void> scroll_element_into_view(Web::DOM::Element& element)
{
    // 1. Let options be the following ScrollIntoViewOptions:
    Web::DOM::ScrollIntoViewOptions options {};
    // Logical scroll position "block"
    //     "end"
    options.block = Web::Bindings::ScrollLogicalPosition::End;
    // Logical scroll position "inline"
    //     "nearest"
    options.inline_ = Web::Bindings::ScrollLogicalPosition::Nearest;

    // 2. Run Function.[[Call]](scrollIntoView, options) with element as the this value.
    TRY(element.scroll_into_view(options));

    return {};
}

template<typename PropertyType = DeprecatedString>
static ErrorOr<PropertyType, Web::WebDriver::Error> get_property(JsonValue const& payload, StringView key)
{
    if (!payload.is_object())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");

    auto property = payload.as_object().get(key);

    if (!property.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("No property called '{}' present", key));

    if constexpr (IsSame<PropertyType, DeprecatedString>) {
        if (!property->is_string())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not a String", key));
        return property->as_string();
    } else if constexpr (IsSame<PropertyType, bool>) {
        if (!property->is_bool())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not a Boolean", key));
        return property->as_bool();
    } else if constexpr (IsSame<PropertyType, u32>) {
        if (!property->is_u32())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not a Number", key));
        return property->as_u32();
    } else if constexpr (IsSame<PropertyType, JsonArray const*>) {
        if (!property->is_array())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not an Array", key));
        return &property->as_array();
    } else if constexpr (IsSame<PropertyType, JsonObject const*>) {
        if (!property->is_object())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not an Object", key));
        return &property->as_object();
    } else {
        static_assert(DependentFalse<PropertyType>, "get_property invoked with unknown property type");
        VERIFY_NOT_REACHED();
    }
}

// https://w3c.github.io/webdriver/#dfn-container
static Optional<Web::DOM::Element&> container_for_element(Web::DOM::Element& element)
{
    auto first_element_reached_by_traversing_the_tree_in_reverse_order = [](Web::DOM::Element& element, auto filter) -> Optional<Web::DOM::Element&> {
        auto node_iterator = element.document().create_node_iterator(element, to_underlying(Web::DOM::NodeFilter::WhatToShow::SHOW_ALL), nullptr);

        auto current_node = node_iterator->previous_node();
        while (current_node.has_value() && current_node.value() != nullptr && current_node.value()->is_element()) {
            if (filter(current_node.value()))
                return static_cast<Web::DOM::Element&>(*current_node.release_value());
        }

        return {};
    };

    // An element’s container is:
    // -> option element in a valid element context
    // -> optgroup element in a valid element context
    // FIXME: Determine if the element is in a valid element context. (https://html.spec.whatwg.org/#concept-element-contexts)
    if (is<Web::HTML::HTMLOptionElement>(element) || is<Web::HTML::HTMLOptGroupElement>(element)) {
        // The element’s element context, which is determined by:
        // 1. Let datalist parent be the first datalist element reached by traversing the tree in reverse order from element, or undefined if the root of the tree is reached.
        auto datalist_parent = first_element_reached_by_traversing_the_tree_in_reverse_order(element, [](auto& node) { return is<Web::HTML::HTMLDataListElement>(*node); });

        // 2. Let select parent be the first select element reached by traversing the tree in reverse order from element, or undefined if the root of the tree is reached.
        auto select_parent = first_element_reached_by_traversing_the_tree_in_reverse_order(element, [](auto& node) { return is<Web::HTML::HTMLSelectElement>(*node); });

        // 3. If datalist parent is undefined, the element context is select parent. Otherwise, the element context is datalist parent.
        if (!datalist_parent.has_value())
            return select_parent;
        return datalist_parent;
    }
    // -> option element in an invalid element context
    else if (is<Web::HTML::HTMLOptionElement>(element)) {
        // The element does not have a container.
        return {};
    }
    // -> Otherwise
    else {
        // The container is the element itself.
        return element;
    }
}

template<typename T>
static bool fire_an_event(DeprecatedString name, Optional<Web::DOM::Element&> target)
{
    // FIXME: This is supposed to call the https://dom.spec.whatwg.org/#concept-event-fire DOM algorithm,
    //        but that doesn't seem to be implemented elsewhere. So, we'll ad-hack it for now. :^)

    if (!target.has_value())
        return false;

    auto event = T::create(target->realm(), name).release_value_but_fixme_should_propagate_errors();
    return target->dispatch_event(event);
}

ErrorOr<NonnullRefPtr<WebDriverConnection>> WebDriverConnection::connect(Web::PageClient& page_client, DeprecatedString const& webdriver_ipc_path)
{
    dbgln_if(WEBDRIVER_DEBUG, "Trying to connect to {}", webdriver_ipc_path);
    auto socket = TRY(Core::LocalSocket::connect(webdriver_ipc_path));

    dbgln_if(WEBDRIVER_DEBUG, "Connected to WebDriver");
    return adopt_nonnull_ref_or_enomem(new (nothrow) WebDriverConnection(move(socket), page_client));
}

WebDriverConnection::WebDriverConnection(NonnullOwnPtr<Core::LocalSocket> socket, Web::PageClient& page_client)
    : IPC::ConnectionToServer<WebDriverClientEndpoint, WebDriverServerEndpoint>(*this, move(socket))
    , m_page_client(page_client)
{
}

// https://w3c.github.io/webdriver/#dfn-close-the-session
void WebDriverConnection::close_session()
{
    // 1. Set the webdriver-active flag to false.
    set_is_webdriver_active(false);

    // 2. An endpoint node must close any top-level browsing contexts associated with the session, without prompting to unload.
    if (!m_page_client.page().top_level_browsing_context().has_been_discarded())
        m_page_client.page().top_level_browsing_context().close();
}

void WebDriverConnection::set_page_load_strategy(Web::WebDriver::PageLoadStrategy const& page_load_strategy)
{
    m_page_load_strategy = page_load_strategy;
}

void WebDriverConnection::set_unhandled_prompt_behavior(Web::WebDriver::UnhandledPromptBehavior const& unhandled_prompt_behavior)
{
    m_unhandled_prompt_behavior = unhandled_prompt_behavior;
}

void WebDriverConnection::set_strict_file_interactability(bool strict_file_interactability)
{
    m_strict_file_interactability = strict_file_interactability;
}

void WebDriverConnection::set_is_webdriver_active(bool is_webdriver_active)
{
    m_page_client.page().set_is_webdriver_active(is_webdriver_active);
}

// 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
Messages::WebDriverClient::GetTimeoutsResponse WebDriverConnection::get_timeouts()
{
    // 1. Let timeouts be the timeouts object for session’s timeouts configuration
    auto timeouts = Web::WebDriver::timeouts_object(m_timeouts_configuration);

    // 2. Return success with data timeouts.
    return timeouts;
}

// 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
Messages::WebDriverClient::SetTimeoutsResponse WebDriverConnection::set_timeouts(JsonValue const& payload)
{
    // 1. Let timeouts be the result of trying to JSON deserialize as a timeouts configuration the request’s parameters.
    auto timeouts = TRY(Web::WebDriver::json_deserialize_as_a_timeouts_configuration(payload));

    // 2. Make the session timeouts the new timeouts.
    m_timeouts_configuration = move(timeouts);

    // 3. Return success with data null.
    return JsonValue {};
}

// 10.1 Navigate To, https://w3c.github.io/webdriver/#navigate-to
Messages::WebDriverClient::NavigateToResponse WebDriverConnection::navigate_to(JsonValue const& payload)
{
    dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::navigate_to {}", payload);

    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Let url be the result of getting the property url from the parameters argument.
    if (!payload.is_object() || !payload.as_object().has_string("url"sv))
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a string `url`"sv);
    URL url(payload.as_object().get_deprecated_string("url"sv).value());

    // FIXME: 3. If url is not an absolute URL or is not an absolute URL with fragment or not a local scheme, return error with error code invalid argument.

    // 4. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 5. Let current URL be the current top-level browsing context’s active document’s URL.
    auto const& current_url = m_page_client.page().top_level_browsing_context().active_document()->url();
    // FIXME: 6. If current URL and url do not have the same absolute URL:
    // FIXME:     a. If timer has not been started, start a timer. If this algorithm has not completed before timer reaches the session’s session page load timeout in milliseconds, return an error with error code timeout.

    // 7. Navigate the current top-level browsing context to url.
    m_page_client.page().load(url);

    // 8. If url is special except for file and current URL and URL do not have the same absolute URL:
    if (url.is_special() && url.scheme() != "file"sv && current_url != url) {
        // a. Try to wait for navigation to complete.
        TRY(wait_for_navigation_to_complete());

        // FIXME: b. Try to run the post-navigation checks.
    }

    // FIXME: 9. Set the current browsing context with the current top-level browsing context.
    // FIXME: 10. If the current top-level browsing context contains a refresh state pragma directive of time 1 second or less, wait until the refresh timeout has elapsed, a new navigate has begun, and return to the first step of this algorithm.

    // 11. Return success with data null.
    return JsonValue {};
}

// 10.2 Get Current URL, https://w3c.github.io/webdriver/#get-current-url
Messages::WebDriverClient::GetCurrentUrlResponse WebDriverConnection::get_current_url()
{
    dbgln_if(WEBDRIVER_DEBUG, "WebDriverConnection::get_current_url");

    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let url be the serialization of the current top-level browsing context’s active document’s document URL.
    auto url = m_page_client.page().top_level_browsing_context().active_document()->url().to_deprecated_string();

    // 4. Return success with data url.
    return url;
}

// 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
Messages::WebDriverClient::BackResponse WebDriverConnection::back()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Traverse the history by a delta –1 for the current browsing context.
    m_page_client.page_did_request_navigate_back();

    // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
    // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user prompts have been handled, return error with error code timeout.

    // 6. Return success with data null.
    return JsonValue {};
}

// 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
Messages::WebDriverClient::ForwardResponse WebDriverConnection::forward()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Traverse the history by a delta 1 for the current browsing context.
    m_page_client.page_did_request_navigate_forward();

    // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
    // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user prompts have been handled, return error with error code timeout.

    // 6. Return success with data null.
    return JsonValue {};
}

// 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
Messages::WebDriverClient::RefreshResponse WebDriverConnection::refresh()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Initiate an overridden reload of the current top-level browsing context’s active document.
    m_page_client.page_did_request_refresh();

    // FIXME: 4. If url is special except for file:
    // FIXME:     1. Try to wait for navigation to complete.
    // FIXME:     2. Try to run the post-navigation checks.
    // FIXME: 5. Set the current browsing context with current top-level browsing context.

    // 6. Return success with data null.
    return JsonValue {};
}

// 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
Messages::WebDriverClient::GetTitleResponse WebDriverConnection::get_title()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.
    auto title = m_page_client.page().top_level_browsing_context().active_document()->title();

    // 4. Return success with data title.
    return title;
}

// 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
Messages::WebDriverClient::CloseWindowResponse WebDriverConnection::close_window()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Close the current top-level browsing context.
    m_page_client.page().top_level_browsing_context().close();
    return JsonValue {};
}

// 11.8.1 Get Window Rect, https://w3c.github.io/webdriver/#dfn-get-window-rect
Messages::WebDriverClient::GetWindowRectResponse WebDriverConnection::get_window_rect()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Return success with data set to the WindowRect object for the current top-level browsing context.
    return serialize_rect(compute_window_rect(m_page_client.page()));
}

// 11.8.2 Set Window Rect, https://w3c.github.io/webdriver/#dfn-set-window-rect
Messages::WebDriverClient::SetWindowRectResponse WebDriverConnection::set_window_rect(JsonValue const& payload)
{
    if (!payload.is_object())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");

    auto const& properties = payload.as_object();

    auto resolve_property = [](auto name, auto const& property, auto min, auto max) -> ErrorOr<Optional<i32>, Web::WebDriver::Error> {
        if (property.is_null())
            return Optional<i32> {};
        if (!property.is_number())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' is not a Number", name));

        auto number = property.template to_number<i64>();

        if (number < min)
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' value {} exceeds the minimum allowed value {}", name, number, min));
        if (number > max)
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Property '{}' value {} exceeds the maximum allowed value {}", name, number, max));

        return static_cast<i32>(number);
    };

    // 1. Let width be the result of getting a property named width from the parameters argument, else let it be null.
    auto width_property = properties.get("width"sv).value_or(JsonValue());

    // 2. Let height be the result of getting a property named height from the parameters argument, else let it be null.
    auto height_property = properties.get("height"sv).value_or(JsonValue());

    // 3. Let x be the result of getting a property named x from the parameters argument, else let it be null.
    auto x_property = properties.get("x"sv).value_or(JsonValue());

    // 4. Let y be the result of getting a property named y from the parameters argument, else let it be null.
    auto y_property = properties.get("y"sv).value_or(JsonValue());

    // 5. If width or height is neither null nor a Number from 0 to 2^31 − 1, return error with error code invalid argument.
    auto width = TRY(resolve_property("width"sv, width_property, 0, NumericLimits<i32>::max()));
    auto height = TRY(resolve_property("height"sv, height_property, 0, NumericLimits<i32>::max()));

    // 6. If x or y is neither null nor a Number from −(2^31) to 2^31 − 1, return error with error code invalid argument.
    auto x = TRY(resolve_property("x"sv, x_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));
    auto y = TRY(resolve_property("y"sv, y_property, NumericLimits<i32>::min(), NumericLimits<i32>::max()));

    // 7. If the remote end does not support the Set Window Rect command for the current top-level browsing context for any reason, return error with error code unsupported operation.

    // 8. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 9. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // FIXME: 10. Fully exit fullscreen.

    // 11. Restore the window.
    restore_the_window();

    Gfx::IntRect window_rect;

    // 11. If width and height are not null:
    if (width.has_value() && height.has_value()) {
        // a. Set the width, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to width.
        // b. Set the height, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to height.
        auto size = m_page_client.page_did_request_resize_window({ *width, *height });
        window_rect.set_size(size);
    } else {
        window_rect.set_size(m_page_client.page().window_size().to_type<int>());
    }

    // 12. If x and y are not null:
    if (x.has_value() && y.has_value()) {
        // a. Run the implementation-specific steps to set the position of the operating system level window containing the current top-level browsing context to the position given by the x and y coordinates.
        auto position = m_page_client.page_did_request_reposition_window({ *x, *y });
        window_rect.set_location(position);
    } else {
        window_rect.set_location(m_page_client.page().window_position().to_type<int>());
    }

    // 14. Return success with data set to the WindowRect object for the current top-level browsing context.
    return serialize_rect(window_rect);
}

// 11.8.3 Maximize Window, https://w3c.github.io/webdriver/#dfn-maximize-window
Messages::WebDriverClient::MaximizeWindowResponse WebDriverConnection::maximize_window()
{
    // 1. If the remote end does not support the Maximize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.

    // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 3. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // FIXME: 4. Fully exit fullscreen.

    // 5. Restore the window.
    restore_the_window();

    // 6. Maximize the window of the current top-level browsing context.
    auto window_rect = maximize_the_window();

    // 7. Return success with data set to the WindowRect object for the current top-level browsing context.
    return serialize_rect(window_rect);
}

// 11.8.4 Minimize Window, https://w3c.github.io/webdriver/#minimize-window
Messages::WebDriverClient::MinimizeWindowResponse WebDriverConnection::minimize_window()
{
    // 1. If the remote end does not support the Minimize Window command for the current top-level browsing context for any reason, return error with error code unsupported operation.

    // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 3. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // FIXME: 4. Fully exit fullscreen.

    // 5. Iconify the window.
    auto window_rect = iconify_the_window();

    // 6. Return success with data set to the WindowRect object for the current top-level browsing context.
    return serialize_rect(window_rect);
}

// 11.8.5 Fullscreen Window, https://w3c.github.io/webdriver/#dfn-fullscreen-window
Messages::WebDriverClient::FullscreenWindowResponse WebDriverConnection::fullscreen_window()
{
    // 1. If the remote end does not support fullscreen return error with error code unsupported operation.

    // 2. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 3. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 4. Restore the window.
    restore_the_window();

    // 5. FIXME: Call fullscreen an element with the current top-level browsing context’s active document’s document element.
    //           As described in https://fullscreen.spec.whatwg.org/#fullscreen-an-element
    //    NOTE: What we do here is basically `requestFullscreen(options)` with options["navigationUI"]="show"
    auto rect = m_page_client.page_did_request_fullscreen_window();

    // 6. Return success with data set to the WindowRect object for the current top-level browsing context.
    return serialize_rect(rect);
}

// 12.3.2 Find Element, https://w3c.github.io/webdriver/#dfn-find-element
Messages::WebDriverClient::FindElementResponse WebDriverConnection::find_element(JsonValue const& payload)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [this]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the current browsing context’s document element.
        auto* start_node = m_page_client.page().top_level_browsing_context().active_document();

        // 8. If start node is null, return error with error code no such element.
        if (!start_node)
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);

        return start_node;
    };

    // 9. Let result be the result of trying to Find with start node, location strategy, and selector.
    auto result = TRY(find(move(start_node_getter), *location_strategy, selector));

    // 10. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
    if (result.is_empty())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);

    return result.take(0);
}

// 12.3.3 Find Elements, https://w3c.github.io/webdriver/#dfn-find-elements
Messages::WebDriverClient::FindElementsResponse WebDriverConnection::find_elements(JsonValue const& payload)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [this]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the current browsing context’s document element.
        auto* start_node = m_page_client.page().top_level_browsing_context().active_document();

        // 8. If start node is null, return error with error code no such element.
        if (!start_node)
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "document element does not exist"sv);

        return start_node;
    };

    // 9. Return the result of trying to Find with start node, location strategy, and selector.
    return TRY(find(move(start_node_getter), *location_strategy, selector));
}

// 12.3.4 Find Element From Element, https://w3c.github.io/webdriver/#dfn-find-element-from-element
Messages::WebDriverClient::FindElementFromElementResponse WebDriverConnection::find_element_from_element(JsonValue const& payload, String const& element_id)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [&]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the result of trying to get a known connected element with url variable element id.
        return TRY(get_known_connected_element(element_id));
    };

    // 8. Let result be the value of trying to Find with start node, location strategy, and selector.
    auto result = TRY(find(move(start_node_getter), *location_strategy, selector));

    // 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
    if (result.is_empty())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);

    return result.take(0);
}

// 12.3.5 Find Elements From Element, https://w3c.github.io/webdriver/#dfn-find-elements-from-element
Messages::WebDriverClient::FindElementsFromElementResponse WebDriverConnection::find_elements_from_element(JsonValue const& payload, String const& element_id)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [&]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the result of trying to get a known connected element with url variable element id.
        return TRY(get_known_connected_element(element_id));
    };

    // 8. Return the result of trying to Find with start node, location strategy, and selector.
    return TRY(find(move(start_node_getter), *location_strategy, selector));
}

// 12.3.6 Find Element From Shadow Root, https://w3c.github.io/webdriver/#find-element-from-shadow-root
Messages::WebDriverClient::FindElementFromShadowRootResponse WebDriverConnection::find_element_from_shadow_root(JsonValue const& payload, String const& shadow_id)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [&]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the result of trying to get a known shadow root with url variable shadow id.
        return TRY(get_known_shadow_root(shadow_id));
    };

    // 8. Let result be the value of trying to Find with start node, location strategy, and selector.
    auto result = TRY(find(move(start_node_getter), *location_strategy, selector));

    // 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.
    if (result.is_empty())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The requested element does not exist"sv);

    return result.take(0);
}

// 12.3.7 Find Elements From Shadow Root, https://w3c.github.io/webdriver/#find-elements-from-shadow-root
Messages::WebDriverClient::FindElementsFromShadowRootResponse WebDriverConnection::find_elements_from_shadow_root(JsonValue const& payload, String const& shadow_id)
{
    // 1. Let location strategy be the result of getting a property called "using".
    auto location_strategy_string = TRY(get_property(payload, "using"sv));
    auto location_strategy = Web::WebDriver::location_strategy_from_string(location_strategy_string);

    // 2. If location strategy is not present as a keyword in the table of location strategies, return error with error code invalid argument.
    if (!location_strategy.has_value())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, DeprecatedString::formatted("Location strategy '{}' is invalid", location_strategy_string));

    // 3. Let selector be the result of getting a property called "value".
    // 4. If selector is undefined, return error with error code invalid argument.
    auto selector = TRY(get_property(payload, "value"sv));

    // 5. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 6. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto start_node_getter = [&]() -> StartNodeGetter::ReturnType {
        // 7. Let start node be the result of trying to get a known shadow root with url variable shadow id.
        return TRY(get_known_shadow_root(shadow_id));
    };

    // 8. Return the result of trying to Find with start node, location strategy, and selector.
    return TRY(find(move(start_node_getter), *location_strategy, selector));
}

// 12.3.8 Get Active Element, https://w3c.github.io/webdriver/#get-active-element
Messages::WebDriverClient::GetActiveElementResponse WebDriverConnection::get_active_element()
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let active element be the active element of the current browsing context’s document element.
    auto* active_element = m_page_client.page().top_level_browsing_context().active_document()->active_element();

    // 4. If active element is a non-null element, return success with data set to web element reference object for active element.
    //    Otherwise, return error with error code no such element.
    if (active_element)
        return DeprecatedString::number(active_element->id());

    return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The current document does not have an active element"sv);
}

// 12.3.9 Get Element Shadow Root, https://w3c.github.io/webdriver/#get-element-shadow-root
Messages::WebDriverClient::GetElementShadowRootResponse WebDriverConnection::get_element_shadow_root(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let shadow root be element's shadow root.
    auto* shadow_root = element->shadow_root_internal();

    // 5. If shadow root is null, return error with error code no such shadow root.
    if (!shadow_root)
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchShadowRoot, DeprecatedString::formatted("Element with ID '{}' does not have a shadow root", element_id));

    // 6. Let serialized be the shadow root reference object for shadow root.
    auto serialized = shadow_root_reference_object(*shadow_root);

    // 7. Return success with data serialized.
    return serialized;
}

// 12.4.1 Is Element Selected, https://w3c.github.io/webdriver/#dfn-is-element-selected
Messages::WebDriverClient::IsElementSelectedResponse WebDriverConnection::is_element_selected(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let selected be the value corresponding to the first matching statement:
    bool selected = false;

    // element is an input element with a type attribute in the Checkbox- or Radio Button state
    if (is<Web::HTML::HTMLInputElement>(*element)) {
        // -> The result of element’s checkedness.
        auto& input = static_cast<Web::HTML::HTMLInputElement&>(*element);
        using enum Web::HTML::HTMLInputElement::TypeAttributeState;

        if (input.type_state() == Checkbox || input.type_state() == RadioButton)
            selected = input.checked();
    }
    // element is an option element
    else if (is<Web::HTML::HTMLOptionElement>(*element)) {
        // -> The result of element’s selectedness.
        selected = static_cast<Web::HTML::HTMLOptionElement&>(*element).selected();
    }
    // Otherwise
    //   -> False.

    // 5. Return success with data selected.
    return selected;
}

// 12.4.2 Get Element Attribute, https://w3c.github.io/webdriver/#dfn-get-element-attribute
Messages::WebDriverClient::GetElementAttributeResponse WebDriverConnection::get_element_attribute(String const& element_id, String const& name)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let result be the result of the first matching condition:
    Optional<DeprecatedString> result;

    auto deprecated_name = name.to_deprecated_string();

    // -> If name is a boolean attribute
    if (Web::HTML::is_boolean_attribute(deprecated_name)) {
        // "true" (string) if the element has the attribute, otherwise null.
        if (element->has_attribute(deprecated_name))
            result = "true"sv;
    }
    // -> Otherwise
    else {
        // The result of getting an attribute by name name.
        result = element->get_attribute(deprecated_name);
    }

    // 5. Return success with data result.
    if (result.has_value())
        return result.release_value();
    return JsonValue {};
}

// 12.4.3 Get Element Property, https://w3c.github.io/webdriver/#dfn-get-element-property
Messages::WebDriverClient::GetElementPropertyResponse WebDriverConnection::get_element_property(String const& element_id, String const& name)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    Optional<DeprecatedString> result;

    // 4. Let property be the result of calling the Object.[[GetProperty]](name) on element.
    if (auto property_or_error = element->get(name.to_deprecated_string()); !property_or_error.is_throw_completion()) {
        auto property = property_or_error.release_value();

        // 5. Let result be the value of property if not undefined, or null.
        if (!property.is_undefined()) {
            if (auto string_or_error = property.to_deprecated_string(element->vm()); !string_or_error.is_error())
                result = string_or_error.release_value();
        }
    }

    // 6. Return success with data result.
    if (result.has_value())
        return result.release_value();
    return JsonValue {};
}

// 12.4.4 Get Element CSS Value, https://w3c.github.io/webdriver/#dfn-get-element-css-value
Messages::WebDriverClient::GetElementCssValueResponse WebDriverConnection::get_element_css_value(String const& element_id, String const& name)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let computed value be the result of the first matching condition:
    DeprecatedString computed_value;

    // -> current browsing context’s active document’s type is not "xml"
    if (!m_page_client.page().top_level_browsing_context().active_document()->is_xml_document()) {
        // computed value of parameter property name from element’s style declarations. property name is obtained from url variables.
        auto property = Web::CSS::property_id_from_string(name);

        if (auto* computed_values = element->computed_css_values())
            computed_value = computed_values->property(property)->to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string();
    }
    // -> Otherwise
    else {
        // "" (empty string)
        computed_value = DeprecatedString::empty();
    }

    // 5. Return success with data computed value.
    return computed_value;
}

// 12.4.5 Get Element Text, https://w3c.github.io/webdriver/#dfn-get-element-text
Messages::WebDriverClient::GetElementTextResponse WebDriverConnection::get_element_text(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let rendered text be the result of performing implementation-specific steps whose result is exactly the same as the result of a Function.[[Call]](null, element) with bot.dom.getVisibleText as the this value.
    auto rendered_text = element->text_content();

    // 5. Return success with data rendered text.
    return rendered_text;
}

// 12.4.6 Get Element Tag Name, https://w3c.github.io/webdriver/#dfn-get-element-tag-name
Messages::WebDriverClient::GetElementTagNameResponse WebDriverConnection::get_element_tag_name(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let qualified name be the result of getting element’s tagName IDL attribute.
    auto qualified_name = element->tag_name();

    // 5. Return success with data qualified name.
    return qualified_name;
}

// 12.4.7 Get Element Rect, https://w3c.github.io/webdriver/#dfn-get-element-rect
Messages::WebDriverClient::GetElementRectResponse WebDriverConnection::get_element_rect(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Calculate the absolute position of element and let it be coordinates.
    // 5. Let rect be element’s bounding rectangle.
    auto rect = calculate_absolute_rect_of_element(m_page_client.page(), *element);

    // 6. Let body be a new JSON Object initialized with:
    // "x"
    //     The first value of coordinates.
    // "y"
    //     The second value of coordinates.
    // "width"
    //     Value of rect’s width dimension.
    // "height"
    //     Value of rect’s height dimension.
    auto body = serialize_rect(rect);

    // 7. Return success with data body.
    return body;
}

// 12.4.8 Is Element Enabled, https://w3c.github.io/webdriver/#dfn-is-element-enabled
Messages::WebDriverClient::IsElementEnabledResponse WebDriverConnection::is_element_enabled(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let enabled be a boolean initially set to true if the current browsing context’s active document’s type is not "xml".
    // 5. Otherwise, let enabled to false and jump to the last step of this algorithm.
    bool enabled = !m_page_client.page().top_level_browsing_context().active_document()->is_xml_document();

    // 6. Set enabled to false if a form control is disabled.
    if (enabled && is<Web::HTML::FormAssociatedElement>(*element)) {
        auto& form_associated_element = dynamic_cast<Web::HTML::FormAssociatedElement&>(*element);
        enabled = form_associated_element.enabled();
    }

    // 7. Return success with data enabled.
    return enabled;
}

// 12.4.9 Get Computed Role, https://w3c.github.io/webdriver/#dfn-get-computed-role
Messages::WebDriverClient::GetComputedRoleResponse WebDriverConnection::get_computed_role(String const& element_id)
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let role be the result of computing the WAI-ARIA role of element.
    auto role = element->role_or_default();

    // 5. Return success with data role.
    if (role.has_value())
        return Web::ARIA::role_name(*role);
    return ""sv;
}

// 12.4.10 Get Computed Label, https://w3c.github.io/webdriver/#get-computed-label
Messages::WebDriverClient::GetComputedLabelResponse WebDriverConnection::get_computed_label(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Let label be the result of a Accessible Name and Description Computation for the Accessible Name of the element.
    auto label = element->accessible_name(element->document()).release_value_but_fixme_should_propagate_errors();

    // 5. Return success with data label.
    return label.to_deprecated_string();
}

// 12.5.1 Element Click, https://w3c.github.io/webdriver/#element-click
Messages::WebDriverClient::ElementClickResponse WebDriverConnection::element_click(String const& element_id)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known element with element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. If the element is an input element in the file upload state return error with error code invalid argument.
    if (is<Web::HTML::HTMLInputElement>(*element)) {
        // -> The result of element’s checkedness.
        auto& input = static_cast<Web::HTML::HTMLInputElement&>(*element);
        using enum Web::HTML::HTMLInputElement::TypeAttributeState;

        if (input.type_state() == FileUpload)
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Clicking on an input element in the file upload state is not supported"sv);
    }

    // 5. Scroll into view the element’s container.
    auto element_container = container_for_element(*element);
    auto scroll_or_error = scroll_element_into_view(*element_container);
    if (scroll_or_error.is_error())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, scroll_or_error.error().string_literal());

    // FIXME: 6. If element’s container is still not in view, return error with error code element not interactable.

    // FIXME: 7. If element’s container is obscured by another element, return error with error code element click intercepted.

    // 8. Matching on element:
    // -> option element
    if (is<Web::HTML::HTMLOptionElement>(*element)) {
        auto& option_element = static_cast<Web::HTML::HTMLOptionElement&>(*element);

        // 1. Let parent node be the element’s container.
        auto parent_node = element_container;

        // 2. Fire a mouseOver event at parent node.
        fire_an_event<Web::UIEvents::MouseEvent>("mouseOver", parent_node);

        // 3. Fire a mouseMove event at parent node.
        fire_an_event<Web::UIEvents::MouseEvent>("mouseMove", parent_node);

        // 4. Fire a mouseDown event at parent node.
        fire_an_event<Web::UIEvents::MouseEvent>("mouseDown", parent_node);

        // 5. Run the focusing steps on parent node.
        Web::HTML::run_focusing_steps(parent_node.has_value() ? &*parent_node : nullptr);

        // 6. If element is not disabled:
        if (!option_element.is_actually_disabled()) {
            // 1. Fire an input event at parent node.
            fire_an_event<Web::DOM::Event>("input", parent_node);

            // 2. Let previous selectedness be equal to element selectedness.
            auto previous_selectedness = option_element.selected();

            // 3. If element’s container has the multiple attribute, toggle the element’s selectedness state
            //    by setting it to the opposite value of its current selectedness.
            if (parent_node.has_value() && parent_node->has_attribute("multiple")) {
                option_element.set_selected(!option_element.selected());
            }
            //    Otherwise, set the element’s selectedness state to true.
            else {
                option_element.set_selected(true);
            }

            // 4. If previous selectedness is false, fire a change event at parent node.
            if (!previous_selectedness) {
                fire_an_event<Web::DOM::Event>("change", parent_node);
            }
        }
        // 7. Fire a mouseUp event at parent node.
        fire_an_event<Web::UIEvents::MouseEvent>("mouseUp", parent_node);

        // 8. Fire a click event at parent node.
        fire_an_event<Web::UIEvents::MouseEvent>("click", parent_node);
    }
    // -> Otherwise
    else {
        // FIXME: 1. Let input state be the result of get the input state given current session and current top-level browsing context.

        // FIXME: 2. Let actions options be a new actions options with the is element origin steps set to represents a web element, and the get element origin steps set to get a WebElement origin.

        // FIXME: 3. Let input id be a the result of generating a UUID.

        // FIXME: 4. Let source be the result of create an input source with input state, and "pointer".

        // FIXME: 5. Add an input source with input state, input id and source.

        // FIXME: 6. Let click point be the element’s in-view center point.

        // FIXME: 7. Let pointer move action be an action object constructed with arguments input id, "pointer", and "pointerMove".

        // FIXME: 8. Set a property x to 0 on pointer move action.

        // FIXME: 9. Set a property y to 0 on pointer move action.

        // FIXME: 10. Set a property origin to element on pointer move action.

        // FIXME: 11. Let pointer down action be an action object constructed with arguments input id, "pointer", and "pointerDown".

        // FIXME: 12. Set a property button to 0 on pointer down action.

        // FIXME: 13. Let pointer up action be an action object constructed with arguments input id, "mouse", and "pointerUp" as arguments.

        // FIXME: 14. Set a property button to 0 on pointer up action.

        // FIXME: 15. Let actions be the list «pointer move action, pointer down action, pointer move action».

        // FIXME: 16. Dispatch a list of actions with input state, actions, current browsing context, and actions options.

        // FIXME: 17. Remove an input source with input state and input id.
    }

    // FIXME: 9. Wait until the user agent event loop has spun enough times to process the DOM events generated by the previous step.
    // FIXME: 10. Perform implementation-defined steps to allow any navigations triggered by the click to start.
    // FIXME: 11. Try to wait for navigation to complete.
    // FIXME: 12. Try to run the post-navigation checks.
    // FIXME: 13. Return success with data null.

    return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Click not implemented"sv);
}

// 13.1 Get Page Source, https://w3c.github.io/webdriver/#dfn-get-page-source
Messages::WebDriverClient::GetSourceResponse WebDriverConnection::get_source()
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    auto* document = m_page_client.page().top_level_browsing_context().active_document();
    Optional<DeprecatedString> source;

    // 3. Let source be the result of invoking the fragment serializing algorithm on a fictional node whose only child is the document element providing true for the require well-formed flag. If this causes an exception to be thrown, let source be null.
    if (auto result = document->serialize_fragment(Web::DOMParsing::RequireWellFormed::Yes); !result.is_error())
        source = result.release_value();

    // 4. Let source be the result of serializing to string the current browsing context active document, if source is null.
    if (!source.has_value())
        source = MUST(document->serialize_fragment(Web::DOMParsing::RequireWellFormed::No));

    // 5. Return success with data source.
    return source.release_value();
}

// 13.2.1 Execute Script, https://w3c.github.io/webdriver/#dfn-execute-script
Messages::WebDriverClient::ExecuteScriptResponse WebDriverConnection::execute_script(JsonValue const& payload)
{
    // 1. Let body and arguments be the result of trying to extract the script arguments from a request with argument parameters.
    auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));

    // 2. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 3. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 4., 5.1-5.3.
    auto result = Web::WebDriver::execute_script(m_page_client.page(), body, move(arguments), m_timeouts_configuration.script_timeout);
    dbgln_if(WEBDRIVER_DEBUG, "Executing script returned: {}", result.value);

    switch (result.type) {
    // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
    case Web::WebDriver::ExecuteScriptResultType::Timeout:
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
    // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
    case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
        return move(result.value);
    // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
    case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
    case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result.value));
    }

    VERIFY_NOT_REACHED();
}

// 13.2.2 Execute Async Script, https://w3c.github.io/webdriver/#dfn-execute-async-script
Messages::WebDriverClient::ExecuteAsyncScriptResponse WebDriverConnection::execute_async_script(JsonValue const& payload)
{
    // 1. Let body and arguments by the result of trying to extract the script arguments from a request with argument parameters.
    auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));

    // 2. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 3. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 4., 5.1-5.11.
    auto result = Web::WebDriver::execute_async_script(m_page_client.page(), body, move(arguments), m_timeouts_configuration.script_timeout);
    dbgln_if(WEBDRIVER_DEBUG, "Executing async script returned: {}", result.value);

    switch (result.type) {
    // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
    case Web::WebDriver::ExecuteScriptResultType::Timeout:
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
    // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
    case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
        return move(result.value);
    // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
    case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
    case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result.value));
    }

    VERIFY_NOT_REACHED();
}

// 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
Messages::WebDriverClient::GetAllCookiesResponse WebDriverConnection::get_all_cookies()
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let cookies be a new JSON List.
    JsonArray cookies;

    // 4. For each cookie in all associated cookies of the current browsing context’s active document:
    auto* document = m_page_client.page().top_level_browsing_context().active_document();

    for (auto const& cookie : m_page_client.page_did_request_all_cookies(document->url())) {
        // 1. Let serialized cookie be the result of serializing cookie.
        auto serialized_cookie = serialize_cookie(cookie);

        // 2. Append serialized cookie to cookies
        cookies.append(move(serialized_cookie));
    }

    // 5. Return success with data cookies.
    return cookies;
}

// 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
Messages::WebDriverClient::GetNamedCookieResponse WebDriverConnection::get_named_cookie(String const& name)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the current browsing context’s active document, return success with the serialized cookie as data.
    auto* document = m_page_client.page().top_level_browsing_context().active_document();

    if (auto cookie = m_page_client.page_did_request_named_cookie(document->url(), name.to_deprecated_string()); cookie.has_value()) {
        auto serialized_cookie = serialize_cookie(*cookie);
        return serialized_cookie;
    }

    // 4. Otherwise, return error with error code no such cookie.
    return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, DeprecatedString::formatted("Cookie '{}' not found", name));
}

// 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
Messages::WebDriverClient::AddCookieResponse WebDriverConnection::add_cookie(JsonValue const& payload)
{
    // 1. Let data be the result of getting a property named cookie from the parameters argument.
    auto const& data = *TRY(get_property<JsonObject const*>(payload, "cookie"sv));

    // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion, return error with error code invalid argument.
    // NOTE: This validation is performed in subsequent steps.

    // 3. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 4. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object, return error with error code invalid cookie domain.

    // 6. If cookie name or cookie value is null, cookie domain is not equal to the current browsing context’s active document’s domain, cookie secure only or cookie HTTP only are not boolean types, or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer, return error with error code invalid argument.
    // NOTE: This validation is either performed in subsequent steps, or is performed by the CookieJar (namely domain matching).

    // 7. Create a cookie in the cookie store associated with the active document’s address using cookie name name, cookie value value, and an attribute-value list of the following cookie concepts listed in the table for cookie conversion from data:
    Web::Cookie::ParsedCookie cookie {};
    cookie.name = TRY(get_property(data, "name"sv));
    cookie.value = TRY(get_property(data, "value"sv));

    // Cookie path
    //     The value if the entry exists, otherwise "/".
    if (data.has("path"sv))
        cookie.path = TRY(get_property(data, "path"sv));
    else
        cookie.path = "/";

    // Cookie domain
    //     The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
    // NOTE: The otherwise case is handled by the CookieJar
    if (data.has("domain"sv))
        cookie.domain = TRY(get_property(data, "domain"sv));

    // Cookie secure only
    //     The value if the entry exists, otherwise false.
    if (data.has("secure"sv))
        cookie.secure_attribute_present = TRY(get_property<bool>(data, "secure"sv));

    // Cookie HTTP only
    //     The value if the entry exists, otherwise false.
    if (data.has("httpOnly"sv))
        cookie.http_only_attribute_present = TRY(get_property<bool>(data, "httpOnly"sv));

    // Cookie expiry time
    //     The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
    if (data.has("expiry"sv)) {
        // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
        auto expiry = TRY(get_property<u32>(data, "expiry"sv));
        cookie.expiry_time_from_expires_attribute = Time::from_seconds(expiry);
    }

    // Cookie same site
    //     The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
    if (data.has("sameSite"sv)) {
        auto same_site = TRY(get_property(data, "sameSite"sv));
        cookie.same_site_attribute = Web::Cookie::same_site_from_string(same_site);
    }

    auto* document = m_page_client.page().top_level_browsing_context().active_document();
    m_page_client.page_did_set_cookie(document->url(), cookie, Web::Cookie::Source::Http);

    // If there is an error during this step, return error with error code unable to set cookie.
    // NOTE: This probably should only apply to the actual setting of the cookie in the Browser, which cannot fail in our case.

    // 8. Return success with data null.
    return JsonValue {};
}

// 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
Messages::WebDriverClient::DeleteCookieResponse WebDriverConnection::delete_cookie(String const& name)
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Delete cookies using the url variable name parameter as the filter argument.
    delete_cookies(name);

    // 4. Return success with data null.
    return JsonValue {};
}

// 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
Messages::WebDriverClient::DeleteAllCookiesResponse WebDriverConnection::delete_all_cookies()
{
    // 1. If the current browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts, and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Delete cookies, giving no filtering argument.
    delete_cookies();

    // 4. Return success with data null.
    return JsonValue {};
}

// 16.1 Dismiss Alert, https://w3c.github.io/webdriver/#dismiss-alert
Messages::WebDriverClient::DismissAlertResponse WebDriverConnection::dismiss_alert()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. If there is no current user prompt, return error with error code no such alert.
    if (!m_page_client.page().has_pending_dialog())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);

    // 3. Dismiss the current user prompt.
    m_page_client.page().dismiss_dialog();

    // 4. Return success with data null.
    return JsonValue {};
}

// 16.2 Accept Alert, https://w3c.github.io/webdriver/#accept-alert
Messages::WebDriverClient::AcceptAlertResponse WebDriverConnection::accept_alert()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. If there is no current user prompt, return error with error code no such alert.
    if (!m_page_client.page().has_pending_dialog())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);

    // 3. Accept the current user prompt.
    m_page_client.page().accept_dialog();

    // 4. Return success with data null.
    return JsonValue {};
}

// 16.3 Get Alert Text, https://w3c.github.io/webdriver/#get-alert-text
Messages::WebDriverClient::GetAlertTextResponse WebDriverConnection::get_alert_text()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. If there is no current user prompt, return error with error code no such alert.
    if (!m_page_client.page().has_pending_dialog())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);

    // 3. Let message be the text message associated with the current user prompt, or otherwise be null.
    auto const& message = m_page_client.page().pending_dialog_text();

    // 4. Return success with data message.
    if (message.has_value())
        return message->to_deprecated_string();
    return JsonValue {};
}

// 16.4 Send Alert Text, https://w3c.github.io/webdriver/#send-alert-text
Messages::WebDriverClient::SendAlertTextResponse WebDriverConnection::send_alert_text(JsonValue const& payload)
{
    // 1. Let text be the result of getting the property "text" from parameters.
    // 2. If text is not a String, return error with error code invalid argument.
    auto text = TRY(get_property(payload, "text"sv));

    // 3. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 4. If there is no current user prompt, return error with error code no such alert.
    if (!m_page_client.page().has_pending_dialog())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);

    // 5. Run the substeps of the first matching current user prompt:
    switch (m_page_client.page().pending_dialog()) {
    // -> alert
    // -> confirm
    case Web::Page::PendingDialog::Alert:
    case Web::Page::PendingDialog::Confirm:
        // Return error with error code element not interactable.
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ElementNotInteractable, "Only prompt dialogs may receive text"sv);

    // -> prompt
    case Web::Page::PendingDialog::Prompt:
        // Do nothing.
        break;

    // -> Otherwise
    default:
        // Return error with error code unsupported operation.
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Unknown dialog type"sv);
    }

    // 6. Perform user agent dependent steps to set the value of current user prompt’s text field to text.
    m_page_client.page_did_request_set_prompt_text(TRY(String::from_deprecated_string(text)));

    // 7. Return success with data null.
    return JsonValue {};
}

// 17.1 Take Screenshot, https://w3c.github.io/webdriver/#take-screenshot
Messages::WebDriverClient::TakeScreenshotResponse WebDriverConnection::take_screenshot()
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. When the user agent is next to run the animation frame callbacks:
    //     a. Let root rect be the current top-level browsing context’s document element’s rectangle.
    //     b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given root rect as an argument.
    //     c. Let canvas be a canvas element of screenshot result’s data.
    //     d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
    //     e. Let encoded string be encoding result’s data.
    auto* document = m_page_client.page().top_level_browsing_context().active_document();
    auto root_rect = calculate_absolute_rect_of_element(m_page_client.page(), *document->document_element());

    auto encoded_string = TRY(Web::WebDriver::capture_element_screenshot(
        [&](auto const& rect, auto& bitmap) { m_page_client.paint(rect.template to_type<Web::DevicePixels>(), bitmap); },
        m_page_client.page(),
        *document->document_element(),
        root_rect));

    // 3. Return success with data encoded string.
    return encoded_string;
}

// 17.2 Take Element Screenshot, https://w3c.github.io/webdriver/#dfn-take-element-screenshot
Messages::WebDriverClient::TakeElementScreenshotResponse WebDriverConnection::take_element_screenshot(String const& element_id)
{
    // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
    TRY(ensure_open_top_level_browsing_context());

    // 2. Handle any user prompts and return its value if it is an error.
    TRY(handle_any_user_prompts());

    // 3. Let element be the result of trying to get a known connected element with url variable element id.
    auto* element = TRY(get_known_connected_element(element_id));

    // 4. Scroll into view the element.
    (void)scroll_element_into_view(*element);

    // 5. When the user agent is next to run the animation frame callbacks:
    //     a. Let element rect be element’s rectangle.
    //     b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given element rect as an argument.
    //     c. Let canvas be a canvas element of screenshot result’s data.
    //     d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
    //     e. Let encoded string be encoding result’s data.
    auto element_rect = calculate_absolute_rect_of_element(m_page_client.page(), *element);

    auto encoded_string = TRY(Web::WebDriver::capture_element_screenshot(
        [&](auto const& rect, auto& bitmap) { m_page_client.paint(rect.template to_type<Web::DevicePixels>(), bitmap); },
        m_page_client.page(),
        *element,
        element_rect));

    // 6. Return success with data encoded string.
    return encoded_string;
}

// 18.1 Print Page, https://w3c.github.io/webdriver/#dfn-print-page
Messages::WebDriverClient::PrintPageResponse WebDriverConnection::print_page()
{
    // FIXME: Actually implement this :^)
    return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Print not implemented"sv);
}

// https://w3c.github.io/webdriver/#dfn-no-longer-open
Messages::WebDriverClient::EnsureTopLevelBrowsingContextIsOpenResponse WebDriverConnection::ensure_top_level_browsing_context_is_open()
{
    // A browsing context is said to be no longer open if it has been discarded.
    if (m_page_client.page().top_level_browsing_context().has_been_discarded())
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found"sv);
    return JsonValue {};
}

// https://w3c.github.io/webdriver/#dfn-no-longer-open
ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::ensure_open_top_level_browsing_context()
{
    TRY(ensure_top_level_browsing_context_is_open().take_response());
    return {};
}

// https://w3c.github.io/webdriver/#dfn-handle-any-user-prompts
ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::handle_any_user_prompts()
{
    // 1. If there is no current user prompt, abort these steps and return success.
    if (!m_page_client.page().has_pending_dialog())
        return {};

    // 2. Perform the following substeps based on the current session’s user prompt handler:
    switch (m_unhandled_prompt_behavior) {
    // -> dismiss state
    case Web::WebDriver::UnhandledPromptBehavior::Dismiss:
        // Dismiss the current user prompt.
        m_page_client.page().dismiss_dialog();
        break;

    // -> accept state
    case Web::WebDriver::UnhandledPromptBehavior::Accept:
        // Accept the current user prompt.
        m_page_client.page().accept_dialog();
        break;

    // -> dismiss and notify state
    case Web::WebDriver::UnhandledPromptBehavior::DismissAndNotify:
        // Dismiss the current user prompt.
        m_page_client.page().dismiss_dialog();

        // Return an annotated unexpected alert open error.
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnexpectedAlertOpen, "A user dialog is open"sv);

    // -> accept and notify state
    case Web::WebDriver::UnhandledPromptBehavior::AcceptAndNotify:
        // Accept the current user prompt.
        m_page_client.page().accept_dialog();

        // Return an annotated unexpected alert open error.
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnexpectedAlertOpen, "A user dialog is open"sv);

    // -> ignore state
    case Web::WebDriver::UnhandledPromptBehavior::Ignore:
        // Return an annotated unexpected alert open error.
        return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnexpectedAlertOpen, "A user dialog is open"sv);
    }

    // 3. Return success.
    return {};
}

// https://w3c.github.io/webdriver/#dfn-waiting-for-the-navigation-to-complete
ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::wait_for_navigation_to_complete()
{
    // 1. If the current session has a page loading strategy of none, return success with data null.
    if (m_page_load_strategy == Web::WebDriver::PageLoadStrategy::None)
        return {};

    // 2. If the current browsing context is no longer open, return success with data null.
    if (m_page_client.page().top_level_browsing_context().has_been_discarded())
        return {};

    // FIXME: 3. Start a timer. If this algorithm has not completed before timer reaches the session’s session page load timeout in milliseconds, return an error with error code timeout.
    // FIXME: 4. If there is an ongoing attempt to navigate the current browsing context that has not yet matured, wait for navigation to mature.

    // 5. Let readiness target be the document readiness state associated with the current session’s page loading strategy, which can be found in the table of page load strategies.
    auto readiness_target = [this]() {
        switch (m_page_load_strategy) {
        case Web::WebDriver::PageLoadStrategy::Normal:
            return Web::HTML::DocumentReadyState::Complete;
        case Web::WebDriver::PageLoadStrategy::Eager:
            return Web::HTML::DocumentReadyState::Interactive;
        default:
            VERIFY_NOT_REACHED();
        };
    }();

    // 6. Wait for the current browsing context’s document readiness state to reach readiness target,
    // FIXME: or for the session page load timeout to pass, whichever occurs sooner.
    Web::Platform::EventLoopPlugin::the().spin_until([&]() {
        return m_page_client.page().top_level_browsing_context().active_document()->readiness() == readiness_target;
    });

    // FIXME: 7. If the previous step completed by the session page load timeout being reached and the browser does not have an active user prompt, return error with error code timeout.

    // 8. Return success with data null.
    return {};
}

// https://w3c.github.io/webdriver/#dfn-restore-the-window
void WebDriverConnection::restore_the_window()
{
    // To restore the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to restore or unhide the window to the visible screen.
    m_page_client.page_did_request_restore_window();

    // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the visible state, or until the operation times out.
    // FIXME: Implement timeouts.
    Web::Platform::EventLoopPlugin::the().spin_until([this]() {
        auto state = m_page_client.page().top_level_browsing_context().system_visibility_state();
        return state == Web::HTML::VisibilityState::Visible;
    });
}

// https://w3c.github.io/webdriver/#dfn-maximize-the-window
Gfx::IntRect WebDriverConnection::maximize_the_window()
{
    // To maximize the window, given an operating system level window with an associated top-level browsing context, run the implementation-specific steps to transition the operating system level window into the maximized window state.
    auto rect = m_page_client.page_did_request_maximize_window();

    // Return when the window has completed the transition, or within an implementation-defined timeout.
    return rect;
}

// https://w3c.github.io/webdriver/#dfn-iconify-the-window
Gfx::IntRect WebDriverConnection::iconify_the_window()
{
    // To iconify the window, given an operating system level window with an associated top-level browsing context, run implementation-specific steps to iconify, minimize, or hide the window from the visible screen.
    auto rect = m_page_client.page_did_request_minimize_window();

    // Do not return from this operation until the visibility state of the top-level browsing context’s active document has reached the hidden state, or until the operation times out.
    // FIXME: Implement timeouts.
    Web::Platform::EventLoopPlugin::the().spin_until([this]() {
        auto state = m_page_client.page().top_level_browsing_context().system_visibility_state();
        return state == Web::HTML::VisibilityState::Hidden;
    });

    return rect;
}

// https://w3c.github.io/webdriver/#dfn-find
ErrorOr<JsonArray, Web::WebDriver::Error> WebDriverConnection::find(StartNodeGetter&& start_node_getter, Web::WebDriver::LocationStrategy using_, StringView value)
{
    // 1. Let end time be the current time plus the session implicit wait timeout.
    auto end_time = Time::now_monotonic() + Time::from_milliseconds(static_cast<i64>(m_timeouts_configuration.implicit_wait_timeout));

    // 2. Let location strategy be equal to using.
    auto location_strategy = using_;

    // 3. Let selector be equal to value.
    auto selector = value;

    ErrorOr<JS::GCPtr<Web::DOM::NodeList>, Web::WebDriver::Error> maybe_elements { nullptr };

    auto try_to_find_element = [&]() -> decltype(maybe_elements) {
        // 4. Let elements returned be the result of trying to call the relevant element location strategy with arguments start node, and selector.
        auto elements = Web::WebDriver::invoke_location_strategy(location_strategy, *TRY(start_node_getter()), selector);

        // 5. If a DOMException, SyntaxError, XPathException, or other error occurs during the execution of the element location strategy, return error invalid selector.
        if (elements.is_error())
            return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidSelector, DeprecatedString::formatted("The location strategy could not finish: {}", elements.error().message));

        return elements.release_value();
    };

    Web::Platform::EventLoopPlugin::the().spin_until([&]() {
        maybe_elements = try_to_find_element();
        if (maybe_elements.is_error())
            return true;

        // 6. If elements returned is empty and the current time is less than end time return to step 4. Otherwise, continue to the next step.
        return maybe_elements.value()->length() != 0 || Time::now_monotonic() >= end_time;
    });

    auto elements = TRY(maybe_elements);
    VERIFY(elements);

    // 7. Let result be an empty JSON List.
    JsonArray result;
    result.ensure_capacity(elements->length());

    // 8. For each element in elements returned, append the web element reference object for element, to result.
    for (size_t i = 0; i < elements->length(); ++i)
        result.append(web_element_reference_object(*elements->item(i)));

    // 9. Return success with data result.
    return result;
}

// https://w3c.github.io/webdriver/#dfn-extract-the-script-arguments-from-a-request
ErrorOr<WebDriverConnection::ScriptArguments, Web::WebDriver::Error> WebDriverConnection::extract_the_script_arguments_from_a_request(JsonValue const& payload)
{
    auto* window = m_page_client.page().top_level_browsing_context().active_window();
    auto& vm = window->vm();

    // 1. Let script be the result of getting a property named script from the parameters.
    // 2. If script is not a String, return error with error code invalid argument.
    auto script = TRY(get_property(payload, "script"sv));

    // 3. Let args be the result of getting a property named args from the parameters.
    // 4. If args is not an Array return error with error code invalid argument.
    auto const& args = *TRY(get_property<JsonArray const*>(payload, "args"sv));

    // 5. Let arguments be the result of calling the JSON deserialize algorithm with arguments args.
    auto arguments = JS::MarkedVector<JS::Value> { vm.heap() };

    args.for_each([&](auto const& arg) {
        arguments.append(JS::JSONObject::parse_json_value(vm, arg));
    });

    // 6. Return success with data script and arguments.
    return ScriptArguments { move(script), move(arguments) };
}

// https://w3c.github.io/webdriver/#dfn-delete-cookies
void WebDriverConnection::delete_cookies(Optional<StringView> const& name)
{
    // For each cookie among all associated cookies of the current browsing context’s active document, un the substeps of the first matching condition:
    auto* document = m_page_client.page().top_level_browsing_context().active_document();

    for (auto& cookie : m_page_client.page_did_request_all_cookies(document->url())) {
        // -> name is undefined
        // -> name is equal to cookie name
        if (!name.has_value() || name.value() == cookie.name) {
            // Set the cookie expiry time to a Unix timestamp in the past.
            cookie.expiry_time = Time::from_seconds(0);
            m_page_client.page_did_update_cookie(move(cookie));
        }
        // -> Otherwise
        //    Do nothing.
    }
}

}