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
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/* global XPCNativeWrapper */
const EXPORTED_SYMBOLS = ["GeckoDriver"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
OS: "resource://gre/modules/osfile.jsm",
accessibility: "chrome://marionette/content/accessibility.js",
Addon: "chrome://marionette/content/addon.js",
allowAllCerts: "chrome://marionette/content/cert.js",
assert: "chrome://marionette/content/assert.js",
atom: "chrome://marionette/content/atom.js",
browser: "chrome://marionette/content/browser.js",
Capabilities: "chrome://marionette/content/capabilities.js",
capture: "chrome://marionette/content/capture.js",
ChromeWebElement: "chrome://marionette/content/element.js",
clearElementIdCache:
"chrome://marionette/content/actors/MarionetteCommandsParent.jsm",
clearActionInputState:
"chrome://marionette/content/actors/MarionetteCommandsChild.jsm",
Context: "chrome://marionette/content/browser.js",
cookie: "chrome://marionette/content/cookie.js",
DebounceCallback: "chrome://marionette/content/sync.js",
element: "chrome://marionette/content/element.js",
error: "chrome://marionette/content/error.js",
evaluate: "chrome://marionette/content/evaluate.js",
getMarionetteCommandsActorProxy:
"chrome://marionette/content/actors/MarionetteCommandsParent.jsm",
IdlePromise: "chrome://marionette/content/sync.js",
interaction: "chrome://marionette/content/interaction.js",
l10n: "chrome://marionette/content/l10n.js",
legacyaction: "chrome://marionette/content/legacyaction.js",
Log: "chrome://marionette/content/log.js",
MarionettePrefs: "chrome://marionette/content/prefs.js",
modal: "chrome://marionette/content/modal.js",
navigate: "chrome://marionette/content/navigate.js",
PollPromise: "chrome://marionette/content/sync.js",
pprint: "chrome://marionette/content/format.js",
print: "chrome://marionette/content/print.js",
proxy: "chrome://marionette/content/proxy.js",
reftest: "chrome://marionette/content/reftest.js",
registerCommandsActor:
"chrome://marionette/content/actors/MarionetteCommandsParent.jsm",
registerEventsActor:
"chrome://marionette/content/actors/MarionetteEventsParent.jsm",
Sandboxes: "chrome://marionette/content/evaluate.js",
TimedPromise: "chrome://marionette/content/sync.js",
Timeouts: "chrome://marionette/content/capabilities.js",
UnhandledPromptBehavior: "chrome://marionette/content/capabilities.js",
unregisterCommandsActor:
"chrome://marionette/content/actors/MarionetteCommandsParent.jsm",
unregisterEventsActor:
"chrome://marionette/content/actors/MarionetteEventsParent.jsm",
waitForEvent: "chrome://marionette/content/sync.js",
waitForLoadEvent: "chrome://marionette/content/sync.js",
waitForObserverTopic: "chrome://marionette/content/sync.js",
WebElement: "chrome://marionette/content/element.js",
WebElementEventTarget: "chrome://marionette/content/dom.js",
WindowState: "chrome://marionette/content/browser.js",
});
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
const APP_ID_FIREFOX = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
const APP_ID_THUNDERBIRD = "{3550f703-e582-4d05-9a08-453d09bdfdc6}";
const FRAME_SCRIPT = "chrome://marionette/content/listener.js";
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const SUPPORTED_STRATEGIES = new Set([
element.Strategy.ClassName,
element.Strategy.Selector,
element.Strategy.ID,
element.Strategy.Name,
element.Strategy.LinkText,
element.Strategy.PartialLinkText,
element.Strategy.TagName,
element.Strategy.XPath,
]);
// Timeout used to abort fullscreen, maximize, and minimize
// commands if no window manager is present.
const TIMEOUT_NO_WINDOW_MANAGER = 5000;
const globalMessageManager = Services.mm;
/**
* The Marionette WebDriver services provides a standard conforming
* implementation of the W3C WebDriver specification.
*
* @see {@link https://w3c.github.io/webdriver/webdriver-spec.html}
* @namespace driver
*/
/**
* Implements (parts of) the W3C WebDriver protocol. GeckoDriver lives
* in chrome space and mediates calls to the message listener of the current
* browsing context's content frame message listener via ListenerProxy.
*
* Throughout this prototype, functions with the argument <var>cmd</var>'s
* documentation refers to the contents of the <code>cmd.parameter</code>
* object.
*
* @class GeckoDriver
*
* @param {MarionetteServer} server
* The instance of Marionette server.
*/
this.GeckoDriver = function(server) {
this.appId = Services.appinfo.ID;
this.appName = Services.appinfo.name.toLowerCase();
this._server = server;
this.sessionID = null;
this.browsers = {};
// Maps permanentKey to browsing context id: WeakMap.<Object, number>
this._browserIds = new WeakMap();
// points to current browser
this.curBrowser = null;
// top-most chrome window
this.mainFrame = null;
// current browsing contexts for chrome and content
this.chromeBrowsingContext = null;
this.contentBrowsingContext = null;
// Use content context by default
this.context = Context.Content;
this.sandboxes = new Sandboxes(() => this.getCurrentWindow());
this.legacyactions = new legacyaction.Chain();
this.capabilities = new Capabilities();
this.mm = globalMessageManager;
if (!MarionettePrefs.useActors) {
this.listener = proxy.toListener(
this.sendAsync.bind(this),
() => this.curBrowser
);
}
// used for modal dialogs or tab modal alerts
this.dialog = null;
this.dialogObserver = null;
};
Object.defineProperty(GeckoDriver.prototype, "a11yChecks", {
get() {
return this.capabilities.get("moz:accessibilityChecks");
},
});
/**
* The current context decides if commands are executed in chrome- or
* content space.
*/
Object.defineProperty(GeckoDriver.prototype, "context", {
get() {
return this._context;
},
set(context) {
this._context = Context.fromString(context);
},
});
/**
* Returns the current URL of the ChromeWindow or content browser,
* depending on context.
*
* @return {URL}
* Read-only property containing the currently loaded URL.
*/
Object.defineProperty(GeckoDriver.prototype, "currentURL", {
get() {
const browsingContext = this.getBrowsingContext({ top: true });
return new URL(browsingContext.currentWindowGlobal.documentURI.spec);
},
});
/**
* Returns the title of the ChromeWindow or content browser,
* depending on context.
*
* @return {string}
* Read-only property containing the title of the loaded URL.
*/
Object.defineProperty(GeckoDriver.prototype, "title", {
get() {
const browsingContext = this.getBrowsingContext({ top: true });
return browsingContext.currentWindowGlobal.documentTitle;
},
});
Object.defineProperty(GeckoDriver.prototype, "proxy", {
get() {
return this.capabilities.get("proxy");
},
});
Object.defineProperty(GeckoDriver.prototype, "secureTLS", {
get() {
return !this.capabilities.get("acceptInsecureCerts");
},
});
Object.defineProperty(GeckoDriver.prototype, "timeouts", {
get() {
return this.capabilities.get("timeouts");
},
set(newTimeouts) {
this.capabilities.set("timeouts", newTimeouts);
},
});
Object.defineProperty(GeckoDriver.prototype, "windows", {
get() {
return Services.wm.getEnumerator(null);
},
});
Object.defineProperty(GeckoDriver.prototype, "windowType", {
get() {
return this.curBrowser.window.document.documentElement.getAttribute(
"windowtype"
);
},
});
Object.defineProperty(GeckoDriver.prototype, "windowHandles", {
get() {
let hs = [];
for (let win of this.windows) {
let tabBrowser = browser.getTabBrowser(win);
// Only return handles for browser windows
if (tabBrowser && tabBrowser.tabs) {
for (let tab of tabBrowser.tabs) {
let winId = this.getIdForBrowser(browser.getBrowserForTab(tab));
if (winId !== null) {
hs.push(winId);
}
}
}
}
return hs;
},
});
Object.defineProperty(GeckoDriver.prototype, "chromeWindowHandles", {
get() {
let hs = [];
for (let win of this.windows) {
hs.push(getWindowId(win));
}
return hs;
},
});
GeckoDriver.prototype.QueryInterface = ChromeUtils.generateQI([
"nsIObserver",
"nsISupportsWeakReference",
]);
GeckoDriver.prototype.init = function() {
if (MarionettePrefs.useActors) {
// When using JSWindowActors, we are not relying on framescript events
return;
}
this.mm.addMessageListener("Marionette:ListenersAttached", this);
this.mm.addMessageListener("Marionette:Register", this);
this.mm.addMessageListener("Marionette:switchedToFrame", this);
this.mm.addMessageListener("Marionette:NavigationEvent", this);
this.mm.addMessageListener("Marionette:Unloaded", this, true);
};
GeckoDriver.prototype.uninit = function() {
if (MarionettePrefs.useActors) {
return;
}
this.mm.removeMessageListener("Marionette:ListenersAttached", this);
this.mm.removeMessageListener("Marionette:Register", this);
this.mm.removeMessageListener("Marionette:switchedToFrame", this);
this.mm.removeMessageListener("Marionette:NavigationEvent", this);
this.mm.removeMessageListener("Marionette:Unloaded", this);
};
/**
* Callback used to observe the creation of new modal or tab modal dialogs
* during the session's lifetime.
*/
GeckoDriver.prototype.handleModalDialog = function(action, dialog, win) {
// Only care about modals of the currently selected window.
if (win !== this.curBrowser.window) {
return;
}
if (action === modal.ACTION_OPENED) {
this.dialog = new modal.Dialog(() => this.curBrowser, dialog);
} else if (action === modal.ACTION_CLOSED) {
this.dialog = null;
}
};
/**
* Get the current visible URL.
*
* Can be removed once WindowGlobal supports visibleURL (bug 1664881).
*/
GeckoDriver.prototype._getCurrentURL = async function() {
let url;
if (MarionettePrefs.useActors) {
url = await this.getActor({ top: true }).getCurrentUrl();
return new URL(url);
}
switch (this.context) {
case Context.Chrome:
const browsingContext = this.getBrowsingContext({ top: true });
url = browsingContext.window.location.href;
break;
case Context.Content:
url = await this.listener.getCurrentUrl();
break;
}
return new URL(url);
};
/**
* Helper method to send async messages to the content listener.
* Correct usage is to pass in the name of a function in listener.js,
* a serialisable object, and optionally the current command's ID
* when not using the modern dispatching technique.
*
* @param {string} name
* Suffix of the target message handler <tt>Marionette:SUFFIX</tt>.
* @param {Object=} data
* Data that must be serialisable using {@link evaluate.toJSON}.
* @param {number=} commandID
* Optional command ID to ensure synchronisity.
*
* @throws {JavaScriptError}
* If <var>data</var> could not be marshaled.
* @throws {NoSuchWindowError}
* If there is no current target frame.
*/
GeckoDriver.prototype.sendAsync = function(name, data, commandID) {
let payload = evaluate.toJSON(data, this.seenEls);
if (payload === null) {
payload = {};
}
// TODO(ato): When proxy.AsyncMessageChannel
// is used for all chrome <-> content communication
// this can be removed.
if (commandID) {
payload.commandID = commandID;
}
if (this.curBrowser.curFrameId) {
let target = `Marionette:${name}`;
this.curBrowser.messageManager.sendAsyncMessage(target, payload);
} else {
throw new error.NoSuchWindowError(
"No such content frame; perhaps the listener was not registered?"
);
}
};
/**
* Get the current "MarionetteCommands" parent actor.
*
* @param {Object} options
* @param {boolean=} options.top
* If set to true use the window's top-level browsing context for the actor,
* otherwise the one from the currently selected frame. Defaults to false.
*
* @returns {MarionetteCommandsParent}
* The parent actor.
*/
GeckoDriver.prototype.getActor = function(options = {}) {
return getMarionetteCommandsActorProxy(() =>
this.getBrowsingContext(options)
);
};
/**
* Get the selected BrowsingContext for the current context.
*
* @param {Object} options
* @param {Context=} options.context
* Context (content or chrome) for which to retrieve the browsing context.
* Defaults to the current one.
* @param {boolean=} options.parent
* If set to true return the window's parent browsing context,
* otherwise the one from the currently selected frame. Defaults to false.
* @param {boolean=} options.top
* If set to true return the window's top-level browsing context,
* otherwise the one from the currently selected frame. Defaults to false.
*
* @return {BrowsingContext}
* The browsing context.
*/
GeckoDriver.prototype.getBrowsingContext = function(options = {}) {
const { context = this.context, parent = false, top = false } = options;
let browsingContext = null;
if (context === Context.Chrome) {
browsingContext = this.chromeBrowsingContext;
} else {
browsingContext = this.contentBrowsingContext;
}
if (browsingContext && parent) {
browsingContext = browsingContext.parent;
}
if (browsingContext && top) {
browsingContext = browsingContext.top;
}
return browsingContext;
};
/**
* Get the currently selected window.
*
* It will return the outer {@link ChromeWindow} previously selected by
* window handle through {@link #switchToWindow}, or the first window that
* was registered.
*
* @param {Object} options
* @param {Context=} options.context
* Optional name of the context to use for finding the window.
* It will be required if a command always needs a specific context,
* whether which context is currently set. Defaults to the current
* context.
*
* @return {ChromeWindow}
* The current top-level browsing context.
*/
GeckoDriver.prototype.getCurrentWindow = function(options = {}) {
const { context = this.context } = options;
let win = null;
switch (context) {
case Context.Chrome:
if (this.curBrowser) {
win = this.curBrowser.window;
}
break;
case Context.Content:
if (this.curBrowser && this.curBrowser.contentBrowser) {
win = this.curBrowser.window;
}
break;
}
return win;
};
GeckoDriver.prototype.isReftestBrowser = function(element) {
return (
this._reftest &&
element &&
element.tagName === "xul:browser" &&
element.parentElement &&
element.parentElement.id === "reftest"
);
};
GeckoDriver.prototype.addFrameCloseListener = function(action) {
let win = this.getCurrentWindow();
this.mozBrowserClose = e => {
if (e.target.id == this.oopFrameId) {
win.removeEventListener("mozbrowserclose", this.mozBrowserClose, true);
throw new error.NoSuchWindowError(
"The window closed during action: " + action
);
}
};
win.addEventListener("mozbrowserclose", this.mozBrowserClose, true);
};
/**
* Create a new browsing context for window and add to known browsers.
*
* @param {ChromeWindow} win
* Window for which we will create a browsing context.
*
* @return {string}
* Returns the unique server-assigned ID of the window.
*/
GeckoDriver.prototype.addBrowser = function(win) {
let context = new browser.Context(win, this);
let winId = getWindowId(win);
this.browsers[winId] = context;
this.curBrowser = this.browsers[winId];
};
/**
* Registers a new browser, win, with Marionette.
*
* If we have not seen the browser content window before, the listener
* frame script will be loaded into it. If isNewSession is true, we will
* switch focus to the start frame when it registers.
*
* @param {ChromeWindow} win
* Window whose browser we need to access.
* @param {boolean=} [false] isNewSession
* True if this is the first time we're talking to this browser.
*/
GeckoDriver.prototype.startBrowser = function(window, isNewSession = false) {
this.mainFrame = window;
this.addBrowser(window);
this.whenBrowserStarted(window, isNewSession);
};
/**
* Callback invoked after a new session has been started in a browser.
* Loads the Marionette frame script into the browser if needed.
*
* @param {ChromeWindow} window
* Window whose browser we need to access.
* @param {boolean} isNewSession
* True if this is the first time we're talking to this browser.
*/
GeckoDriver.prototype.whenBrowserStarted = function(window, isNewSession) {
// Do not load the framescript when actors are used.
if (MarionettePrefs.useActors) {
return;
}
let mm = window.messageManager;
if (mm) {
if (!isNewSession) {
// Loading the frame script corresponds to a situation we need to
// return to the server. If the messageManager is a message broadcaster
// with no children, we don't have a hope of coming back from this
// call, so send the ack here. Otherwise, make a note of how many
// child scripts will be loaded so we known when it's safe to return.
// Child managers may not have child scripts yet (e.g. socialapi),
// only count child managers that have children, but only count the top
// level children as they are the ones that we expect a response from.
if (mm.childCount !== 0) {
this.curBrowser.frameRegsPending = 0;
for (let i = 0; i < mm.childCount; i++) {
if (mm.getChildAt(i).childCount !== 0) {
this.curBrowser.frameRegsPending += 1;
}
}
}
}
if (!MarionettePrefs.contentListener || !isNewSession) {
// load listener into the remote frame
// and any applicable new frames
// opened after this call
mm.loadFrameScript(FRAME_SCRIPT, true);
MarionettePrefs.contentListener = true;
}
} else {
logger.error("Unable to load content frame script");
}
};
/**
* Recursively get all labeled text.
*
* @param {Element} el
* The parent element.
* @param {Array.<string>} lines
* Array that holds the text lines.
*/
GeckoDriver.prototype.getVisibleText = function(el, lines) {
try {
if (atom.isElementDisplayed(el, this.getCurrentWindow())) {
if (el.value) {
lines.push(el.value);
}
for (let child in el.childNodes) {
this.getVisibleText(el.childNodes[child], lines);
}
}
} catch (e) {
if (el.nodeName == "#text") {
lines.push(el.textContent);
}
}
};
/**
* Handles registration of new content listener browsers. Depending on
* their type they are either accepted or ignored.
*
* @param {xul:browser} browserElement
*/
GeckoDriver.prototype.registerBrowser = function(browserElement) {
// We want to ignore frames that are XUL browsers that aren't in the "main"
// tabbrowser, but accept things on Fennec (which doesn't have a
// xul:tabbrowser), and accept HTML iframes (because tests depend on it),
// as well as XUL frames. Ideally this should be cleaned up and we should
// keep track of browsers a different way.
if (
this.appId != APP_ID_FIREFOX ||
browserElement.namespaceURI != XUL_NS ||
browserElement.nodeName != "browser" ||
browserElement.getTabBrowser()
) {
this.curBrowser.register(browserElement);
}
};
GeckoDriver.prototype.registerPromise = function() {
const li = "Marionette:Register";
return new Promise(resolve => {
let cb = ({ json, target }) => {
this.registerBrowser(target);
if (this.curBrowser.frameRegsPending > 0) {
this.curBrowser.frameRegsPending--;
}
if (this.curBrowser.frameRegsPending === 0) {
this.mm.removeMessageListener(li, cb);
resolve();
}
return { frameId: json.frameId };
};
this.mm.addMessageListener(li, cb);
});
};
GeckoDriver.prototype.listeningPromise = function() {
const li = "Marionette:ListenersAttached";
return new Promise(resolve => {
let cb = msg => {
if (msg.json.frameId === this.curBrowser.curFrameId) {
this.mm.removeMessageListener(li, cb);
resolve(msg.json.frameId);
}
};
this.mm.addMessageListener(li, cb);
});
};
/**
* Create a new WebDriver session.
*
* It is expected that the caller performs the necessary checks on
* the requested capabilities to be WebDriver conforming. The WebDriver
* service offered by Marionette does not match or negotiate capabilities
* beyond type- and bounds checks.
*
* <h3>Capabilities</h3>
*
* <dl>
* <dt><code>pageLoadStrategy</code> (string)
* <dd>The page load strategy to use for the current session. Must be
* one of "<tt>none</tt>", "<tt>eager</tt>", and "<tt>normal</tt>".
*
* <dt><code>acceptInsecureCerts</code> (boolean)
* <dd>Indicates whether untrusted and self-signed TLS certificates
* are implicitly trusted on navigation for the duration of the session.
*
* <dt><code>timeouts</code> (Timeouts object)
* <dd>Describes the timeouts imposed on certian session operations.
*
* <dt><code>proxy</code> (Proxy object)
* <dd>Defines the proxy configuration.
*
* <dt><code>moz:accessibilityChecks</code> (boolean)
* <dd>Run a11y checks when clicking elements.
*
* <dt><code>moz:useNonSpecCompliantPointerOrigin</code> (boolean)
* <dd>Use the not WebDriver conforming calculation of the pointer origin
* when the origin is an element, and the element center point is used.
*
* <dt><code>moz:webdriverClick</code> (boolean)
* <dd>Use a WebDriver conforming <i>WebDriver::ElementClick</i>.
* </dl>
*
* <h4>Timeouts object</h4>
*
* <dl>
* <dt><code>script</code> (number)
* <dd>Determines when to interrupt a script that is being evaluates.
*
* <dt><code>pageLoad</code> (number)
* <dd>Provides the timeout limit used to interrupt navigation of the
* browsing context.
*
* <dt><code>implicit</code> (number)
* <dd>Gives the timeout of when to abort when locating an element.
* </dl>
*
* <h4>Proxy object</h4>
*
* <dl>
* <dt><code>proxyType</code> (string)
* <dd>Indicates the type of proxy configuration. Must be one
* of "<tt>pac</tt>", "<tt>direct</tt>", "<tt>autodetect</tt>",
* "<tt>system</tt>", or "<tt>manual</tt>".
*
* <dt><code>proxyAutoconfigUrl</code> (string)
* <dd>Defines the URL for a proxy auto-config file if
* <code>proxyType</code> is equal to "<tt>pac</tt>".
*
* <dt><code>ftpProxy</code> (string)
* <dd>Defines the proxy host for FTP traffic when the
* <code>proxyType</code> is "<tt>manual</tt>".
*
* <dt><code>httpProxy</code> (string)
* <dd>Defines the proxy host for HTTP traffic when the
* <code>proxyType</code> is "<tt>manual</tt>".
*
* <dt><code>noProxy</code> (string)
* <dd>Lists the adress for which the proxy should be bypassed when
* the <code>proxyType</code> is "<tt>manual</tt>". Must be a JSON
* List containing any number of any of domains, IPv4 addresses, or IPv6
* addresses.
*
* <dt><code>sslProxy</code> (string)
* <dd>Defines the proxy host for encrypted TLS traffic when the
* <code>proxyType</code> is "<tt>manual</tt>".
*
* <dt><code>socksProxy</code> (string)
* <dd>Defines the proxy host for a SOCKS proxy traffic when the
* <code>proxyType</code> is "<tt>manual</tt>".
*
* <dt><code>socksVersion</code> (string)
* <dd>Defines the SOCKS proxy version when the <code>proxyType</code> is
* "<tt>manual</tt>". It must be any integer between 0 and 255
* inclusive.
* </dl>
*
* <h3>Example</h3>
*
* Input:
*
* <pre><code>
* {"capabilities": {"acceptInsecureCerts": true}}
* </code></pre>
*
* @param {string=} sessionId
* Normally a unique ID is given to a new session, however this can
* be overriden by providing this field.
* @param {Object.<string, *>=} capabilities
* JSON Object containing any of the recognised capabilities listed
* above.
*
* @return {Object}
* Session ID and capabilities offered by the WebDriver service.
*
* @throws {SessionNotCreatedError}
* If, for whatever reason, a session could not be created.
*/
GeckoDriver.prototype.newSession = async function(cmd) {
if (this.sessionID) {
throw new error.SessionNotCreatedError("Maximum number of active sessions");
}
this.sessionID = WebElement.generateUUID();
try {
this.capabilities = Capabilities.fromJSON(cmd.parameters);
if (!this.secureTLS) {
logger.warn("TLS certificate errors will be ignored for this session");
allowAllCerts.enable();
}
if (this.proxy.init()) {
logger.info("Proxy settings initialised: " + JSON.stringify(this.proxy));
}
} catch (e) {
throw new error.SessionNotCreatedError(e);
}
// If we are testing accessibility with marionette, start a11y service in
// chrome first. This will ensure that we do not have any content-only
// services hanging around.
if (this.a11yChecks && accessibility.service) {
logger.info("Preemptively starting accessibility service in Chrome");
}
let waitForWindow = function() {
let windowTypes;
switch (this.appId) {
case APP_ID_THUNDERBIRD:
windowTypes = ["mail:3pane"];
break;
default:
// We assume that an app either has GeckoView windows, or
// Firefox/Fennec windows, but not both.
windowTypes = ["navigator:browser", "navigator:geckoview"];
break;
}
let win;
for (let windowType of windowTypes) {
win = Services.wm.getMostRecentWindow(windowType);
if (win) {
break;
}
}
if (!win) {
// if the window isn't even created, just poll wait for it
let checkTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
checkTimer.initWithCallback(
waitForWindow.bind(this),
100,
Ci.nsITimer.TYPE_ONE_SHOT
);
} else if (win.document.readyState != "complete") {
// otherwise, wait for it to be fully loaded before proceeding
let listener = ev => {
// ensure that we proceed, on the top level document load event
// (not an iframe one...)
if (ev.target != win.document) {
return;
}
win.removeEventListener("load", listener);
waitForWindow.call(this);
};
win.addEventListener("load", listener, true);
} else {
if (MarionettePrefs.clickToStart) {
Services.prompt.alert(
win,
"",
"Click to start execution of marionette tests"
);
}
this.startBrowser(win, true);
}
};
let registerBrowsers;
let browserListening;
if (MarionettePrefs.useActors) {
registerCommandsActor();
registerEventsActor();
} else {
registerBrowsers = this.registerPromise();
browserListening = this.listeningPromise();
}
if (!MarionettePrefs.contentListener) {
waitForWindow.call(this);
} else if (this.appId != APP_ID_FIREFOX && this.curBrowser === null) {
// if there is a content listener, then we just wake it up
let win = this.getCurrentWindow();
this.addBrowser(win);
this.whenBrowserStarted(win, false);
} else {
throw new error.WebDriverError("Session already running");
}
if (MarionettePrefs.useActors) {
for (let win of this.windows) {
const tabBrowser = browser.getTabBrowser(win);
if (tabBrowser) {
for (const tab of tabBrowser.tabs) {
const contentBrowser = browser.getBrowserForTab(tab);
this.registerBrowser(contentBrowser);
}
}
}
} else {
await registerBrowsers;
await browserListening;
}
if (this.mainFrame) {
this.chromeBrowsingContext = this.mainFrame.browsingContext;
this.mainFrame.focus();
}
if (this.curBrowser.tab) {
this.contentBrowsingContext = this.curBrowser.contentBrowser.browsingContext;
this.curBrowser.contentBrowser.focus();
}
// Setup observer for modal dialogs
this.dialogObserver = new modal.DialogObserver(this);
this.dialogObserver.add(this.handleModalDialog.bind(this));
Services.obs.addObserver(this, "browsing-context-attached");
// Check if there is already an open dialog for the selected browser window.
this.dialog = modal.findModalDialogs(this.curBrowser);
return {
sessionId: this.sessionID,
capabilities: this.capabilities,
};
};
GeckoDriver.prototype.observe = function(subject, topic, data) {
switch (topic) {
case "browsing-context-attached":
// For cross-group navigations the complete browsing context tree of a tab
// gets replaced. An indication for that is when the newly attached
// browsing context has the same browserId as the currently selected
// content browsing context, and doesn't have a parent.
//
// Also the current content browsing context gets only updated when it's
// the top-level one to not automatically switch away from the currently
// selected frame.
if (
subject.browserId == this.contentBrowsingContext?.browserId &&
!subject.parent &&
!this.contentBrowsingContext?.parent
) {
logger.trace(
"Remoteness change detected. Set new top-level browsing context " +
`to ${subject.id}`
);
this.contentBrowsingContext = subject;
if (MarionettePrefs.useActors) {
// When using the framescript, the new browsing context created after
// a remoteness change will self-register. With JSWindowActors, we
// manually update the stored browsing context id.
// Switching to browserId instead of browsingContext.id would make
// this call unnecessary. See Bug 1681973.
this.updateIdForBrowser(this.curBrowser.contentBrowser, subject.id);
}
}
break;
}
};
/**
* Send the current session's capabilities to the client.
*
* Capabilities informs the client of which WebDriver features are
* supported by Firefox and Marionette. They are immutable for the
* length of the session.
*
* The return value is an immutable map of string keys
* ("capabilities") to values, which may be of types boolean,
* numerical or string.
*/
GeckoDriver.prototype.getSessionCapabilities = function() {
return { capabilities: this.capabilities };
};
/**
* Sets the context of the subsequent commands.
*
* All subsequent requests to commands that in some way involve
* interaction with a browsing context will target the chosen browsing
* context.
*
* @param {string} value
* Name of the context to be switched to. Must be one of "chrome" or
* "content".
*
* @throws {InvalidArgumentError}
* If <var>value</var> is not a string.
* @throws {WebDriverError}
* If <var>value</var> is not a valid browsing context.
*/
GeckoDriver.prototype.setContext = function(cmd) {
let value = assert.string(cmd.parameters.value);
this.context = value;
};
/**
* Gets the context type that is Marionette's current target for
* browsing context scoped commands.
*
* You may choose a context through the {@link #setContext} command.
*
* The default browsing context is {@link Context.Content}.
*
* @return {Context}
* Current context.
*/
GeckoDriver.prototype.getContext = function() {
return this.context;
};
/**
* Executes a JavaScript function in the context of the current browsing
* context, if in content space, or in chrome space otherwise, and returns
* the return value of the function.
*
* It is important to note that if the <var>sandboxName</var> parameter
* is left undefined, the script will be evaluated in a mutable sandbox,
* causing any change it makes on the global state of the document to have
* lasting side-effects.
*
* @param {string} script
* Script to evaluate as a function body.
* @param {Array.<(string|boolean|number|object|WebElement)>} args
* Arguments exposed to the script in <code>arguments</code>.
* The array items must be serialisable to the WebDriver protocol.
* @param {string=} sandbox
* Name of the sandbox to evaluate the script in. The sandbox is
* cached for later re-use on the same Window object if
* <var>newSandbox</var> is false. If he parameter is undefined,
* the script is evaluated in a mutable sandbox. If the parameter
* is "system", it will be evaluted in a sandbox with elevated system
* privileges, equivalent to chrome space.
* @param {boolean=} newSandbox
* Forces the script to be evaluated in a fresh sandbox. Note that if
* it is undefined, the script will normally be evaluted in a fresh
* sandbox.
* @param {string=} filename
* Filename of the client's program where this script is evaluated.
* @param {number=} line
* Line in the client's program where this script is evaluated.
*
* @return {(string|boolean|number|object|WebElement)}
* Return value from the script, or null which signifies either the
* JavaScript notion of null or undefined.
*
* @throws {JavaScriptError}
* If an {@link Error} was thrown whilst evaluating the script.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {ScriptTimeoutError}
* If the script was interrupted due to reaching the session's
* script timeout.
*/
GeckoDriver.prototype.executeScript = async function(cmd) {
let { script, args } = cmd.parameters;
let opts = {
script: cmd.parameters.script,
args: cmd.parameters.args,
sandboxName: cmd.parameters.sandbox,
newSandbox: cmd.parameters.newSandbox,
file: cmd.parameters.filename,
line: cmd.parameters.line,
};
return { value: await this.execute_(script, args, opts) };
};
/**
* Executes a JavaScript function in the context of the current browsing
* context, if in content space, or in chrome space otherwise, and returns
* the object passed to the callback.
*
* The callback is always the last argument to the <var>arguments</var>
* list passed to the function scope of the script. It can be retrieved
* as such:
*
* <pre><code>
* let callback = arguments[arguments.length - 1];
* callback("foo");
* // "foo" is returned
* </code></pre>
*
* It is important to note that if the <var>sandboxName</var> parameter
* is left undefined, the script will be evaluated in a mutable sandbox,
* causing any change it makes on the global state of the document to have
* lasting side-effects.
*
* @param {string} script
* Script to evaluate as a function body.
* @param {Array.<(string|boolean|number|object|WebElement)>} args
* Arguments exposed to the script in <code>arguments</code>.
* The array items must be serialisable to the WebDriver protocol.
* @param {string=} sandbox
* Name of the sandbox to evaluate the script in. The sandbox is
* cached for later re-use on the same Window object if
* <var>newSandbox</var> is false. If the parameter is undefined,
* the script is evaluated in a mutable sandbox. If the parameter
* is "system", it will be evaluted in a sandbox with elevated system
* privileges, equivalent to chrome space.
* @param {boolean=} newSandbox
* Forces the script to be evaluated in a fresh sandbox. Note that if
* it is undefined, the script will normally be evaluted in a fresh
* sandbox.
* @param {string=} filename
* Filename of the client's program where this script is evaluated.
* @param {number=} line
* Line in the client's program where this script is evaluated.
*
* @return {(string|boolean|number|object|WebElement)}
* Return value from the script, or null which signifies either the
* JavaScript notion of null or undefined.
*
* @throws {JavaScriptError}
* If an Error was thrown whilst evaluating the script.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {ScriptTimeoutError}
* If the script was interrupted due to reaching the session's
* script timeout.
*/
GeckoDriver.prototype.executeAsyncScript = async function(cmd) {
let { script, args } = cmd.parameters;
let opts = {
script: cmd.parameters.script,
args: cmd.parameters.args,
sandboxName: cmd.parameters.sandbox,
newSandbox: cmd.parameters.newSandbox,
file: cmd.parameters.filename,
line: cmd.parameters.line,
async: true,
};
return { value: await this.execute_(script, args, opts) };
};
GeckoDriver.prototype.execute_ = async function(
script,
args = [],
{
sandboxName = null,
newSandbox = false,
file = "",
line = 0,
async = false,
} = {}
) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
assert.string(script, pprint`Expected "script" to be a string: ${script}`);
assert.array(args, pprint`Expected script args to be an array: ${args}`);
if (sandboxName !== null) {
assert.string(
sandboxName,
pprint`Expected sandbox name to be a string: ${sandboxName}`
);
}
assert.boolean(
newSandbox,
pprint`Expected newSandbox to be boolean: ${newSandbox}`
);
assert.string(file, pprint`Expected file to be a string: ${file}`);
assert.number(line, pprint`Expected line to be a number: ${line}`);
let opts = {
timeout: this.timeouts.script,
sandboxName,
newSandbox,
file,
line,
async,
};
if (MarionettePrefs.useActors) {
return this.getActor().executeScript(script, args, opts);
}
let res, els;
switch (this.context) {
case Context.Chrome:
let sb = this.sandboxes.get(sandboxName, newSandbox);
let wargs = evaluate.fromJSON(args, this.curBrowser.seenEls, sb.window);
res = await evaluate.sandbox(sb, script, wargs, opts);
els = this.curBrowser.seenEls;
break;
case Context.Content:
// evaluate in content with lasting side-effects
opts.useSandbox = !!sandboxName;
res = await this.listener.executeScript(script, args, opts);
break;
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
return evaluate.toJSON(res, els);
};
/**
* Navigate to given URL.
*
* Navigates the current browsing context to the given URL and waits for
* the document to load or the session's page timeout duration to elapse
* before returning.
*
* The command will return with a failure if there is an error loading
* the document or the URL is blocked. This can occur if it fails to
* reach host, the URL is malformed, or if there is a certificate issue
* to name some examples.
*
* The document is considered successfully loaded when the
* DOMContentLoaded event on the frame element associated with the
* current window triggers and document.readyState is "complete".
*
* In chrome context it will change the current window's location to
* the supplied URL and wait until document.readyState equals "complete"
* or the page timeout duration has elapsed.
*
* @param {string} url
* URL to navigate to.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.navigateTo = async function(cmd) {
assert.content(this.context);
const browsingContext = assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
let validURL;
try {
validURL = new URL(cmd.parameters.url);
} catch (e) {
throw new error.InvalidArgumentError(`Malformed URL: ${e.message}`);
}
// Switch to the top-level browsing context before navigating
if (MarionettePrefs.useActors) {
this.contentBrowsingContext = browsingContext;
} else {
await this.listener.switchToFrame();
}
const loadEventExpected = navigate.isLoadEventExpected(
await this._getCurrentURL(),
{
future: validURL,
}
);
await navigate.waitForNavigationCompleted(
this,
() => {
navigate.navigateTo(browsingContext, validURL);
},
{ loadEventExpected }
);
this.curBrowser.contentBrowser.focus();
};
/**
* Get a string representing the current URL.
*
* On Desktop this returns a string representation of the URL of the
* current top level browsing context. This is equivalent to
* document.location.href.
*
* When in the context of the chrome, this returns the canonical URL
* of the current resource.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getCurrentUrl = async function() {
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
const url = await this._getCurrentURL();
return url.href;
};
/**
* Gets the current title of the window.
*
* @return {string}
* Document title of the top-level browsing context.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getTitle = async function() {
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
return this.title;
};
/**
* Gets the current type of the window.
*
* @return {string}
* Type of window
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.getWindowType = function() {
assert.open(this.getBrowsingContext({ top: true }));
return this.windowType;
};
/**
* Gets the page source of the content document.
*
* @return {string}
* String serialisation of the DOM of the current browsing context's
* active document.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getPageSource = async function() {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
if (MarionettePrefs.useActors) {
return this.getActor().getPageSource();
}
switch (this.context) {
case Context.Chrome:
const win = this.getCurrentWindow();
const s = new win.XMLSerializer();
return s.serializeToString(win.document);
case Context.Content:
return this.listener.getPageSource();
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Cause the browser to traverse one step backward in the joint history
* of the current browsing context.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.goBack = async function() {
assert.content(this.context);
const browsingContext = assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
// If there is no history, just return
if (!browsingContext.embedderElement?.canGoBack) {
return;
}
await navigate.waitForNavigationCompleted(this, () => {
browsingContext.goBack();
});
};
/**
* Cause the browser to traverse one step forward in the joint history
* of the current browsing context.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.goForward = async function() {
assert.content(this.context);
const browsingContext = assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
// If there is no history, just return
if (!browsingContext.embedderElement?.canGoForward) {
return;
}
await navigate.waitForNavigationCompleted(this, () => {
browsingContext.goForward();
});
};
/**
* Causes the browser to reload the page in current top-level browsing
* context.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.refresh = async function() {
assert.content(this.context);
const browsingContext = assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
// Switch to the top-level browsing context before navigating
if (MarionettePrefs.useActors) {
this.contentBrowsingContext = browsingContext;
} else {
await this.listener.switchToFrame();
}
await navigate.waitForNavigationCompleted(this, () => {
navigate.refresh(browsingContext);
});
};
/**
* Forces an update for the given browser's id.
*/
GeckoDriver.prototype.updateIdForBrowser = function(browser, newId) {
this._browserIds.set(browser.permanentKey, newId);
};
/**
* Retrieves a listener id for the given xul browser element. In case
* the browser is not known, an attempt is made to retrieve the id from
* a CPOW, and null is returned if this fails.
*/
GeckoDriver.prototype.getIdForBrowser = function(browser) {
if (browser === null) {
return null;
}
let permKey = browser.permanentKey;
if (this._browserIds.has(permKey)) {
return this._browserIds.get(permKey);
}
let winId = browser.browsingContext.id;
if (winId) {
this._browserIds.set(permKey, winId);
return winId;
}
return null;
};
/**
* Get the current window's handle. On desktop this typically corresponds
* to the currently selected tab.
*
* Return an opaque server-assigned identifier to this window that
* uniquely identifies it within this Marionette instance. This can
* be used to switch to this window at a later point.
*
* @return {string}
* Unique window handle.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.getWindowHandle = function() {
const browsingContext = assert.open(
this.getBrowsingContext({
context: Context.Content,
top: true,
})
);
return browsingContext.id.toString();
};
/**
* Get a list of top-level browsing contexts. On desktop this typically
* corresponds to the set of open tabs for browser windows, or the window
* itself for non-browser chrome windows.
*
* Each window handle is assigned by the server and is guaranteed unique,
* however the return array does not have a specified ordering.
*
* @return {Array.<string>}
* Unique window handles.
*/
GeckoDriver.prototype.getWindowHandles = function() {
return this.windowHandles.map(String);
};
/**
* Get the current window's handle. This corresponds to a window that
* may itself contain tabs.
*
* Return an opaque server-assigned identifier to this window that
* uniquely identifies it within this Marionette instance. This can
* be used to switch to this window at a later point.
*
* @return {string}
* Unique window handle.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnknownError}
* Internal browsing context reference not found
*/
GeckoDriver.prototype.getChromeWindowHandle = function() {
const browsingContext = assert.open(
this.getBrowsingContext({
context: Context.Chrome,
top: true,
})
);
return browsingContext.id.toString();
};
/**
* Returns identifiers for each open chrome window for tests interested in
* managing a set of chrome windows and tabs separately.
*
* @return {Array.<string>}
* Unique window handles.
*/
GeckoDriver.prototype.getChromeWindowHandles = function() {
return this.chromeWindowHandles.map(String);
};
/**
* Get the current position and size of the browser window currently in focus.
*
* Will return the current browser window size in pixels. Refers to
* window outerWidth and outerHeight values, which include scroll bars,
* title bars, etc.
*
* @return {Object.<string, number>}
* Object with |x| and |y| coordinates, and |width| and |height|
* of browser window.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getWindowRect = async function() {
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
return this.curBrowser.rect;
};
/**
* Set the window position and size of the browser on the operating
* system window manager.
*
* The supplied `width` and `height` values refer to the window `outerWidth`
* and `outerHeight` values, which include browser chrome and OS-level
* window borders.
*
* @param {number} x
* X coordinate of the top/left of the window that it will be
* moved to.
* @param {number} y
* Y coordinate of the top/left of the window that it will be
* moved to.
* @param {number} width
* Width to resize the window to.
* @param {number} height
* Height to resize the window to.
*
* @return {Object.<string, number>}
* Object with `x` and `y` coordinates and `width` and `height`
* dimensions.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not applicable to application.
*/
GeckoDriver.prototype.setWindowRect = async function(cmd) {
assert.firefox();
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
let { x, y, width, height } = cmd.parameters;
const win = this.getCurrentWindow();
switch (WindowState.from(win.windowState)) {
case WindowState.Fullscreen:
await exitFullscreen(win);
break;
case WindowState.Maximized:
case WindowState.Minimized:
await restoreWindow(win);
break;
}
if (width != null && height != null) {
assert.positiveInteger(height);
assert.positiveInteger(width);
if (win.outerWidth != width || win.outerHeight != height) {
win.resizeTo(width, height);
await new IdlePromise(win);
}
}
if (x != null && y != null) {
assert.integer(x);
assert.integer(y);
if (win.screenX != x || win.screenY != y) {
win.moveTo(x, y);
await new IdlePromise(win);
}
}
return this.curBrowser.rect;
};
/**
* Switch current top-level browsing context by name or server-assigned
* ID. Searches for windows by name, then ID. Content windows take
* precedence.
*
* @param {string} handle
* Handle of the window to switch to.
* @param {boolean=} focus
* A boolean value which determines whether to focus
* the window. Defaults to true.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.switchToWindow = async function(cmd) {
const { focus = true, handle } = cmd.parameters;
assert.string(
handle,
pprint`Expected "handle" to be a string, got ${handle}`
);
assert.boolean(focus, pprint`Expected "focus" to be a boolean, got ${focus}`);
const id = parseInt(handle);
const found = this.findWindow(this.windows, (win, winId) => id == winId);
let selected = false;
if (found) {
try {
await this.setWindowHandle(found, focus);
selected = true;
} catch (e) {
logger.error(e);
}
}
if (!selected) {
throw new error.NoSuchWindowError(`Unable to locate window: ${handle}`);
}
};
/**
* Find a specific window according to some filter function.
*
* @param {Iterable.<Window>} winIterable
* Iterable that emits Window objects.
* @param {function(Window, number): boolean} filter
* A callback function taking two arguments; the window and
* the outerId of the window, and returning a boolean indicating
* whether the window is the target.
*
* @return {Object}
* A window handle object containing the window and some
* associated metadata.
*/
GeckoDriver.prototype.findWindow = function(winIterable, filter) {
for (const win of winIterable) {
const browsingContext = win.docShell.browsingContext;
const tabBrowser = browser.getTabBrowser(win);
// In case the wanted window is a chrome window, we are done.
if (filter(win, browsingContext.id)) {
return { win, id: browsingContext.id, hasTabBrowser: !!tabBrowser };
// Otherwise check if the chrome window has a tab browser, and that it
// contains a tab with the wanted window handle.
} else if (tabBrowser && tabBrowser.tabs) {
for (let i = 0; i < tabBrowser.tabs.length; ++i) {
let contentBrowser = browser.getBrowserForTab(tabBrowser.tabs[i]);
let contentWindowId = this.getIdForBrowser(contentBrowser);
if (filter(win, contentWindowId)) {
return {
win,
id: browsingContext.id,
hasTabBrowser: true,
tabIndex: i,
};
}
}
}
}
return null;
};
/**
* Switch the marionette window to a given window. If the browser in
* the window is unregistered, register that browser and wait for
* the registration is complete. If |focus| is true then set the focus
* on the window.
*
* @param {Object} winProperties
* Object containing window properties such as returned from
* GeckoDriver#findWindow
* @param {boolean=} focus
* A boolean value which determines whether to focus the window.
* Defaults to true.
*/
GeckoDriver.prototype.setWindowHandle = async function(
winProperties,
focus = true
) {
if (!(winProperties.id in this.browsers)) {
// Initialise Marionette if the current chrome window has not been seen
// before. Also register the initial tab, if one exists.
let registerBrowsers, browserListening;
if (!MarionettePrefs.useActors && winProperties.hasTabBrowser) {
registerBrowsers = this.registerPromise();
browserListening = this.listeningPromise();
}
this.startBrowser(winProperties.win, false /* isNewSession */);
this.chromeBrowsingContext = this.mainFrame.browsingContext;
if (!winProperties.hasTabBrowser) {
this.contentBrowsingContext = null;
} else if (MarionettePrefs.useActors) {
const tabBrowser = browser.getTabBrowser(winProperties.win);
// For chrome windows such as a reftest window, `getTabBrowser` is not
// a tabbrowser, it is the content browser which should be used here.
const contentBrowser = tabBrowser.tabs
? tabBrowser.selectedBrowser
: tabBrowser;
this.contentBrowsingContext = contentBrowser.browsingContext;
this.registerBrowser(contentBrowser);
} else {
await registerBrowsers;
const id = await browserListening;
this.contentBrowsingContext = BrowsingContext.get(id);
}
} else {
// Otherwise switch to the known chrome window
this.curBrowser = this.browsers[winProperties.id];
this.mainFrame = this.curBrowser.window;
// Activate the tab if it's a content window.
let tab = null;
if (winProperties.hasTabBrowser) {
tab = await this.curBrowser.switchToTab(
winProperties.tabIndex,
winProperties.win,
focus
);
}
this.chromeBrowsingContext = this.mainFrame.browsingContext;
this.contentBrowsingContext = tab?.linkedBrowser.browsingContext;
}
if (focus) {
await this.curBrowser.focusWindow();
}
};
/**
* Set the current browsing context for future commands to the parent
* of the current browsing context.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.switchToParentFrame = async function() {
let browsingContext = this.getBrowsingContext();
if (browsingContext && !browsingContext.parent) {
return;
}
browsingContext = assert.open(browsingContext?.parent);
if (MarionettePrefs.useActors) {
this.contentBrowsingContext = browsingContext;
return;
}
await this.listener.switchToParentFrame();
};
/**
* Switch to a given frame within the current window.
*
* @param {(string|Object)=} element
* A web element reference of the frame or its element id.
* @param {number=} id
* The index of the frame to switch to.
* If both element and id are not defined, switch to top-level frame.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.switchToFrame = async function(cmd) {
const { element: el, id } = cmd.parameters;
if (typeof id == "number") {
assert.unsignedShort(id, `Expected id to be unsigned short, got ${id}`);
}
const top = id == null && el == null;
assert.open(this.getBrowsingContext({ top }));
await this._handleUserPrompts();
// Bug 1495063: Elements should be passed as WebElement reference
let byFrame;
if (typeof el == "string") {
byFrame = WebElement.fromUUID(el, this.context);
} else if (el) {
byFrame = WebElement.fromJSON(el);
}
if (MarionettePrefs.useActors) {
const { browsingContext } = await this.getActor({ top }).switchToFrame(
byFrame || id
);
this.contentBrowsingContext = browsingContext;
return;
}
const checkLoad = function(win) {
const otherErrorsExpr = /about:.+(error)|(blocked)\?/;
return new PollPromise(resolve => {
if (win.document.readyState == "complete") {
resolve();
} else if (win.document.readyState == "interactive") {
let documentURI = win.document.documentURI;
if (documentURI.startsWith("about:certerror")) {
throw new error.InsecureCertificateError();
} else if (otherErrorsExpr.exec(documentURI)) {
throw new error.UnknownError("Reached error page: " + documentURI);
}
}
});
};
if (this.context == Context.Chrome) {
const childContexts = this.getBrowsingContext().children;
let browsingContext;
if (id == null && !byFrame) {
browsingContext = this.getBrowsingContext({ top: true });
} else if (typeof id == "number") {
if (id < 0 || id >= childContexts.length) {
throw new error.NoSuchFrameError(
`Unable to locate frame with index: ${id}`
);
}
browsingContext = childContexts[id];
} else {
const wantedFrame = this.curBrowser.seenEls.get(byFrame);
const context = childContexts.find(context => {
return context.embedderElement === wantedFrame;
});
if (!context) {
throw new error.NoSuchFrameError(
`Unable to locate frame for element: ${byFrame}`
);
}
browsingContext = context;
}
this.contentBrowsingContext = browsingContext;
const frameWindow = browsingContext.window;
await checkLoad(frameWindow);
} else if (this.context == Context.Content) {
cmd.commandID = cmd.id;
await this.listener.switchToFrame(cmd.parameters);
}
};
GeckoDriver.prototype.getTimeouts = function() {
return this.timeouts;
};
/**
* Set timeout for page loading, searching, and scripts.
*
* @param {Object.<string, number>}
* Dictionary of timeout types and their new value, where all timeout
* types are optional.
*
* @throws {InvalidArgumentError}
* If timeout type key is unknown, or the value provided with it is
* not an integer.
*/
GeckoDriver.prototype.setTimeouts = function(cmd) {
// merge with existing timeouts
let merged = Object.assign(this.timeouts.toJSON(), cmd.parameters);
this.timeouts = Timeouts.fromJSON(merged);
};
/** Single tap. */
GeckoDriver.prototype.singleTap = async function(cmd) {
assert.open(this.getBrowsingContext());
let { id, x, y } = cmd.parameters;
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
await this.getActor().singleTap(webEl, x, y, this.capabilities);
return;
}
switch (this.context) {
case Context.Chrome:
throw new error.UnsupportedOperationError(
"Command 'singleTap' is not yet available in chrome context"
);
case Context.Content:
await this.listener.singleTap(webEl, x, y, this.capabilities);
break;
}
};
/**
* Perform a series of grouped actions at the specified points in time.
*
* @param {Array.<?>} actions
* Array of objects that each represent an action sequence.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not yet available in current context.
*/
GeckoDriver.prototype.performActions = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
const actions = cmd.parameters.actions;
if (MarionettePrefs.useActors) {
await this.getActor().performActions(actions, this.capabilities);
return;
}
assert.content(
this.context,
"Command 'performActions' is not yet available in chrome context"
);
await this.listener.performActions({ actions }, this.capabilities);
};
/**
* Release all the keys and pointer buttons that are currently depressed.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.releaseActions = async function() {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
if (MarionettePrefs.useActors) {
await this.getActor().releaseActions();
return;
}
assert.content(
this.context,
"Command 'releaseActions' is not yet available in chrome context"
);
await this.listener.releaseActions();
};
/**
* Find an element using the indicated search strategy.
*
* @param {string} using
* Indicates which search method to use.
* @param {string} value
* Value the client is looking for.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.findElement = async function(cmd) {
const { element: el, using, value } = cmd.parameters;
if (!SUPPORTED_STRATEGIES.has(using)) {
throw new error.InvalidSelectorError(`Strategy not supported: ${using}`);
}
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let startNode;
if (typeof el != "undefined") {
startNode = WebElement.fromUUID(el, this.context);
}
let opts = {
startNode,
timeout: this.timeouts.implicit,
all: false,
};
if (MarionettePrefs.useActors) {
return this.getActor().findElement(using, value, opts);
}
switch (this.context) {
case Context.Chrome:
let container = { frame: this.getCurrentWindow() };
if (opts.startNode) {
opts.startNode = this.curBrowser.seenEls.get(opts.startNode);
}
let el = await element.find(container, using, value, opts);
return this.curBrowser.seenEls.add(el);
case Context.Content:
return this.listener.findElementContent(using, value, opts);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Find elements using the indicated search strategy.
*
* @param {string} using
* Indicates which search method to use.
* @param {string} value
* Value the client is looking for.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
*/
GeckoDriver.prototype.findElements = async function(cmd) {
const { element: el, using, value } = cmd.parameters;
if (!SUPPORTED_STRATEGIES.has(using)) {
throw new error.InvalidSelectorError(`Strategy not supported: ${using}`);
}
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let startNode;
if (typeof el != "undefined") {
startNode = WebElement.fromUUID(el, this.context);
}
let opts = {
startNode,
timeout: this.timeouts.implicit,
all: true,
};
if (MarionettePrefs.useActors) {
return this.getActor().findElements(using, value, opts);
}
switch (this.context) {
case Context.Chrome:
let container = { frame: this.getCurrentWindow() };
if (startNode) {
opts.startNode = this.curBrowser.seenEls.get(opts.startNode);
}
let els = await element.find(container, using, value, opts);
return this.curBrowser.seenEls.addAll(els);
case Context.Content:
return this.listener.findElementsContent(using, value, opts);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Return the active element in the document.
*
* @return {WebElement}
* Active element of the current browsing context's document
* element, if the document element is non-null.
*
* @throws {NoSuchElementError}
* If the document does not have an active element, i.e. if
* its document element has been deleted.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.getActiveElement = async function() {
assert.content(this.context);
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
if (MarionettePrefs.useActors) {
return this.getActor().getActiveElement();
}
return this.listener.getActiveElement();
};
/**
* Send click event to element.
*
* @param {string} id
* Reference ID to the element that will be clicked.
*
* @throws {InvalidArgumentError}
* If element <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.clickElement = async function(cmd) {
const browsingContext = assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
const actor = this.getActor();
const loadEventExpected = navigate.isLoadEventExpected(
await this._getCurrentURL(),
{
browsingContext,
target: await actor.getElementAttribute(webEl, "target"),
}
);
await navigate.waitForNavigationCompleted(
this,
() => actor.clickElement(webEl, this.capabilities),
{
loadEventExpected,
// The click might trigger a navigation, so don't count on it.
requireBeforeUnload: false,
}
);
return;
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
await interaction.clickElement(el, this.a11yChecks);
break;
case Context.Content:
const loadEventExpected = navigate.isLoadEventExpected(
await this._getCurrentURL(),
{
browsingContext,
target: this.listener.getElementAttribute(webEl, "target"),
}
);
await navigate.waitForNavigationCompleted(
this,
() => this.listener.clickElement(webEl, this.capabilities),
{
loadEventExpected,
// The click might trigger a navigation, so don't count on it.
requireBeforeUnload: false,
}
);
break;
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Get a given attribute of an element.
*
* @param {string} id
* Web element reference ID to the element that will be inspected.
* @param {string} name
* Name of the attribute which value to retrieve.
*
* @return {string}
* Value of the attribute.
*
* @throws {InvalidArgumentError}
* If <var>id</var> or <var>name</var> are not strings.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementAttribute = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
const id = assert.string(cmd.parameters.id);
const name = assert.string(cmd.parameters.name);
const webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementAttribute(webEl, name);
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
return el.getAttribute(name);
case Context.Content:
return this.listener.getElementAttribute(webEl, name);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Returns the value of a property associated with given element.
*
* @param {string} id
* Web element reference ID to the element that will be inspected.
* @param {string} name
* Name of the property which value to retrieve.
*
* @return {string}
* Value of the property.
*
* @throws {InvalidArgumentError}
* If <var>id</var> or <var>name</var> are not strings.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementProperty = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
const id = assert.string(cmd.parameters.id);
const name = assert.string(cmd.parameters.name);
const webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementProperty(webEl, name);
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
return evaluate.toJSON(el[name], this.curBrowser.seenEls);
case Context.Content:
return this.listener.getElementProperty(webEl, name);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Get the text of an element, if any. Includes the text of all child
* elements.
*
* @param {string} id
* Reference ID to the element that will be inspected.
*
* @return {string}
* Element's text "as rendered".
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementText = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementText(webEl);
}
switch (this.context) {
case Context.Chrome:
// for chrome, we look at text nodes, and any node with a "label" field
let el = this.curBrowser.seenEls.get(webEl);
let lines = [];
this.getVisibleText(el, lines);
return lines.join("\n");
case Context.Content:
return this.listener.getElementText(webEl);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Get the tag name of the element.
*
* @param {string} id
* Reference ID to the element that will be inspected.
*
* @return {string}
* Local tag name of element.
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementTagName = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementTagName(webEl);
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
return el.tagName.toLowerCase();
case Context.Content:
return this.listener.getElementTagName(webEl);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Check if element is displayed.
*
* @param {string} id
* Reference ID to the element that will be inspected.
*
* @return {boolean}
* True if displayed, false otherwise.
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.isElementDisplayed = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().isElementDisplayed(webEl, this.capabilities);
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
return interaction.isElementDisplayed(el, this.a11yChecks);
case Context.Content:
return this.listener.isElementDisplayed(webEl, this.capabilities);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Return the property of the computed style of an element.
*
* @param {string} id
* Reference ID to the element that will be checked.
* @param {string} propertyName
* CSS rule that is being requested.
*
* @return {string}
* Value of |propertyName|.
*
* @throws {InvalidArgumentError}
* If <var>id</var> or <var>propertyName</var> are not strings.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementValueOfCssProperty = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let prop = assert.string(cmd.parameters.propertyName);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementValueOfCssProperty(webEl, prop);
}
switch (this.context) {
case Context.Chrome:
const win = this.getCurrentWindow();
const el = this.curBrowser.seenEls.get(webEl);
const style = win.document.defaultView.getComputedStyle(el);
return style.getPropertyValue(prop);
case Context.Content:
return this.listener.getElementValueOfCssProperty(webEl, prop);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Check if element is enabled.
*
* @param {string} id
* Reference ID to the element that will be checked.
*
* @return {boolean}
* True if enabled, false if disabled.
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.isElementEnabled = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().isElementEnabled(webEl, this.capabilities);
}
switch (this.context) {
case Context.Chrome:
// Selenium atom doesn't quite work here
let el = this.curBrowser.seenEls.get(webEl);
return interaction.isElementEnabled(el, this.a11yChecks);
case Context.Content:
return this.listener.isElementEnabled(webEl, this.capabilities);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Check if element is selected.
*
* @param {string} id
* Reference ID to the element that will be checked.
*
* @return {boolean}
* True if selected, false if unselected.
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.isElementSelected = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().isElementSelected(webEl, this.capabilities);
}
switch (this.context) {
case Context.Chrome:
// Selenium atom doesn't quite work here
let el = this.curBrowser.seenEls.get(webEl);
return interaction.isElementSelected(el, this.a11yChecks);
case Context.Content:
return this.listener.isElementSelected(webEl, this.capabilities);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.getElementRect = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
return this.getActor().getElementRect(webEl);
}
switch (this.context) {
case Context.Chrome:
const win = this.getCurrentWindow();
const el = this.curBrowser.seenEls.get(webEl);
const rect = el.getBoundingClientRect();
return {
x: rect.x + win.pageXOffset,
y: rect.y + win.pageYOffset,
width: rect.width,
height: rect.height,
};
case Context.Content:
return this.listener.getElementRect(webEl);
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Send key presses to element after focusing on it.
*
* @param {string} id
* Reference ID to the element that will be checked.
* @param {string} text
* Value to send to the element.
*
* @throws {InvalidArgumentError}
* If `id` or `text` are not strings.
* @throws {NoSuchElementError}
* If element represented by reference `id` is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.sendKeysToElement = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let text = assert.string(cmd.parameters.text);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
await this.getActor().sendKeysToElement(webEl, text, this.capabilities);
return;
}
switch (this.context) {
case Context.Chrome:
let el = this.curBrowser.seenEls.get(webEl);
await interaction.sendKeysToElement(el, text, {
accessibilityChecks: this.a11yChecks,
});
break;
case Context.Content:
await this.listener.sendKeysToElement(webEl, text, this.capabilities);
break;
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Clear the text of an element.
*
* @param {string} id
* Reference ID to the element that will be cleared.
*
* @throws {InvalidArgumentError}
* If <var>id</var> is not a string.
* @throws {NoSuchElementError}
* If element represented by reference <var>id</var> is unknown.
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.clearElement = async function(cmd) {
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let id = assert.string(cmd.parameters.id);
let webEl = WebElement.fromUUID(id, this.context);
if (MarionettePrefs.useActors) {
await this.getActor().clearElement(webEl);
return;
}
switch (this.context) {
case Context.Chrome:
// the selenium atom doesn't work here
let el = this.curBrowser.seenEls.get(webEl);
if (el.nodeName == "input" && el.type == "text") {
el.value = "";
} else if (el.nodeName == "checkbox") {
el.checked = false;
}
break;
case Context.Content:
await this.listener.clearElement(webEl);
break;
default:
throw new TypeError(`Unknown context: ${this.context}`);
}
};
/**
* Add a single cookie to the cookie store associated with the active
* document's address.
*
* @param {Map.<string, (string|number|boolean)> cookie
* Cookie object.
*
* @throws {InvalidCookieDomainError}
* If <var>cookie</var> is for a different domain than the active
* document's host.
* @throws {NoSuchWindowError}
* Bbrowsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.addCookie = async function(cmd) {
assert.content(this.context);
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let { protocol, hostname } = await this._getCurrentURL();
const networkSchemes = ["ftp:", "http:", "https:"];
if (!networkSchemes.includes(protocol)) {
throw new error.InvalidCookieDomainError("Document is cookie-averse");
}
let newCookie = cookie.fromJSON(cmd.parameters.cookie);
cookie.add(newCookie, { restrictToHost: hostname, protocol });
};
/**
* Get all the cookies for the current domain.
*
* This is the equivalent of calling <code>document.cookie</code> and
* parsing the result.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.getCookies = async function() {
assert.content(this.context);
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let { hostname, pathname } = await this._getCurrentURL();
return [...cookie.iter(hostname, pathname)];
};
/**
* Delete all cookies that are visible to a document.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.deleteAllCookies = async function() {
assert.content(this.context);
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let { hostname, pathname } = await this._getCurrentURL();
for (let toDelete of cookie.iter(hostname, pathname)) {
cookie.remove(toDelete);
}
};
/**
* Delete a cookie by name.
*
* @throws {NoSuchWindowError}
* Browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available in current context.
*/
GeckoDriver.prototype.deleteCookie = async function(cmd) {
assert.content(this.context);
assert.open(this.getBrowsingContext());
await this._handleUserPrompts();
let { hostname, pathname } = await this._getCurrentURL();
let name = assert.string(cmd.parameters.name);
for (let c of cookie.iter(hostname, pathname)) {
if (c.name === name) {
cookie.remove(c);
}
}
};
/**
* Open a new top-level browsing context.
*
* @param {string=} type
* Optional type of the new top-level browsing context. Can be one of
* `tab` or `window`. Defaults to `tab`.
* @param {boolean=} focus
* Optional flag if the new top-level browsing context should be opened
* in foreground (focused) or background (not focused). Defaults to false.
* @param {boolean=} private
* Optional flag, which gets only evaluated for type `window`. True if the
* new top-level browsing context should be a private window.
* Defaults to false.
*
* @return {Object.<string, string>}
* Handle and type of the new browsing context.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.newWindow = async function(cmd) {
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
let focus = false;
if (typeof cmd.parameters.focus != "undefined") {
focus = assert.boolean(
cmd.parameters.focus,
pprint`Expected "focus" to be a boolean, got ${cmd.parameters.focus}`
);
}
let isPrivate = false;
if (typeof cmd.parameters.private != "undefined") {
isPrivate = assert.boolean(
cmd.parameters.private,
pprint`Expected "private" to be a boolean, got ${cmd.parameters.private}`
);
}
let type;
if (typeof cmd.parameters.type != "undefined") {
type = assert.string(
cmd.parameters.type,
pprint`Expected "type" to be a string, got ${cmd.parameters.type}`
);
}
// If an invalid or no type has been specified default to a tab.
if (typeof type == "undefined" || !["tab", "window"].includes(type)) {
type = "tab";
}
let contentBrowser;
let onBrowserContentLoaded;
if (MarionettePrefs.useActors) {
// Actors need the new window to be loaded to safely execute queries.
// Wait until a load event is dispatched for the new browsing context.
onBrowserContentLoaded = waitForLoadEvent(
"pageshow",
() => contentBrowser?.browsingContext
);
}
switch (type) {
case "window":
let win = await this.curBrowser.openBrowserWindow(focus, isPrivate);
contentBrowser = browser.getTabBrowser(win).selectedBrowser;
break;
default:
// To not fail if a new type gets added in the future, make opening
// a new tab the default action.
let tab = await this.curBrowser.openTab(focus);
contentBrowser = browser.getBrowserForTab(tab);
}
await onBrowserContentLoaded;
// Even with the framescript registered, the browser might not be known to
// the parent process yet. Wait until it is available.
// TODO: Fix by using `Browser:Init` or equivalent on bug 1311041
let windowId = await new PollPromise((resolve, reject) => {
let id = this.getIdForBrowser(contentBrowser);
this.windowHandles.includes(id) ? resolve(id) : reject();
});
return { handle: windowId.toString(), type };
};
/**
* Close the currently selected tab/window.
*
* With multiple open tabs present the currently selected tab will
* be closed. Otherwise the window itself will be closed. If it is the
* last window currently open, the window will not be closed to prevent
* a shutdown of the application. Instead the returned list of window
* handles is empty.
*
* @return {Array.<string>}
* Unique window handles of remaining windows.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
*/
GeckoDriver.prototype.close = async function() {
assert.open(this.getBrowsingContext({ context: Context.Content, top: true }));
await this._handleUserPrompts();
let nwins = 0;
for (let win of this.windows) {
// For browser windows count the tabs. Otherwise take the window itself.
let tabbrowser = browser.getTabBrowser(win);
if (tabbrowser && tabbrowser.tabs) {
nwins += tabbrowser.tabs.length;
} else {
nwins += 1;
}
}
// If there is only one window left, do not close it. Instead return
// a faked empty array of window handles. This will instruct geckodriver
// to terminate the application.
if (nwins === 1) {
return [];
}
await this.curBrowser.closeTab();
this.contentBrowsingContext = null;
return this.windowHandles.map(String);
};
/**
* Close the currently selected chrome window.
*
* If it is the last window currently open, the chrome window will not be
* closed to prevent a shutdown of the application. Instead the returned
* list of chrome window handles is empty.
*
* @return {Array.<string>}
* Unique chrome window handles of remaining chrome windows.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.closeChromeWindow = async function() {
assert.firefox();
assert.open(this.getBrowsingContext({ context: Context.Chrome, top: true }));
let nwins = 0;
// eslint-disable-next-line
for (let _ of this.windows) {
nwins++;
}
// If there is only one window left, do not close it. Instead return
// a faked empty array of window handles. This will instruct geckodriver
// to terminate the application.
if (nwins == 1) {
return [];
}
await this.curBrowser.closeWindow();
this.chromeBrowsingContext = null;
this.contentBrowsingContext = null;
return this.chromeWindowHandles.map(String);
};
/** Delete Marionette session. */
GeckoDriver.prototype.deleteSession = function() {
if (MarionettePrefs.useActors) {
clearActionInputState();
clearElementIdCache();
unregisterCommandsActor();
unregisterEventsActor();
} else if (this.curBrowser !== null) {
// frame scripts can be safely reused
MarionettePrefs.contentListener = false;
globalMessageManager.broadcastAsyncMessage("Marionette:Session:Delete");
globalMessageManager.broadcastAsyncMessage("Marionette:Deregister");
for (let win of this.windows) {
if (win.messageManager) {
win.messageManager.removeDelayedFrameScript(FRAME_SCRIPT);
} else {
logger.error(
`Could not remove listener from page ${win.location.href}`
);
}
}
}
// reset to the top-most frame, and clear browsing context references
this.mainFrame = null;
this.chromeBrowsingContext = null;
this.contentBrowsingContext = null;
if (this.dialogObserver) {
this.dialogObserver.cleanup();
this.dialogObserver = null;
}
try {
Services.obs.removeObserver(this, "browsing-context-attached");
} catch (e) {}
this.sandboxes.clear();
allowAllCerts.disable();
this.sessionID = null;
this.capabilities = new Capabilities();
};
/**
* Takes a screenshot of a web element, current frame, or viewport.
*
* The screen capture is returned as a lossless PNG image encoded as
* a base 64 string.
*
* If called in the content context, the |id| argument is not null and
* refers to a present and visible web element's ID, the capture area will
* be limited to the bounding box of that element. Otherwise, the capture
* area will be the bounding box of the current frame.
*
* If called in the chrome context, the screenshot will always represent
* the entire viewport.
*
* @param {string=} id
* Optional web element reference to take a screenshot of.
* If undefined, a screenshot will be taken of the document element.
* @param {boolean=} full
* True to take a screenshot of the entire document element. Is only
* considered if <var>id</var> is not defined. Defaults to true.
* @param {boolean=} hash
* True if the user requests a hash of the image data. Defaults to false.
* @param {boolean=} scroll
* Scroll to element if |id| is provided. Defaults to true.
*
* @return {string}
* If <var>hash</var> is false, PNG image encoded as Base64 encoded
* string. If <var>hash</var> is true, hex digest of the SHA-256
* hash of the Base64 encoded string.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.takeScreenshot = async function(cmd) {
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
let { id, full, hash, scroll } = cmd.parameters;
let format = hash ? capture.Format.Hash : capture.Format.Base64;
full = typeof full == "undefined" ? true : full;
scroll = typeof scroll == "undefined" ? true : scroll;
let webEl = id ? WebElement.fromUUID(id, this.context) : null;
// Only consider full screenshot if no element has been specified
full = webEl ? false : full;
if (MarionettePrefs.useActors) {
return this.getActor().takeScreenshot(webEl, format, full, scroll);
}
const win = this.getCurrentWindow();
let rect;
switch (this.context) {
case Context.Chrome:
if (id) {
let el = this.curBrowser.seenEls.get(webEl, win);
rect = el.getBoundingClientRect();
} else if (full) {
const docEl = win.document.documentElement;
rect = new DOMRect(0, 0, docEl.scrollWidth, docEl.scrollHeight);
} else {
// viewport
rect = new win.DOMRect(
win.pageXOffset,
win.pageYOffset,
win.innerWidth,
win.innerHeight
);
}
break;
case Context.Content:
rect = await this.listener.getScreenshotRect({ el: webEl, full, scroll });
break;
}
// If no element has been specified use the top-level browsing context.
// Otherwise use the browsing context from the currently selected frame.
const browsingContext = this.getBrowsingContext({ top: !webEl });
let canvas = await capture.canvas(
win,
browsingContext,
rect.x,
rect.y,
rect.width,
rect.height
);
switch (format) {
case capture.Format.Hash:
return capture.toHash(canvas);
case capture.Format.Base64:
return capture.toBase64(canvas);
}
throw new TypeError(`Unknown context: ${this.context}`);
};
/**
* Get the current browser orientation.
*
* Will return one of the valid primary orientation values
* portrait-primary, landscape-primary, portrait-secondary, or
* landscape-secondary.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.getScreenOrientation = function() {
assert.fennec();
assert.open(this.getBrowsingContext({ top: true }));
const win = this.getCurrentWindow();
return win.screen.mozOrientation;
};
/**
* Set the current browser orientation.
*
* The supplied orientation should be given as one of the valid
* orientation values. If the orientation is unknown, an error will
* be raised.
*
* Valid orientations are "portrait" and "landscape", which fall
* back to "portrait-primary" and "landscape-primary" respectively,
* and "portrait-secondary" as well as "landscape-secondary".
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.setScreenOrientation = function(cmd) {
assert.fennec();
assert.open(this.getBrowsingContext({ top: true }));
const ors = [
"portrait",
"landscape",
"portrait-primary",
"landscape-primary",
"portrait-secondary",
"landscape-secondary",
];
let or = String(cmd.parameters.orientation);
assert.string(or);
let mozOr = or.toLowerCase();
if (!ors.includes(mozOr)) {
throw new error.InvalidArgumentError(`Unknown screen orientation: ${or}`);
}
const win = this.getCurrentWindow();
if (!win.screen.mozLockOrientation(mozOr)) {
throw new error.WebDriverError(`Unable to set screen orientation: ${or}`);
}
};
/**
* Synchronously minimizes the user agent window as if the user pressed
* the minimize button.
*
* No action is taken if the window is already minimized.
*
* Not supported on Fennec.
*
* @return {Object.<string, number>}
* Window rect and window state.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available for current application.
*/
GeckoDriver.prototype.minimizeWindow = async function() {
assert.firefox();
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
const win = this.getCurrentWindow();
switch (WindowState.from(win.windowState)) {
case WindowState.Fullscreen:
await exitFullscreen(win);
break;
case WindowState.Maximized:
await restoreWindow(win);
break;
}
if (WindowState.from(win.windowState) != WindowState.Minimized) {
let cb;
let observer = new WebElementEventTarget(this.curBrowser.messageManager);
// Use a timed promise to abort if no window manager is present
await new TimedPromise(
resolve => {
cb = new DebounceCallback(resolve);
observer.addEventListener("visibilitychange", cb);
win.minimize();
},
{ throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER }
);
observer.removeEventListener("visibilitychange", cb);
await new IdlePromise(win);
}
return this.curBrowser.rect;
};
/**
* Synchronously maximizes the user agent window as if the user pressed
* the maximize button.
*
* No action is taken if the window is already maximized.
*
* Not supported on Fennec.
*
* @return {Object.<string, number>}
* Window rect.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available for current application.
*/
GeckoDriver.prototype.maximizeWindow = async function() {
assert.firefox();
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
const win = this.getCurrentWindow();
switch (WindowState.from(win.windowState)) {
case WindowState.Fullscreen:
await exitFullscreen(win);
break;
case WindowState.Minimized:
await restoreWindow(win);
break;
}
if (WindowState.from(win.windowState) != WindowState.Maximized) {
let cb;
// Use a timed promise to abort if no window manager is present
await new TimedPromise(
resolve => {
cb = new DebounceCallback(resolve);
win.addEventListener("sizemodechange", cb);
win.maximize();
},
{ throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER }
);
win.removeEventListener("sizemodechange", cb);
await new IdlePromise(win);
}
return this.curBrowser.rect;
};
/**
* Synchronously sets the user agent window to full screen as if the user
* had done "View > Enter Full Screen".
*
* No action is taken if the window is already in full screen mode.
*
* Not supported on Fennec.
*
* @return {Map.<string, number>}
* Window rect.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnexpectedAlertOpenError}
* A modal dialog is open, blocking this operation.
* @throws {UnsupportedOperationError}
* Not available for current application.
*/
GeckoDriver.prototype.fullscreenWindow = async function() {
assert.firefox();
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
const win = this.getCurrentWindow();
switch (WindowState.from(win.windowState)) {
case WindowState.Maximized:
case WindowState.Minimized:
await restoreWindow(win);
break;
}
if (WindowState.from(win.windowState) != WindowState.Fullscreen) {
let cb;
// Use a timed promise to abort if no window manager is present
await new TimedPromise(
resolve => {
cb = new DebounceCallback(resolve);
win.addEventListener("sizemodechange", cb);
win.fullScreen = true;
},
{ throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER }
);
win.removeEventListener("sizemodechange", cb);
}
await new IdlePromise(win);
return this.curBrowser.rect;
};
/**
* Dismisses a currently displayed tab modal, or returns no such alert if
* no modal is displayed.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.dismissDialog = async function() {
assert.open(this.getBrowsingContext({ top: true }));
this._checkIfAlertIsPresent();
const win = this.getCurrentWindow();
const dialogClosed = waitForEvent(win, "DOMModalDialogClosed");
const { button0, button1 } = this.dialog.ui;
(button1 ? button1 : button0).click();
await dialogClosed;
await new IdlePromise(win);
};
/**
* Accepts a currently displayed tab modal, or returns no such alert if
* no modal is displayed.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.acceptDialog = async function() {
assert.open(this.getBrowsingContext({ top: true }));
this._checkIfAlertIsPresent();
const win = this.getCurrentWindow();
const dialogClosed = waitForEvent(win, "DOMModalDialogClosed");
const { button0 } = this.dialog.ui;
button0.click();
await dialogClosed;
await new IdlePromise(win);
};
/**
* Returns the message shown in a currently displayed modal, or returns
* a no such alert error if no modal is currently displayed.
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.getTextFromDialog = function() {
assert.open(this.getBrowsingContext({ top: true }));
this._checkIfAlertIsPresent();
return this.dialog.ui.infoBody.textContent;
};
/**
* Set the user prompt's value field.
*
* Sends keys to the input field of a currently displayed modal, or
* returns a no such alert error if no modal is currently displayed. If
* a tab modal is currently displayed but has no means for text input,
* an element not visible error is returned.
*
* @param {string} text
* Input to the user prompt's value field.
*
* @throws {ElementNotInteractableError}
* If the current user prompt is an alert or confirm.
* @throws {NoSuchAlertError}
* If there is no current user prompt.
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
* @throws {UnsupportedOperationError}
* If the current user prompt is something other than an alert,
* confirm, or a prompt.
*/
GeckoDriver.prototype.sendKeysToDialog = async function(cmd) {
assert.open(this.getBrowsingContext({ top: true }));
this._checkIfAlertIsPresent();
let text = assert.string(cmd.parameters.text);
let promptType = this.dialog.args.promptType;
switch (promptType) {
case "alert":
case "confirm":
throw new error.ElementNotInteractableError(
`User prompt of type ${promptType} is not interactable`
);
case "prompt":
break;
default:
await this.dismissDialog();
throw new error.UnsupportedOperationError(
`User prompt of type ${promptType} is not supported`
);
}
// see toolkit/components/prompts/content/commonDialog.js
let { loginTextbox } = this.dialog.ui;
loginTextbox.value = text;
};
GeckoDriver.prototype._checkIfAlertIsPresent = function() {
if (!this.dialog || !this.dialog.ui) {
throw new error.NoSuchAlertError();
}
};
GeckoDriver.prototype._handleUserPrompts = async function() {
if (!this.dialog || !this.dialog.ui) {
return;
}
let { textContent } = this.dialog.ui.infoBody;
let behavior = this.capabilities.get("unhandledPromptBehavior");
switch (behavior) {
case UnhandledPromptBehavior.Accept:
await this.acceptDialog();
break;
case UnhandledPromptBehavior.AcceptAndNotify:
await this.acceptDialog();
throw new error.UnexpectedAlertOpenError(
`Accepted user prompt dialog: ${textContent}`
);
case UnhandledPromptBehavior.Dismiss:
await this.dismissDialog();
break;
case UnhandledPromptBehavior.DismissAndNotify:
await this.dismissDialog();
throw new error.UnexpectedAlertOpenError(
`Dismissed user prompt dialog: ${textContent}`
);
case UnhandledPromptBehavior.Ignore:
throw new error.UnexpectedAlertOpenError(
"Encountered unhandled user prompt dialog"
);
default:
throw new TypeError(`Unknown unhandledPromptBehavior "${behavior}"`);
}
};
/**
* Enables or disables accepting new socket connections.
*
* By calling this method with `false` the server will not accept any
* further connections, but existing connections will not be forcible
* closed. Use `true` to re-enable accepting connections.
*
* Please note that when closing the connection via the client you can
* end-up in a non-recoverable state if it hasn't been enabled before.
*
* This method is used for custom in application shutdowns via
* marionette.quit() or marionette.restart(), like File -> Quit.
*
* @param {boolean} state
* True if the server should accept new socket connections.
*/
GeckoDriver.prototype.acceptConnections = function(cmd) {
assert.boolean(cmd.parameters.value);
this._server.acceptConnections = cmd.parameters.value;
};
/**
* Quits the application with the provided flags.
*
* Marionette will stop accepting new connections before ending the
* current session, and finally attempting to quit the application.
*
* Optional {@link nsIAppStartup} flags may be provided as
* an array of masks, and these will be combined by ORing
* them with a bitmask. The available masks are defined in
* https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIAppStartup.
*
* Crucially, only one of the *Quit flags can be specified. The |eRestart|
* flag may be bit-wise combined with one of the *Quit flags to cause
* the application to restart after it quits.
*
* @param {Array.<string>=} flags
* Constant name of masks to pass to |Services.startup.quit|.
* If empty or undefined, |nsIAppStartup.eAttemptQuit| is used.
*
* @return {string}
* Explaining the reason why the application quit. This can be
* in response to a normal shutdown or restart, yielding "shutdown"
* or "restart", respectively.
*
* @throws {InvalidArgumentError}
* If <var>flags</var> contains unknown or incompatible flags,
* for example multiple Quit flags.
*/
GeckoDriver.prototype.quit = async function(cmd) {
const quits = ["eConsiderQuit", "eAttemptQuit", "eForceQuit"];
let flags = [];
if (typeof cmd.parameters.flags != "undefined") {
flags = assert.array(cmd.parameters.flags);
}
let quitSeen;
let mode = 0;
if (flags.length > 0) {
for (let k of flags) {
assert.in(k, Ci.nsIAppStartup);
if (quits.includes(k)) {
if (quitSeen) {
throw new error.InvalidArgumentError(
`${k} cannot be combined with ${quitSeen}`
);
}
quitSeen = k;
}
mode |= Ci.nsIAppStartup[k];
}
} else {
mode = Ci.nsIAppStartup.eAttemptQuit;
}
this._server.acceptConnections = false;
this.deleteSession();
// delay response until the application is about to quit
let quitApplication = waitForObserverTopic("quit-application");
Services.startup.quit(mode);
return { cause: (await quitApplication).data };
};
GeckoDriver.prototype.installAddon = function(cmd) {
assert.desktop();
let path = cmd.parameters.path;
let temp = cmd.parameters.temporary || false;
if (
typeof path == "undefined" ||
typeof path != "string" ||
typeof temp != "boolean"
) {
throw new error.InvalidArgumentError();
}
return Addon.install(path, temp);
};
GeckoDriver.prototype.uninstallAddon = function(cmd) {
assert.firefox();
let id = cmd.parameters.id;
if (typeof id == "undefined" || typeof id != "string") {
throw new error.InvalidArgumentError();
}
return Addon.uninstall(id);
};
/** Receives all messages from content messageManager. */
/* eslint-disable consistent-return */
GeckoDriver.prototype.receiveMessage = function(message) {
switch (message.name) {
case "Marionette:switchedToFrame":
this.contentBrowsingContext = BrowsingContext.get(
message.json.browsingContextId
);
break;
case "Marionette:Register":
this.registerBrowser(message.target);
return { frameId: message.json.frameId };
case "Marionette:ListenersAttached":
if (message.json.frameId === this.curBrowser.curFrameId) {
const browsingContext = BrowsingContext.get(message.json.frameId);
// If the framescript for the current content browsing context
// has been re-attached due to a remoteness change (the browserId is
// always persistent) then track the new browsing context.
if (
browsingContext.browserId == this.contentBrowsingContext?.browserId
) {
logger.trace(
"Detected remoteness change. New browsing context: " +
browsingContext.id
);
this.contentBrowsingContext = browsingContext;
}
}
break;
}
};
/* eslint-enable consistent-return */
/**
* Retrieve the localized string for the specified entity id.
*
* Example:
* localizeEntity(["chrome://branding/locale/brand.dtd"], "brandShortName")
*
* @param {Array.<string>} urls
* Array of .dtd URLs.
* @param {string} id
* The ID of the entity to retrieve the localized string for.
*
* @return {string}
* The localized string for the requested entity.
*/
GeckoDriver.prototype.localizeEntity = function(cmd) {
let { urls, id } = cmd.parameters;
if (!Array.isArray(urls)) {
throw new error.InvalidArgumentError(
"Value of `urls` should be of type 'Array'"
);
}
if (typeof id != "string") {
throw new error.InvalidArgumentError(
"Value of `id` should be of type 'string'"
);
}
return l10n.localizeEntity(urls, id);
};
/**
* Retrieve the localized string for the specified property id.
*
* Example:
*
* localizeProperty(
* ["chrome://global/locale/findbar.properties"], "FastFind");
*
* @param {Array.<string>} urls
* Array of .properties URLs.
* @param {string} id
* The ID of the property to retrieve the localized string for.
*
* @return {string}
* The localized string for the requested property.
*/
GeckoDriver.prototype.localizeProperty = function(cmd) {
let { urls, id } = cmd.parameters;
if (!Array.isArray(urls)) {
throw new error.InvalidArgumentError(
"Value of `urls` should be of type 'Array'"
);
}
if (typeof id != "string") {
throw new error.InvalidArgumentError(
"Value of `id` should be of type 'string'"
);
}
return l10n.localizeProperty(urls, id);
};
/**
* Initialize the reftest mode
*/
GeckoDriver.prototype.setupReftest = async function(cmd) {
if (this._reftest) {
throw new error.UnsupportedOperationError(
"Called reftest:setup with a reftest session already active"
);
}
let {
urlCount = {},
screenshot = "unexpected",
isPrint = false,
} = cmd.parameters;
if (!["always", "fail", "unexpected"].includes(screenshot)) {
throw new error.InvalidArgumentError(
"Value of `screenshot` should be 'always', 'fail' or 'unexpected'"
);
}
this._reftest = new reftest.Runner(this);
this._reftest.setup(urlCount, screenshot, isPrint);
};
/** Run a reftest. */
GeckoDriver.prototype.runReftest = async function(cmd) {
let {
test,
references,
expected,
timeout,
width,
height,
pageRanges,
} = cmd.parameters;
if (!this._reftest) {
throw new error.UnsupportedOperationError(
"Called reftest:run before reftest:start"
);
}
assert.string(test);
assert.string(expected);
assert.array(references);
return {
value: await this._reftest.run(
test,
references,
expected,
timeout,
pageRanges,
width,
height
),
};
};
/**
* End a reftest run.
*
* Closes the reftest window (without changing the current window handle),
* and removes cached canvases.
*/
GeckoDriver.prototype.teardownReftest = function() {
if (!this._reftest) {
throw new error.UnsupportedOperationError(
"Called reftest:teardown before reftest:start"
);
}
this._reftest.teardown();
this._reftest = null;
};
/**
* Print page as PDF.
*
* @param {boolean=} landscape
* Paper orientation. Defaults to false.
* @param {number=} margin.bottom
* Bottom margin in cm. Defaults to 1cm (~0.4 inches).
* @param {number=} margin.left
* Left margin in cm. Defaults to 1cm (~0.4 inches).
* @param {number=} margin.right
* Right margin in cm. Defaults to 1cm (~0.4 inches).
* @param {number=} margin.top
* Top margin in cm. Defaults to 1cm (~0.4 inches).
* @param {string=} pageRanges (not supported)
* Paper ranges to print, e.g., '1-5, 8, 11-13'.
* Defaults to the empty string, which means print all pages.
* @param {number=} page.height
* Paper height in cm. Defaults to US letter height (11 inches / 27.94cm)
* @param {number=} page.width
* Paper width in cm. Defaults to US letter width (8.5 inches / 21.59cm)
* @param {boolean=} shrinkToFit
* Whether or not to override page size as defined by CSS.
* Defaults to true, in which case the content will be scaled
* to fit the paper size.
* @param {boolean=} printBackground
* Print background graphics. Defaults to false.
* @param {number=} scale
* Scale of the webpage rendering. Defaults to 1.
*
* @return {string}
* Base64 encoded PDF representing printed document
*
* @throws {NoSuchWindowError}
* Top-level browsing context has been discarded.
*/
GeckoDriver.prototype.print = async function(cmd) {
assert.content(this.context);
assert.open(this.getBrowsingContext({ top: true }));
await this._handleUserPrompts();
const settings = print.addDefaultSettings(cmd.parameters);
for (let prop of ["top", "bottom", "left", "right"]) {
assert.positiveNumber(
settings.margin[prop],
pprint`margin.${prop} is not a positive number`
);
}
for (let prop of ["width", "height"]) {
assert.positiveNumber(
settings.page[prop],
pprint`page.${prop} is not a positive number`
);
}
assert.positiveNumber(
settings.scale,
`scale ${settings.scale} is not a positive number`
);
assert.that(
s => s >= print.minScaleValue && settings.scale <= print.maxScaleValue,
`scale ${settings.scale} is outside the range ${print.minScaleValue}-${print.maxScaleValue}`
)(settings.scale);
assert.boolean(settings.shrinkToFit);
assert.boolean(settings.landscape);
assert.boolean(settings.printBackground);
const linkedBrowser = this.curBrowser.tab.linkedBrowser;
const filePath = await print.printToFile(
linkedBrowser,
linkedBrowser.outerWindowID,
settings
);
// return all data as a base64 encoded string
let bytes;
const file = await OS.File.open(filePath);
try {
bytes = await file.read();
} finally {
file.close();
await OS.File.remove(filePath);
}
// Each UCS2 character has an upper byte of 0 and a lower byte matching
// the binary data
return {
value: btoa(String.fromCharCode.apply(null, bytes)),
};
};
GeckoDriver.prototype.commands = {
// Marionette service
"Marionette:AcceptConnections": GeckoDriver.prototype.acceptConnections,
"Marionette:GetContext": GeckoDriver.prototype.getContext,
"Marionette:GetScreenOrientation": GeckoDriver.prototype.getScreenOrientation,
"Marionette:GetWindowType": GeckoDriver.prototype.getWindowType,
"Marionette:Quit": GeckoDriver.prototype.quit,
"Marionette:SetContext": GeckoDriver.prototype.setContext,
"Marionette:SetScreenOrientation": GeckoDriver.prototype.setScreenOrientation,
"Marionette:SingleTap": GeckoDriver.prototype.singleTap,
// Addon service
"Addon:Install": GeckoDriver.prototype.installAddon,
"Addon:Uninstall": GeckoDriver.prototype.uninstallAddon,
// L10n service
"L10n:LocalizeEntity": GeckoDriver.prototype.localizeEntity,
"L10n:LocalizeProperty": GeckoDriver.prototype.localizeProperty,
// Reftest service
"reftest:setup": GeckoDriver.prototype.setupReftest,
"reftest:run": GeckoDriver.prototype.runReftest,
"reftest:teardown": GeckoDriver.prototype.teardownReftest,
// WebDriver service
"WebDriver:AcceptAlert": GeckoDriver.prototype.acceptDialog,
"WebDriver:AcceptDialog": GeckoDriver.prototype.acceptDialog, // deprecated, but used in geckodriver (see also bug 1495063)
"WebDriver:AddCookie": GeckoDriver.prototype.addCookie,
"WebDriver:Back": GeckoDriver.prototype.goBack,
"WebDriver:CloseChromeWindow": GeckoDriver.prototype.closeChromeWindow,
"WebDriver:CloseWindow": GeckoDriver.prototype.close,
"WebDriver:DeleteAllCookies": GeckoDriver.prototype.deleteAllCookies,
"WebDriver:DeleteCookie": GeckoDriver.prototype.deleteCookie,
"WebDriver:DeleteSession": GeckoDriver.prototype.deleteSession,
"WebDriver:DismissAlert": GeckoDriver.prototype.dismissDialog,
"WebDriver:ElementClear": GeckoDriver.prototype.clearElement,
"WebDriver:ElementClick": GeckoDriver.prototype.clickElement,
"WebDriver:ElementSendKeys": GeckoDriver.prototype.sendKeysToElement,
"WebDriver:ExecuteAsyncScript": GeckoDriver.prototype.executeAsyncScript,
"WebDriver:ExecuteScript": GeckoDriver.prototype.executeScript,
"WebDriver:FindElement": GeckoDriver.prototype.findElement,
"WebDriver:FindElements": GeckoDriver.prototype.findElements,
"WebDriver:Forward": GeckoDriver.prototype.goForward,
"WebDriver:FullscreenWindow": GeckoDriver.prototype.fullscreenWindow,
"WebDriver:GetActiveElement": GeckoDriver.prototype.getActiveElement,
"WebDriver:GetAlertText": GeckoDriver.prototype.getTextFromDialog,
"WebDriver:GetCapabilities": GeckoDriver.prototype.getSessionCapabilities,
"WebDriver:GetChromeWindowHandle":
GeckoDriver.prototype.getChromeWindowHandle,
"WebDriver:GetChromeWindowHandles":
GeckoDriver.prototype.getChromeWindowHandles,
"WebDriver:GetCookies": GeckoDriver.prototype.getCookies,
"WebDriver:GetCurrentChromeWindowHandle":
GeckoDriver.prototype.getChromeWindowHandle,
"WebDriver:GetCurrentURL": GeckoDriver.prototype.getCurrentUrl,
"WebDriver:GetElementAttribute": GeckoDriver.prototype.getElementAttribute,
"WebDriver:GetElementCSSValue":
GeckoDriver.prototype.getElementValueOfCssProperty,
"WebDriver:GetElementProperty": GeckoDriver.prototype.getElementProperty,
"WebDriver:GetElementRect": GeckoDriver.prototype.getElementRect,
"WebDriver:GetElementTagName": GeckoDriver.prototype.getElementTagName,
"WebDriver:GetElementText": GeckoDriver.prototype.getElementText,
"WebDriver:GetPageSource": GeckoDriver.prototype.getPageSource,
"WebDriver:GetTimeouts": GeckoDriver.prototype.getTimeouts,
"WebDriver:GetTitle": GeckoDriver.prototype.getTitle,
"WebDriver:GetWindowHandle": GeckoDriver.prototype.getWindowHandle,
"WebDriver:GetWindowHandles": GeckoDriver.prototype.getWindowHandles,
"WebDriver:GetWindowRect": GeckoDriver.prototype.getWindowRect,
"WebDriver:IsElementDisplayed": GeckoDriver.prototype.isElementDisplayed,
"WebDriver:IsElementEnabled": GeckoDriver.prototype.isElementEnabled,
"WebDriver:IsElementSelected": GeckoDriver.prototype.isElementSelected,
"WebDriver:MinimizeWindow": GeckoDriver.prototype.minimizeWindow,
"WebDriver:MaximizeWindow": GeckoDriver.prototype.maximizeWindow,
"WebDriver:Navigate": GeckoDriver.prototype.navigateTo,
"WebDriver:NewSession": GeckoDriver.prototype.newSession,
"WebDriver:NewWindow": GeckoDriver.prototype.newWindow,
"WebDriver:PerformActions": GeckoDriver.prototype.performActions,
"WebDriver:Print": GeckoDriver.prototype.print,
"WebDriver:Refresh": GeckoDriver.prototype.refresh,
"WebDriver:ReleaseActions": GeckoDriver.prototype.releaseActions,
"WebDriver:SendAlertText": GeckoDriver.prototype.sendKeysToDialog,
"WebDriver:SetTimeouts": GeckoDriver.prototype.setTimeouts,
"WebDriver:SetWindowRect": GeckoDriver.prototype.setWindowRect,
"WebDriver:SwitchToFrame": GeckoDriver.prototype.switchToFrame,
"WebDriver:SwitchToParentFrame": GeckoDriver.prototype.switchToParentFrame,
"WebDriver:SwitchToWindow": GeckoDriver.prototype.switchToWindow,
"WebDriver:TakeScreenshot": GeckoDriver.prototype.takeScreenshot,
};
function getWindowId(win) {
return win.docShell.browsingContext.id;
}
async function exitFullscreen(win) {
let cb;
// Use a timed promise to abort if no window manager is present
await new TimedPromise(
resolve => {
cb = new DebounceCallback(resolve);
win.addEventListener("sizemodechange", cb);
win.fullScreen = false;
},
{ throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER }
);
win.removeEventListener("sizemodechange", cb);
}
async function restoreWindow(win) {
win.restore();
// Use a poll promise to abort if no window manager is present
await new PollPromise(
(resolve, reject) => {
if (WindowState.from(win.windowState) == WindowState.Normal) {
resolve();
} else {
reject();
}
},
{ timeout: TIMEOUT_NO_WINDOW_MANAGER }
);
}
|