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
|
/* 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/. */
/*
* This module implements a number of utilities useful for browser tests.
*
* All asynchronous helper methods should return promises, rather than being
* callback based.
*/
// This file uses ContentTask & frame scripts, where these are available.
/* global ContentTaskUtils */
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
import { ComponentUtils } from "resource://gre/modules/ComponentUtils.sys.mjs";
import { TestUtils } from "resource://testing-common/TestUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
ContentTask: "resource://testing-common/ContentTask.sys.mjs",
});
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
});
XPCOMUtils.defineLazyServiceGetters(lazy, {
ProtocolProxyService: [
"@mozilla.org/network/protocol-proxy-service;1",
"nsIProtocolProxyService",
],
});
const PROCESSSELECTOR_CONTRACTID = "@mozilla.org/ipc/processselector;1";
const OUR_PROCESSSELECTOR_CID = Components.ID(
"{f9746211-3d53-4465-9aeb-ca0d96de0253}"
);
const EXISTING_JSID = Cc[PROCESSSELECTOR_CONTRACTID];
const DEFAULT_PROCESSSELECTOR_CID = EXISTING_JSID
? Components.ID(EXISTING_JSID.number)
: null;
let gListenerId = 0;
// A process selector that always asks for a new process.
function NewProcessSelector() {}
NewProcessSelector.prototype = {
classID: OUR_PROCESSSELECTOR_CID,
QueryInterface: ChromeUtils.generateQI(["nsIContentProcessProvider"]),
provideProcess() {
return Ci.nsIContentProcessProvider.NEW_PROCESS;
},
};
let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
let selectorFactory =
ComponentUtils.generateSingletonFactory(NewProcessSelector);
registrar.registerFactory(OUR_PROCESSSELECTOR_CID, "", null, selectorFactory);
const kAboutPageRegistrationContentScript =
"chrome://mochikit/content/tests/BrowserTestUtils/content-about-page-utils.js";
/**
* Create and register the BrowserTestUtils and ContentEventListener window
* actors.
*/
function registerActors() {
ChromeUtils.registerWindowActor("BrowserTestUtils", {
parent: {
esModuleURI: "resource://testing-common/BrowserTestUtilsParent.sys.mjs",
},
child: {
esModuleURI: "resource://testing-common/BrowserTestUtilsChild.sys.mjs",
events: {
DOMContentLoaded: { capture: true },
load: { capture: true },
},
},
allFrames: true,
includeChrome: true,
});
ChromeUtils.registerWindowActor("ContentEventListener", {
parent: {
esModuleURI:
"resource://testing-common/ContentEventListenerParent.sys.mjs",
},
child: {
esModuleURI:
"resource://testing-common/ContentEventListenerChild.sys.mjs",
events: {
// We need to see the creation of all new windows, in case they have
// a browsing context we are interested in.
DOMWindowCreated: { capture: true },
},
},
allFrames: true,
});
}
registerActors();
/**
* BrowserTestUtils provides useful test utilities for working with the browser
* in browser mochitests. Most common operations (opening, closing and switching
* between tabs and windows, loading URLs, waiting for events in the parent or
* content process, clicking things in the content process, registering about
* pages, etc.) have dedicated helpers on this object.
*
* @class
*/
export var BrowserTestUtils = {
/**
* Loads a page in a new tab, executes a Task and closes the tab.
*
* @param {Object|String} options
* If this is a string it is the url to open and will be opened in the
* currently active browser window.
* @param {tabbrowser} [options.gBrowser
* A reference to the ``tabbrowser`` element where the new tab should
* be opened,
* @param {string} options.url
* The URL of the page to load.
* @param {Function} taskFn
* Async function representing that will be executed while
* the tab is loaded. The first argument passed to the function is a
* reference to the browser object for the new tab.
*
* @return {Any} Returns the value that is returned from taskFn.
* @resolves When the tab has been closed.
* @rejects Any exception from taskFn is propagated.
*/
async withNewTab(options, taskFn) {
if (typeof options == "string") {
options = {
gBrowser: Services.wm.getMostRecentWindow("navigator:browser").gBrowser,
url: options,
};
}
let tab = await BrowserTestUtils.openNewForegroundTab(options);
let originalWindow = tab.ownerGlobal;
let result;
try {
result = await taskFn(tab.linkedBrowser);
} finally {
let finalWindow = tab.ownerGlobal;
if (originalWindow == finalWindow && !tab.closing && tab.linkedBrowser) {
// taskFn may resolve within a tick after opening a new tab.
// We shouldn't remove the newly opened tab in the same tick.
// Wait for the next tick here.
await TestUtils.waitForTick();
BrowserTestUtils.removeTab(tab);
} else {
Services.console.logStringMessage(
"BrowserTestUtils.withNewTab: Tab was already closed before " +
"removeTab would have been called"
);
}
}
return Promise.resolve(result);
},
/**
* Opens a new tab in the foreground.
*
* This function takes an options object (which is preferred) or actual
* parameters. The names of the options must correspond to the names below.
* gBrowser is required and all other options are optional.
*
* @param {tabbrowser} gBrowser
* The tabbrowser to open the tab new in.
* @param {string} opening (or url)
* May be either a string URL to load in the tab, or a function that
* will be called to open a foreground tab. Defaults to "about:blank".
* @param {boolean} waitForLoad
* True to wait for the page in the new tab to load. Defaults to true.
* @param {boolean} waitForStateStop
* True to wait for the web progress listener to send STATE_STOP for the
* document in the tab. Defaults to false.
* @param {boolean} forceNewProcess
* True to force the new tab to load in a new process. Defaults to
* false.
*
* @return {Promise}
* Resolves when the tab is ready and loaded as necessary.
* @resolves The new tab.
*/
openNewForegroundTab(tabbrowser, ...args) {
let startTime = Cu.now();
let options;
if (
tabbrowser.ownerGlobal &&
tabbrowser === tabbrowser.ownerGlobal.gBrowser
) {
// tabbrowser is a tabbrowser, read the rest of the arguments from args.
let [
opening = "about:blank",
waitForLoad = true,
waitForStateStop = false,
forceNewProcess = false,
] = args;
options = { opening, waitForLoad, waitForStateStop, forceNewProcess };
} else {
if ("url" in tabbrowser && !("opening" in tabbrowser)) {
tabbrowser.opening = tabbrowser.url;
}
let {
opening = "about:blank",
waitForLoad = true,
waitForStateStop = false,
forceNewProcess = false,
} = tabbrowser;
tabbrowser = tabbrowser.gBrowser;
options = { opening, waitForLoad, waitForStateStop, forceNewProcess };
}
let {
opening: opening,
waitForLoad: aWaitForLoad,
waitForStateStop: aWaitForStateStop,
} = options;
let promises, tab;
try {
// If we're asked to force a new process, replace the normal process
// selector with one that always asks for a new process.
// If DEFAULT_PROCESSSELECTOR_CID is null, we're in non-e10s mode and we
// should skip this.
if (options.forceNewProcess && DEFAULT_PROCESSSELECTOR_CID) {
Services.ppmm.releaseCachedProcesses();
registrar.registerFactory(
OUR_PROCESSSELECTOR_CID,
"",
PROCESSSELECTOR_CONTRACTID,
null
);
}
promises = [
BrowserTestUtils.switchTab(tabbrowser, function () {
if (typeof opening == "function") {
opening();
tab = tabbrowser.selectedTab;
} else {
tabbrowser.selectedTab = tab = BrowserTestUtils.addTab(
tabbrowser,
opening
);
}
}),
];
if (aWaitForLoad) {
promises.push(BrowserTestUtils.browserLoaded(tab.linkedBrowser));
}
if (aWaitForStateStop) {
promises.push(BrowserTestUtils.browserStopped(tab.linkedBrowser));
}
} finally {
// Restore the original process selector, if needed.
if (options.forceNewProcess && DEFAULT_PROCESSSELECTOR_CID) {
registrar.registerFactory(
DEFAULT_PROCESSSELECTOR_CID,
"",
PROCESSSELECTOR_CONTRACTID,
null
);
}
}
return Promise.all(promises).then(() => {
let { innerWindowId } = tabbrowser.ownerGlobal.windowGlobalChild;
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test", innerWindowId },
"openNewForegroundTab"
);
return tab;
});
},
/**
* Checks if a DOM element is hidden.
*
* @param {Element} element
* The element which is to be checked.
*
* @return {boolean}
*/
is_hidden(element) {
let win = element.ownerGlobal;
let style = win.getComputedStyle(element);
if (style.display == "none") {
return true;
}
if (style.visibility != "visible") {
return true;
}
if (win.XULPopupElement.isInstance(element)) {
return ["hiding", "closed"].includes(element.state);
}
// Hiding a parent element will hide all its children
if (element.parentNode != element.ownerDocument) {
return BrowserTestUtils.is_hidden(element.parentNode);
}
return false;
},
/**
* Checks if a DOM element is visible.
*
* @param {Element} element
* The element which is to be checked.
*
* @return {boolean}
*/
is_visible(element) {
let win = element.ownerGlobal;
let style = win.getComputedStyle(element);
if (style.display == "none") {
return false;
}
if (style.visibility != "visible") {
return false;
}
if (win.XULPopupElement.isInstance(element) && element.state != "open") {
return false;
}
// Hiding a parent element will hide all its children
if (element.parentNode != element.ownerDocument) {
return BrowserTestUtils.is_visible(element.parentNode);
}
return true;
},
/**
* If the argument is a browsingContext, return it. If the
* argument is a browser/frame, returns the browsing context for it.
*/
getBrowsingContextFrom(browser) {
if (Element.isInstance(browser)) {
return browser.browsingContext;
}
return browser;
},
/**
* Switches to a tab and resolves when it is ready.
*
* @param {tabbrowser} tabbrowser
* The tabbrowser.
* @param {tab} tab
* Either a tab element to switch to or a function to perform the switch.
*
* @return {Promise}
* Resolves when the tab has been switched to.
* @resolves The tab switched to.
*/
switchTab(tabbrowser, tab) {
let startTime = Cu.now();
let { innerWindowId } = tabbrowser.ownerGlobal.windowGlobalChild;
let promise = new Promise(resolve => {
tabbrowser.addEventListener(
"TabSwitchDone",
function () {
TestUtils.executeSoon(() => {
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ category: "Test", startTime, innerWindowId },
"switchTab"
);
resolve(tabbrowser.selectedTab);
});
},
{ once: true }
);
});
if (typeof tab == "function") {
tab();
} else {
tabbrowser.selectedTab = tab;
}
return promise;
},
/**
* Waits for an ongoing page load in a browser window to complete.
*
* This can be used in conjunction with any synchronous method for starting a
* load, like the "addTab" method on "tabbrowser", and must be called before
* yielding control to the event loop. Note that calling this after multiple
* successive load operations can be racy, so ``wantLoad`` should be specified
* in these cases.
*
* This function works by listening for custom load events on ``browser``. These
* are sent by a BrowserTestUtils window actor in response to "load" and
* "DOMContentLoaded" content events.
*
* @param {xul:browser} browser
* A xul:browser.
* @param {Boolean} [includeSubFrames = false]
* A boolean indicating if loads from subframes should be included.
* @param {string|function} [wantLoad = null]
* If a function, takes a URL and returns true if that's the load we're
* interested in. If a string, gives the URL of the load we're interested
* in. If not present, the first load resolves the promise.
* @param {boolean} [maybeErrorPage = false]
* If true, this uses DOMContentLoaded event instead of load event.
* Also wantLoad will be called with visible URL, instead of
* 'about:neterror?...' for error page.
*
* @return {Promise}
* @resolves When a load event is triggered for the browser.
*/
browserLoaded(
browser,
includeSubFrames = false,
wantLoad = null,
maybeErrorPage = false
) {
let startTime = Cu.now();
let { innerWindowId } = browser.ownerGlobal.windowGlobalChild;
// Passing a url as second argument is a common mistake we should prevent.
if (includeSubFrames && typeof includeSubFrames != "boolean") {
throw new Error(
"The second argument to browserLoaded should be a boolean."
);
}
// If browser belongs to tabbrowser-tab, ensure it has been
// inserted into the document.
let tabbrowser = browser.ownerGlobal.gBrowser;
if (tabbrowser && tabbrowser.getTabForBrowser) {
let tab = tabbrowser.getTabForBrowser(browser);
if (tab) {
tabbrowser._insertBrowser(tab);
}
}
function isWanted(url) {
if (!wantLoad) {
return true;
} else if (typeof wantLoad == "function") {
return wantLoad(url);
}
// HTTPS-First (Bug 1704453) TODO: In case we are waiting
// for an http:// URL to be loaded and https-first is enabled,
// then we also return true in case the backend upgraded
// the load to https://.
if (
BrowserTestUtils._httpsFirstEnabled &&
typeof wantLoad == "string" &&
wantLoad.startsWith("http://")
) {
let wantLoadHttps = wantLoad.replace("http://", "https://");
if (wantLoadHttps == url) {
return true;
}
}
// It's a string.
return wantLoad == url;
}
// Error pages are loaded slightly differently, so listen for the
// DOMContentLoaded event for those instead.
let loadEvent = maybeErrorPage ? "DOMContentLoaded" : "load";
let eventName = `BrowserTestUtils:ContentEvent:${loadEvent}`;
return new Promise((resolve, reject) => {
function listener(event) {
switch (event.type) {
case eventName: {
let { browsingContext, internalURL, visibleURL } = event.detail;
// Sometimes we arrive here without an internalURL. If that's the
// case, just keep waiting until we get one.
if (!internalURL) {
return;
}
// Ignore subframes if we only care about the top-level load.
let subframe = browsingContext !== browsingContext.top;
if (subframe && !includeSubFrames) {
return;
}
// See testing/mochitest/BrowserTestUtils/content/BrowserTestUtilsChild.sys.mjs
// for the difference between visibleURL and internalURL.
if (!isWanted(maybeErrorPage ? visibleURL : internalURL)) {
return;
}
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test", innerWindowId },
"browserLoaded: " + internalURL
);
resolve(internalURL);
break;
}
case "unload":
reject(
new Error(
"The window unloaded while we were waiting for the browser to load - this should never happen."
)
);
break;
default:
return;
}
browser.removeEventListener(eventName, listener, true);
browser.ownerGlobal.removeEventListener("unload", listener);
}
browser.addEventListener(eventName, listener, true);
browser.ownerGlobal.addEventListener("unload", listener);
});
},
/**
* Waits for the selected browser to load in a new window. This
* is most useful when you've got a window that might not have
* loaded its DOM yet, and where you can't easily use browserLoaded
* on gBrowser.selectedBrowser since gBrowser doesn't yet exist.
*
* @param {xul:window} window
* A newly opened window for which we're waiting for the
* first browser load.
* @param {Boolean} aboutBlank [optional]
* If false, about:blank loads are ignored and we continue
* to wait.
* @param {function|null} checkFn [optional]
* If checkFn(browser) returns false, the load is ignored
* and we continue to wait.
*
* @return {Promise}
* @resolves Once the selected browser fires its load event.
*/
firstBrowserLoaded(win, aboutBlank = true, checkFn = null) {
return this.waitForEvent(
win,
"BrowserTestUtils:ContentEvent:load",
true,
event => {
if (checkFn) {
return checkFn(event.target);
}
return (
win.gBrowser.selectedBrowser.currentURI.spec !== "about:blank" ||
aboutBlank
);
}
);
},
_webProgressListeners: new Set(),
_contentEventListenerSharedState: new Map(),
_contentEventListeners: new Map(),
/**
* Waits for the web progress listener associated with this tab to fire a
* state change that matches checkFn for the toplevel document.
*
* @param {xul:browser} browser
* A xul:browser.
* @param {String} expectedURI (optional)
* A specific URL to check the channel load against
* @param {Function} checkFn
* If checkFn(aStateFlags, aStatus) returns false, the state change
* is ignored and we continue to wait.
*
* @return {Promise}
* @resolves When the desired state change reaches the tab's progress listener
*/
waitForBrowserStateChange(browser, expectedURI, checkFn) {
return new Promise(resolve => {
let wpl = {
onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
dump(
"Saw state " +
aStateFlags.toString(16) +
" and status " +
aStatus.toString(16) +
"\n"
);
if (checkFn(aStateFlags, aStatus) && aWebProgress.isTopLevel) {
let chan = aRequest.QueryInterface(Ci.nsIChannel);
dump(
"Browser got expected state change " +
chan.originalURI.spec +
"\n"
);
if (!expectedURI || chan.originalURI.spec == expectedURI) {
browser.removeProgressListener(wpl);
BrowserTestUtils._webProgressListeners.delete(wpl);
resolve();
}
}
},
onSecurityChange() {},
onStatusChange() {},
onLocationChange() {},
onContentBlockingEvent() {},
QueryInterface: ChromeUtils.generateQI([
"nsIWebProgressListener",
"nsIWebProgressListener2",
"nsISupportsWeakReference",
]),
};
browser.addProgressListener(wpl);
this._webProgressListeners.add(wpl);
dump(
"Waiting for browser state change" +
(expectedURI ? " of " + expectedURI : "") +
"\n"
);
});
},
/**
* Waits for the web progress listener associated with this tab to fire a
* STATE_STOP for the toplevel document.
*
* @param {xul:browser} browser
* A xul:browser.
* @param {String} expectedURI (optional)
* A specific URL to check the channel load against
* @param {Boolean} checkAborts (optional, defaults to false)
* Whether NS_BINDING_ABORTED stops 'count' as 'real' stops
* (e.g. caused by the stop button or equivalent APIs)
*
* @return {Promise}
* @resolves When STATE_STOP reaches the tab's progress listener
*/
browserStopped(browser, expectedURI, checkAborts = false) {
let testFn = function (aStateFlags, aStatus) {
return (
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
(checkAborts || aStatus != Cr.NS_BINDING_ABORTED)
);
};
dump(
"Waiting for browser load" +
(expectedURI ? " of " + expectedURI : "") +
"\n"
);
return BrowserTestUtils.waitForBrowserStateChange(
browser,
expectedURI,
testFn
);
},
/**
* Waits for the web progress listener associated with this tab to fire a
* STATE_START for the toplevel document.
*
* @param {xul:browser} browser
* A xul:browser.
* @param {String} expectedURI (optional)
* A specific URL to check the channel load against
*
* @return {Promise}
* @resolves When STATE_START reaches the tab's progress listener
*/
browserStarted(browser, expectedURI) {
let testFn = function (aStateFlags, aStatus) {
return (
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK &&
aStateFlags & Ci.nsIWebProgressListener.STATE_START
);
};
dump(
"Waiting for browser to start load" +
(expectedURI ? " of " + expectedURI : "") +
"\n"
);
return BrowserTestUtils.waitForBrowserStateChange(
browser,
expectedURI,
testFn
);
},
/**
* Waits for a tab to open and load a given URL.
*
* By default, the method doesn't wait for the tab contents to load.
*
* @param {tabbrowser} tabbrowser
* The tabbrowser to look for the next new tab in.
* @param {string|function} [wantLoad = null]
* If a function, takes a URL and returns true if that's the load we're
* interested in. If a string, gives the URL of the load we're interested
* in. If not present, the first non-about:blank load is used.
* @param {boolean} [waitForLoad = false]
* True to wait for the page in the new tab to load. Defaults to false.
* @param {boolean} [waitForAnyTab = false]
* True to wait for the url to be loaded in any new tab, not just the next
* one opened.
*
* @return {Promise}
* @resolves With the {xul:tab} when a tab is opened and its location changes
* to the given URL and optionally that browser has loaded.
*
* NB: this method will not work if you open a new tab with e.g. BrowserOpenTab
* and the tab does not load a URL, because no onLocationChange will fire.
*/
waitForNewTab(
tabbrowser,
wantLoad = null,
waitForLoad = false,
waitForAnyTab = false
) {
let urlMatches;
if (wantLoad && typeof wantLoad == "function") {
urlMatches = wantLoad;
} else if (wantLoad) {
urlMatches = urlToMatch => urlToMatch == wantLoad;
} else {
urlMatches = urlToMatch => urlToMatch != "about:blank";
}
return new Promise((resolve, reject) => {
tabbrowser.tabContainer.addEventListener(
"TabOpen",
function tabOpenListener(openEvent) {
if (!waitForAnyTab) {
tabbrowser.tabContainer.removeEventListener(
"TabOpen",
tabOpenListener
);
}
let newTab = openEvent.target;
let newBrowser = newTab.linkedBrowser;
let result;
if (waitForLoad) {
// If waiting for load, resolve with promise for that, which when load
// completes resolves to the new tab.
result = BrowserTestUtils.browserLoaded(
newBrowser,
false,
urlMatches
).then(() => newTab);
} else {
// If not waiting for load, just resolve with the new tab.
result = newTab;
}
let progressListener = {
onLocationChange(aBrowser) {
// Only interested in location changes on our browser.
if (aBrowser != newBrowser) {
return;
}
// Check that new location is the URL we want.
if (!urlMatches(aBrowser.currentURI.spec)) {
return;
}
if (waitForAnyTab) {
tabbrowser.tabContainer.removeEventListener(
"TabOpen",
tabOpenListener
);
}
tabbrowser.removeTabsProgressListener(progressListener);
TestUtils.executeSoon(() => resolve(result));
},
};
tabbrowser.addTabsProgressListener(progressListener);
}
);
});
},
/**
* Waits for onLocationChange.
*
* @param {tabbrowser} tabbrowser
* The tabbrowser to wait for the location change on.
* @param {string} url
* The string URL to look for. The URL must match the URL in the
* location bar exactly.
* @return {Promise}
* @resolves When onLocationChange fires.
*/
waitForLocationChange(tabbrowser, url) {
return new Promise((resolve, reject) => {
let progressListener = {
onLocationChange(
aBrowser,
aWebProgress,
aRequest,
aLocationURI,
aFlags
) {
if (
(url && aLocationURI.spec != url) ||
(!url && aLocationURI.spec == "about:blank")
) {
return;
}
tabbrowser.removeTabsProgressListener(progressListener);
resolve();
},
};
tabbrowser.addTabsProgressListener(progressListener);
});
},
/**
* Waits for the next browser window to open and be fully loaded.
*
* @param {Object} aParams
* @param {string} [aParams.url]
* If set, we will wait until the initial browser in the new window
* has loaded a particular page.
* If unset, the initial browser may or may not have finished
* loading its first page when the resulting Promise resolves.
* @param {bool} [aParams.anyWindow]
* True to wait for the url to be loaded in any new
* window, not just the next one opened.
* @param {bool} [aParams.maybeErrorPage]
* See ``browserLoaded`` function.
* @return {Promise}
* A Promise which resolves the next time that a DOM window
* opens and the delayed startup observer notification fires.
*/
waitForNewWindow(aParams = {}) {
let { url = null, anyWindow = false, maybeErrorPage = false } = aParams;
if (anyWindow && !url) {
throw new Error("url should be specified if anyWindow is true");
}
return new Promise((resolve, reject) => {
let observe = async (win, topic, data) => {
if (topic != "domwindowopened") {
return;
}
try {
if (!anyWindow) {
Services.ww.unregisterNotification(observe);
}
// Add these event listeners now since they may fire before the
// DOMContentLoaded event down below.
let promises = [
this.waitForEvent(win, "focus", true),
this.waitForEvent(win, "activate"),
];
if (url) {
await this.waitForEvent(win, "DOMContentLoaded");
if (win.document.documentURI != AppConstants.BROWSER_CHROME_URL) {
return;
}
}
promises.push(
TestUtils.topicObserved(
"browser-delayed-startup-finished",
subject => subject == win
)
);
if (url) {
let loadPromise = this.browserLoaded(
win.gBrowser.selectedBrowser,
false,
url,
maybeErrorPage
);
promises.push(loadPromise);
}
await Promise.all(promises);
if (anyWindow) {
Services.ww.unregisterNotification(observe);
}
resolve(win);
} catch (err) {
// We failed to wait for the load in this URI. This is only an error
// if `anyWindow` is not set, as if it is we can just wait for another
// window.
if (!anyWindow) {
reject(err);
}
}
};
Services.ww.registerNotification(observe);
});
},
/**
* Loads a new URI in the given browser, triggered by the system principal.
*
* @param {xul:browser} browser
* A xul:browser.
* @param {string} uri
* The URI to load.
*/
loadURIString(browser, uri) {
browser.fixupAndLoadURIString(uri, {
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
});
},
/**
* Maybe create a preloaded browser and ensure it's finished loading.
*
* @param gBrowser (<xul:tabbrowser>)
* The tabbrowser in which to preload a browser.
*/
async maybeCreatePreloadedBrowser(gBrowser) {
let win = gBrowser.ownerGlobal;
win.NewTabPagePreloading.maybeCreatePreloadedBrowser(win);
// We cannot use the regular BrowserTestUtils helper for waiting here, since that
// would try to insert the preloaded browser, which would only break things.
await lazy.ContentTask.spawn(gBrowser.preloadedBrowser, [], async () => {
await ContentTaskUtils.waitForCondition(() => {
return (
this.content.document &&
this.content.document.readyState == "complete"
);
});
});
},
/**
* @param win (optional)
* The window we should wait to have "domwindowopened" sent through
* the observer service for. If this is not supplied, we'll just
* resolve when the first "domwindowopened" notification is seen.
* @param {function} checkFn [optional]
* Called with the nsIDOMWindow object as argument, should return true
* if the event is the expected one, or false if it should be ignored
* and observing should continue. If not specified, the first window
* resolves the returned promise.
* @return {Promise}
* A Promise which resolves when a "domwindowopened" notification
* has been fired by the window watcher.
*/
domWindowOpened(win, checkFn) {
return new Promise(resolve => {
async function observer(subject, topic, data) {
if (topic == "domwindowopened" && (!win || subject === win)) {
let observedWindow = subject;
if (checkFn && !(await checkFn(observedWindow))) {
return;
}
Services.ww.unregisterNotification(observer);
resolve(observedWindow);
}
}
Services.ww.registerNotification(observer);
});
},
/**
* @param win (optional)
* The window we should wait to have "domwindowopened" sent through
* the observer service for. If this is not supplied, we'll just
* resolve when the first "domwindowopened" notification is seen.
* The promise will be resolved once the new window's document has been
* loaded.
*
* @param {function} checkFn (optional)
* Called with the nsIDOMWindow object as argument, should return true
* if the event is the expected one, or false if it should be ignored
* and observing should continue. If not specified, the first window
* resolves the returned promise.
*
* @return {Promise}
* A Promise which resolves when a "domwindowopened" notification
* has been fired by the window watcher.
*/
domWindowOpenedAndLoaded(win, checkFn) {
return this.domWindowOpened(win, async observedWin => {
await this.waitForEvent(observedWin, "load");
if (checkFn && !(await checkFn(observedWin))) {
return false;
}
return true;
});
},
/**
* @param win (optional)
* The window we should wait to have "domwindowclosed" sent through
* the observer service for. If this is not supplied, we'll just
* resolve when the first "domwindowclosed" notification is seen.
* @return {Promise}
* A Promise which resolves when a "domwindowclosed" notification
* has been fired by the window watcher.
*/
domWindowClosed(win) {
return new Promise(resolve => {
function observer(subject, topic, data) {
if (topic == "domwindowclosed" && (!win || subject === win)) {
Services.ww.unregisterNotification(observer);
resolve(subject);
}
}
Services.ww.registerNotification(observer);
});
},
/**
* Clear the stylesheet cache and open a new window to ensure
* CSS @supports -moz-bool-pref(...) {} rules are correctly
* applied to the browser chrome.
*
* @param {Object} options See BrowserTestUtils.openNewBrowserWindow
* @returns {Promise} Resolves with the new window once it is loaded.
*/
async openNewWindowWithFlushedCacheForMozSupports(options) {
ChromeUtils.clearStyleSheetCache();
return BrowserTestUtils.openNewBrowserWindow(options);
},
/**
* Open a new browser window from an existing one.
* This relies on OpenBrowserWindow in browser.js, and waits for the window
* to be completely loaded before resolving.
*
* @param {Object} options
* Options to pass to OpenBrowserWindow. Additionally, supports:
* @param {bool} options.waitForTabURL
* Forces the initial browserLoaded check to wait for the tab to
* load the given URL (instead of about:blank)
*
* @return {Promise}
* Resolves with the new window once it is loaded.
*/
async openNewBrowserWindow(options = {}) {
let startTime = Cu.now();
let currentWin = lazy.BrowserWindowTracker.getTopWindow({ private: false });
if (!currentWin) {
throw new Error(
"Can't open a new browser window from this helper if no non-private window is open."
);
}
let win = currentWin.OpenBrowserWindow(options);
let promises = [
this.waitForEvent(win, "focus", true),
this.waitForEvent(win, "activate"),
];
// Wait for browser-delayed-startup-finished notification, it indicates
// that the window has loaded completely and is ready to be used for
// testing.
promises.push(
TestUtils.topicObserved(
"browser-delayed-startup-finished",
subject => subject == win
).then(() => win)
);
promises.push(
this.firstBrowserLoaded(win, !options.waitForTabURL, browser => {
return (
!options.waitForTabURL ||
options.waitForTabURL == browser.currentURI.spec
);
})
);
await Promise.all(promises);
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test" },
"openNewBrowserWindow"
);
return win;
},
/**
* Closes a window.
*
* @param {Window} win
* A window to close.
*
* @return {Promise}
* Resolves when the provided window has been closed. For browser
* windows, the Promise will also wait until all final SessionStore
* messages have been sent up from all browser tabs.
*/
closeWindow(win) {
let closedPromise = BrowserTestUtils.windowClosed(win);
win.close();
return closedPromise;
},
/**
* Returns a Promise that resolves when a window has finished closing.
*
* @param {Window} win
* The closing window.
*
* @return {Promise}
* Resolves when the provided window has been fully closed. For
* browser windows, the Promise will also wait until all final
* SessionStore messages have been sent up from all browser tabs.
*/
windowClosed(win) {
let domWinClosedPromise = BrowserTestUtils.domWindowClosed(win);
let promises = [domWinClosedPromise];
let winType = win.document.documentElement.getAttribute("windowtype");
let flushTopic = "sessionstore-browser-shutdown-flush";
if (winType == "navigator:browser") {
let finalMsgsPromise = new Promise(resolve => {
let browserSet = new Set(win.gBrowser.browsers);
// Ensure all browsers have been inserted or we won't get
// messages back from them.
browserSet.forEach(browser => {
win.gBrowser._insertBrowser(win.gBrowser.getTabForBrowser(browser));
});
let observer = (subject, topic, data) => {
if (browserSet.has(subject)) {
browserSet.delete(subject);
}
if (!browserSet.size) {
Services.obs.removeObserver(observer, flushTopic);
// Give the TabStateFlusher a chance to react to this final
// update and for the TabStateFlusher.flushWindow promise
// to resolve before we resolve.
TestUtils.executeSoon(resolve);
}
};
Services.obs.addObserver(observer, flushTopic);
});
promises.push(finalMsgsPromise);
}
return Promise.all(promises);
},
/**
* Returns a Promise that resolves once the SessionStore information for the
* given tab is updated and all listeners are called.
*
* @param {xul:tab} tab
* The tab that will be removed.
* @returns {Promise}
* @resolves When the SessionStore information is updated.
*/
waitForSessionStoreUpdate(tab) {
return new Promise(resolve => {
let browser = tab.linkedBrowser;
let flushTopic = "sessionstore-browser-shutdown-flush";
let observer = (subject, topic, data) => {
if (subject === browser) {
Services.obs.removeObserver(observer, flushTopic);
// Wait for the next event tick to make sure other listeners are
// called.
TestUtils.executeSoon(() => resolve());
}
};
Services.obs.addObserver(observer, flushTopic);
});
},
/**
* Waits for an event to be fired on a specified element.
*
* @example
*
* let promiseEvent = BrowserTestUtils.waitForEvent(element, "eventName");
* // Do some processing here that will cause the event to be fired
* // ...
* // Now wait until the Promise is fulfilled
* let receivedEvent = await promiseEvent;
*
* @example
* // The promise resolution/rejection handler for the returned promise is
* // guaranteed not to be called until the next event tick after the event
* // listener gets called, so that all other event listeners for the element
* // are executed before the handler is executed.
*
* let promiseEvent = BrowserTestUtils.waitForEvent(element, "eventName");
* // Same event tick here.
* await promiseEvent;
* // Next event tick here.
*
* @example
* // If some code, such like adding yet another event listener, needs to be
* // executed in the same event tick, use raw addEventListener instead and
* // place the code inside the event listener.
*
* element.addEventListener("load", () => {
* // Add yet another event listener in the same event tick as the load
* // event listener.
* p = BrowserTestUtils.waitForEvent(element, "ready");
* }, { once: true });
*
* @param {Element} subject
* The element that should receive the event.
* @param {string} eventName
* Name of the event to listen to.
* @param {bool} [capture]
* True to use a capturing listener.
* @param {function} [checkFn]
* Called with the Event object as argument, should return true if the
* event is the expected one, or false if it should be ignored and
* listening should continue. If not specified, the first event with
* the specified name resolves the returned promise.
* @param {bool} [wantsUntrusted=false]
* True to receive synthetic events dispatched by web content.
*
* @note Because this function is intended for testing, any error in checkFn
* will cause the returned promise to be rejected instead of waiting for
* the next event, since this is probably a bug in the test.
*
* @returns {Promise}
* @resolves The Event object.
*/
waitForEvent(subject, eventName, capture, checkFn, wantsUntrusted) {
let startTime = Cu.now();
let innerWindowId = subject.ownerGlobal?.windowGlobalChild.innerWindowId;
return new Promise((resolve, reject) => {
let removed = false;
function listener(event) {
function cleanup() {
removed = true;
// Avoid keeping references to objects after the promise resolves.
subject = null;
checkFn = null;
}
try {
if (checkFn && !checkFn(event)) {
return;
}
subject.removeEventListener(eventName, listener, capture);
cleanup();
TestUtils.executeSoon(() => {
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test", innerWindowId },
"waitForEvent: " + eventName
);
resolve(event);
});
} catch (ex) {
try {
subject.removeEventListener(eventName, listener, capture);
} catch (ex2) {
// Maybe the provided object does not support removeEventListener.
}
cleanup();
TestUtils.executeSoon(() => reject(ex));
}
}
subject.addEventListener(eventName, listener, capture, wantsUntrusted);
TestUtils.promiseTestFinished?.then(() => {
if (removed) {
return;
}
subject.removeEventListener(eventName, listener, capture);
let text = eventName + " listener";
if (subject.id) {
text += ` on #${subject.id}`;
}
text += " not removed before the end of test";
reject(text);
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test", innerWindowId },
"waitForEvent: " + text
);
});
});
},
/**
* Like waitForEvent, but adds the event listener to the message manager
* global for browser.
*
* @param {string} eventName
* Name of the event to listen to.
* @param {bool} capture [optional]
* Whether to use a capturing listener.
* @param {function} checkFn [optional]
* Called with the Event object as argument, should return true if the
* event is the expected one, or false if it should be ignored and
* listening should continue. If not specified, the first event with
* the specified name resolves the returned promise.
* @param {bool} wantUntrusted [optional]
* Whether to accept untrusted events
*
* @note As of bug 1588193, this function no longer rejects the returned
* promise in the case of a checkFn error. Instead, since checkFn is now
* called through eval in the content process, the error is thrown in
* the listener created by ContentEventListenerChild. Work to improve
* error handling (eg. to reject the promise as before and to preserve
* the filename/stack) is being tracked in bug 1593811.
*
* @returns {Promise}
*/
waitForContentEvent(
browser,
eventName,
capture = false,
checkFn,
wantUntrusted = false
) {
return new Promise(resolve => {
let removeEventListener = this.addContentEventListener(
browser,
eventName,
() => {
removeEventListener();
resolve(eventName);
},
{ capture, wantUntrusted },
checkFn
);
});
},
/**
* Like waitForEvent, but acts on a popup. It ensures the popup is not already
* in the expected state.
*
* @param {Element} popup
* The popup element that should receive the event.
* @param {string} eventSuffix
* The event suffix expected to be received, one of "shown" or "hidden".
* @returns {Promise}
*/
waitForPopupEvent(popup, eventSuffix) {
let endState = { shown: "open", hidden: "closed" }[eventSuffix];
if (popup.state == endState) {
return Promise.resolve();
}
return this.waitForEvent(popup, "popup" + eventSuffix);
},
/**
* Waits for the select popup to be shown. This is needed because the select
* dropdown is created lazily.
*
* @param {Window} win
* A window to expect the popup in.
*
* @return {Promise}
* Resolves when the popup has been fully opened. The resolution value
* is the select popup.
*/
async waitForSelectPopupShown(win) {
let getMenulist = () =>
win.document.getElementById("ContentSelectDropdown");
let menulist = getMenulist();
if (!menulist) {
await this.waitForMutationCondition(
win.document,
{ childList: true, subtree: true },
getMenulist
);
menulist = getMenulist();
if (menulist.menupopup.state == "open") {
return menulist.menupopup;
}
}
await this.waitForEvent(menulist.menupopup, "popupshown");
return menulist.menupopup;
},
/**
* Waits for the datetime picker popup to be shown.
*
* @param {Window} win
* A window to expect the popup in.
*
* @return {Promise}
* Resolves when the popup has been fully opened. The resolution value
* is the select popup.
*/
async waitForDateTimePickerPanelShown(win) {
let getPanel = () => win.document.getElementById("DateTimePickerPanel");
let panel = getPanel();
let ensureReady = async () => {
let frame = panel.querySelector("#dateTimePopupFrame");
let isValidUrl = () => {
return (
frame.browsingContext?.currentURI?.spec ==
"chrome://global/content/datepicker.xhtml" ||
frame.browsingContext?.currentURI?.spec ==
"chrome://global/content/timepicker.xhtml"
);
};
// Ensure it's loaded.
if (!isValidUrl() || frame.contentDocument.readyState != "complete") {
await new Promise(resolve => {
frame.addEventListener(
"load",
function listener() {
if (isValidUrl()) {
frame.removeEventListener("load", listener, { capture: true });
resolve();
}
},
{ capture: true }
);
});
}
// Ensure it's ready.
if (!frame.contentWindow.PICKER_READY) {
await new Promise(resolve => {
frame.contentDocument.addEventListener("PickerReady", resolve, {
once: true,
});
});
}
// And that l10n mutations are flushed.
// FIXME(bug 1828721): We should ideally localize everything before
// showing the panel.
if (frame.contentDocument.hasPendingL10nMutations) {
await new Promise(resolve => {
frame.contentDocument.addEventListener(
"L10nMutationsFinished",
resolve,
{
once: true,
}
);
});
}
};
if (!panel) {
await this.waitForMutationCondition(
win.document,
{ childList: true, subtree: true },
getPanel
);
panel = getPanel();
if (panel.state == "open") {
await ensureReady();
return panel;
}
}
await this.waitForEvent(panel, "popupshown");
await ensureReady();
return panel;
},
/**
* Adds a content event listener on the given browser
* element. Similar to waitForContentEvent, but the listener will
* fire until it is removed. A callable object is returned that,
* when called, removes the event listener. Note that this function
* works even if the browser's frameloader is swapped.
*
* @param {xul:browser} browser
* The browser element to listen for events in.
* @param {string} eventName
* Name of the event to listen to.
* @param {function} listener
* Function to call in parent process when event fires.
* Not passed any arguments.
* @param {object} listenerOptions [optional]
* Options to pass to the event listener.
* @param {function} checkFn [optional]
* Called with the Event object as argument, should return true if the
* event is the expected one, or false if it should be ignored and
* listening should continue. If not specified, the first event with
* the specified name resolves the returned promise. This is called
* within the content process and can have no closure environment.
*
* @returns function
* If called, the return value will remove the event listener.
*/
addContentEventListener(
browser,
eventName,
listener,
listenerOptions = {},
checkFn
) {
let id = gListenerId++;
let contentEventListeners = this._contentEventListeners;
contentEventListeners.set(id, {
listener,
browserId: browser.browserId,
});
let eventListenerState = this._contentEventListenerSharedState;
eventListenerState.set(id, {
eventName,
listenerOptions,
checkFnSource: checkFn ? checkFn.toSource() : "",
});
Services.ppmm.sharedData.set(
"BrowserTestUtils:ContentEventListener",
eventListenerState
);
Services.ppmm.sharedData.flush();
let unregisterFunction = function () {
if (!eventListenerState.has(id)) {
return;
}
eventListenerState.delete(id);
contentEventListeners.delete(id);
Services.ppmm.sharedData.set(
"BrowserTestUtils:ContentEventListener",
eventListenerState
);
Services.ppmm.sharedData.flush();
};
return unregisterFunction;
},
/**
* This is an internal method to be invoked by
* BrowserTestUtilsParent.sys.mjs when a content event we were listening for
* happens.
*
* @private
*/
_receivedContentEventListener(listenerId, browserId) {
let listenerData = this._contentEventListeners.get(listenerId);
if (!listenerData) {
return;
}
if (listenerData.browserId != browserId) {
return;
}
listenerData.listener();
},
/**
* This is an internal method that cleans up any state from content event
* listeners.
*
* @private
*/
_cleanupContentEventListeners() {
this._contentEventListeners.clear();
if (this._contentEventListenerSharedState.size != 0) {
this._contentEventListenerSharedState.clear();
Services.ppmm.sharedData.set(
"BrowserTestUtils:ContentEventListener",
this._contentEventListenerSharedState
);
Services.ppmm.sharedData.flush();
}
if (this._contentEventListenerActorRegistered) {
this._contentEventListenerActorRegistered = false;
ChromeUtils.unregisterWindowActor("ContentEventListener");
}
},
observe(subject, topic, data) {
switch (topic) {
case "test-complete":
this._cleanupContentEventListeners();
break;
}
},
/**
* Wait until DOM mutations cause the condition expressed in checkFn
* to pass.
*
* Intended as an easy-to-use alternative to waitForCondition.
*
* @param {Element} target The target in which to observe mutations.
* @param {Object} options The options to pass to MutationObserver.observe();
* @param {function} checkFn Function that returns true when it wants the promise to be
* resolved.
*/
waitForMutationCondition(target, options, checkFn) {
if (checkFn()) {
return Promise.resolve();
}
return new Promise(resolve => {
let obs = new target.ownerGlobal.MutationObserver(function () {
if (checkFn()) {
obs.disconnect();
resolve();
}
});
obs.observe(target, options);
});
},
/**
* Like browserLoaded, but waits for an error page to appear.
*
* @param {xul:browser} browser
* A xul:browser.
*
* @return {Promise}
* @resolves When an error page has been loaded in the browser.
*/
waitForErrorPage(browser) {
return this.waitForContentEvent(
browser,
"AboutNetErrorLoad",
false,
null,
true
);
},
/**
* Waits for the next top-level document load in the current browser. The URI
* of the document is compared against expectedURL. The load is then stopped
* before it actually starts.
*
* @param {string} expectedURL
* The URL of the document that is expected to load.
* @param {object} browser
* The browser to wait for.
* @param {function} checkFn (optional)
* Function to run on the channel before stopping it.
* @returns {Promise}
*/
waitForDocLoadAndStopIt(expectedURL, browser, checkFn) {
let isHttp = url => /^https?:/.test(url);
return new Promise(resolve => {
// Redirect non-http URIs to http://mochi.test:8888/, so we can still
// use http-on-before-connect to listen for loads. Since we're
// aborting the load as early as possible, it doesn't matter whether the
// server handles it sensibly or not. However, this also means that this
// helper shouldn't be used to load local URIs (about pages, chrome://
// URIs, etc).
let proxyFilter;
if (!isHttp(expectedURL)) {
proxyFilter = {
proxyInfo: lazy.ProtocolProxyService.newProxyInfo(
"http",
"mochi.test",
8888,
"",
"",
0,
4096,
null
),
applyFilter(channel, defaultProxyInfo, callback) {
callback.onProxyFilterResult(
isHttp(channel.URI.spec) ? defaultProxyInfo : this.proxyInfo
);
},
};
lazy.ProtocolProxyService.registerChannelFilter(proxyFilter, 0);
}
function observer(chan) {
chan.QueryInterface(Ci.nsIHttpChannel);
if (!chan.originalURI || chan.originalURI.spec !== expectedURL) {
return;
}
if (checkFn && !checkFn(chan)) {
return;
}
// TODO: We should check that the channel's BrowsingContext matches
// the browser's. See bug 1587114.
try {
chan.cancel(Cr.NS_BINDING_ABORTED);
} finally {
if (proxyFilter) {
lazy.ProtocolProxyService.unregisterChannelFilter(proxyFilter);
}
Services.obs.removeObserver(observer, "http-on-before-connect");
resolve();
}
}
Services.obs.addObserver(observer, "http-on-before-connect");
});
},
/**
* Versions of EventUtils.jsm synthesizeMouse functions that synthesize a
* mouse event in a child process and return promises that resolve when the
* event has fired and completed. Instead of a window, a browser or
* browsing context is required to be passed to this function.
*
* @param target
* One of the following:
* - a selector string that identifies the element to target. The syntax is as
* for querySelector.
* - a function to be run in the content process that returns the element to
* target
* - null, in which case the offset is from the content document's edge.
* @param {integer} offsetX
* x offset from target's left bounding edge
* @param {integer} offsetY
* y offset from target's top bounding edge
* @param {Object} event object
* Additional arguments, similar to the EventUtils.jsm version
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
* @param {boolean} handlingUserInput
* Whether the synthesize should be perfomed while simulating
* user interaction (making windowUtils.isHandlingUserInput be true).
*
* @returns {Promise}
* @resolves True if the mouse event was cancelled.
*/
synthesizeMouse(
target,
offsetX,
offsetY,
event,
browsingContext,
handlingUserInput
) {
let targetFn = null;
if (typeof target == "function") {
targetFn = target.toString();
target = null;
} else if (typeof target != "string" && !Array.isArray(target)) {
target = null;
}
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SynthesizeMouse", {
target,
targetFn,
x: offsetX,
y: offsetY,
event,
handlingUserInput,
});
},
/**
* Versions of EventUtils.jsm synthesizeTouch functions that synthesize a
* touch event in a child process and return promises that resolve when the
* event has fired and completed. Instead of a window, a browser or
* browsing context is required to be passed to this function.
*
* @param target
* One of the following:
* - a selector string that identifies the element to target. The syntax is as
* for querySelector.
* - a function to be run in the content process that returns the element to
* target
* - null, in which case the offset is from the content document's edge.
* @param {integer} offsetX
* x offset from target's left bounding edge
* @param {integer} offsetY
* y offset from target's top bounding edge
* @param {Object} event object
* Additional arguments, similar to the EventUtils.jsm version
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
*
* @returns {Promise}
* @resolves True if the touch event was cancelled.
*/
synthesizeTouch(target, offsetX, offsetY, event, browsingContext) {
let targetFn = null;
if (typeof target == "function") {
targetFn = target.toString();
target = null;
} else if (typeof target != "string" && !Array.isArray(target)) {
target = null;
}
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SynthesizeTouch", {
target,
targetFn,
x: offsetX,
y: offsetY,
event,
});
},
/**
* Wait for a message to be fired from a particular message manager
*
* @param {nsIMessageManager} messageManager
* The message manager that should be used.
* @param {String} message
* The message we're waiting for.
* @param {Function} checkFn (optional)
* Optional function to invoke to check the message.
*/
waitForMessage(messageManager, message, checkFn) {
return new Promise(resolve => {
messageManager.addMessageListener(message, function onMessage(msg) {
if (!checkFn || checkFn(msg)) {
messageManager.removeMessageListener(message, onMessage);
resolve(msg.data);
}
});
});
},
/**
* Version of synthesizeMouse that uses the center of the target as the mouse
* location. Arguments and the return value are the same.
*/
synthesizeMouseAtCenter(target, event, browsingContext) {
// Use a flag to indicate to center rather than having a separate message.
event.centered = true;
return BrowserTestUtils.synthesizeMouse(
target,
0,
0,
event,
browsingContext
);
},
/**
* Version of synthesizeMouse that uses a client point within the child
* window instead of a target as the offset. Otherwise, the arguments and
* return value are the same as synthesizeMouse.
*/
synthesizeMouseAtPoint(offsetX, offsetY, event, browsingContext) {
return BrowserTestUtils.synthesizeMouse(
null,
offsetX,
offsetY,
event,
browsingContext
);
},
/**
* Removes the given tab from its parent tabbrowser.
* This method doesn't SessionStore etc.
*
* @param (tab) tab
* The tab to remove.
* @param (Object) options
* Extra options to pass to tabbrowser's removeTab method.
*/
removeTab(tab, options = {}) {
tab.ownerGlobal.gBrowser.removeTab(tab, options);
},
/**
* Returns a Promise that resolves once the tab starts closing.
*
* @param (tab) tab
* The tab that will be removed.
* @returns (Promise)
* @resolves When the tab starts closing. Does not get passed a value.
*/
waitForTabClosing(tab) {
return this.waitForEvent(tab, "TabClose");
},
/**
*
* @param {tab} tab
* The tab that will be reloaded.
* @param {Boolean} [includeSubFrames = false]
* A boolean indicating if loads from subframes should be included
* when waiting for the frame to reload.
* @returns {Promise}
* @resolves When the tab finishes reloading.
*/
reloadTab(tab, includeSubFrames = false) {
const finished = BrowserTestUtils.browserLoaded(
tab.linkedBrowser,
includeSubFrames
);
tab.ownerGlobal.gBrowser.reloadTab(tab);
return finished;
},
/**
* Create enough tabs to cause a tab overflow in the given window.
* @param {Function} registerCleanupFunction
* The test framework doesn't keep its cleanup stuff anywhere accessible,
* so the first argument is a reference to your cleanup registration
* function, allowing us to clean up after you if necessary.
* @param {Window} win
* The window where the tabs need to be overflowed.
* @param {object} params [optional]
* Parameters object for BrowserTestUtils.overflowTabs.
* overflowAtStart: bool
* Determines whether the new tabs are added at the beginning of the
* URL bar or at the end of it.
* overflowTabFactor: 3 | 1.1
* Factor that helps in determining the tab count for overflow.
*/
async overflowTabs(registerCleanupFunction, win, params = {}) {
if (!params.hasOwnProperty("overflowAtStart")) {
params.overflowAtStart = true;
}
if (!params.hasOwnProperty("overflowTabFactor")) {
params.overflowTabFactor = 1.1;
}
let index = params.overflowAtStart ? 0 : undefined;
let { gBrowser } = win;
let arrowScrollbox = gBrowser.tabContainer.arrowScrollbox;
const originalSmoothScroll = arrowScrollbox.smoothScroll;
arrowScrollbox.smoothScroll = false;
registerCleanupFunction(() => {
arrowScrollbox.smoothScroll = originalSmoothScroll;
});
let width = ele => ele.getBoundingClientRect().width;
let tabMinWidth = parseInt(
win.getComputedStyle(gBrowser.selectedTab).minWidth
);
let tabCountForOverflow = Math.ceil(
(width(arrowScrollbox) / tabMinWidth) * params.overflowTabFactor
);
while (gBrowser.tabs.length < tabCountForOverflow) {
BrowserTestUtils.addTab(gBrowser, "about:blank", {
skipAnimation: true,
index,
});
}
},
/**
* Crashes a remote frame tab and cleans up the generated minidumps.
* Resolves with the data from the .extra file (the crash annotations).
*
* @param (Browser) browser
* A remote <xul:browser> element. Must not be null.
* @param (bool) shouldShowTabCrashPage
* True if it is expected that the tab crashed page will be shown
* for this browser. If so, the Promise will only resolve once the
* tab crash page has loaded.
* @param (bool) shouldClearMinidumps
* True if the minidumps left behind by the crash should be removed.
* @param (BrowsingContext) browsingContext
* The context where the frame leaves. Default to
* top level context if not supplied.
* @param (object?) options
* An object with any of the following fields:
* crashType: "CRASH_INVALID_POINTER_DEREF" | "CRASH_OOM"
* The type of crash. If unspecified, default to "CRASH_INVALID_POINTER_DEREF"
* asyncCrash: bool
* If specified and `true`, cause the crash asynchronously.
*
* @returns (Promise)
* @resolves An Object with key-value pairs representing the data from the
* crash report's extra file (if applicable).
*/
async crashFrame(
browser,
shouldShowTabCrashPage = true,
shouldClearMinidumps = true,
browsingContext,
options = {}
) {
let extra = {};
if (!browser.isRemoteBrowser) {
throw new Error("<xul:browser> needs to be remote in order to crash");
}
/**
* Returns the directory where crash dumps are stored.
*
* @return nsIFile
*/
function getMinidumpDirectory() {
let dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
dir.append("minidumps");
return dir;
}
/**
* Removes a file from a directory. This is a no-op if the file does not
* exist.
*
* @param directory
* The nsIFile representing the directory to remove from.
* @param filename
* A string for the file to remove from the directory.
*/
function removeFile(directory, filename) {
let file = directory.clone();
file.append(filename);
if (file.exists()) {
file.remove(false);
}
}
let expectedPromises = [];
let crashCleanupPromise = new Promise((resolve, reject) => {
let observer = (subject, topic, data) => {
if (topic != "ipc:content-shutdown") {
reject("Received incorrect observer topic: " + topic);
return;
}
if (!(subject instanceof Ci.nsIPropertyBag2)) {
reject("Subject did not implement nsIPropertyBag2");
return;
}
// we might see this called as the process terminates due to previous tests.
// We are only looking for "abnormal" exits...
if (!subject.hasKey("abnormal")) {
dump(
"\nThis is a normal termination and isn't the one we are looking for...\n"
);
return;
}
Services.obs.removeObserver(observer, "ipc:content-shutdown");
let dumpID;
if (AppConstants.MOZ_CRASHREPORTER) {
dumpID = subject.getPropertyAsAString("dumpID");
if (!dumpID) {
reject(
"dumpID was not present despite crash reporting being enabled"
);
return;
}
}
let removalPromise = Promise.resolve();
if (dumpID) {
removalPromise = Services.crashmanager
.ensureCrashIsPresent(dumpID)
.then(async () => {
let minidumpDirectory = getMinidumpDirectory();
let extrafile = minidumpDirectory.clone();
extrafile.append(dumpID + ".extra");
if (extrafile.exists()) {
if (AppConstants.MOZ_CRASHREPORTER) {
extra = await IOUtils.readJSON(extrafile.path);
} else {
dump(
"\nCrashReporter not enabled - will not return any extra data\n"
);
}
} else {
dump(`\nNo .extra file for dumpID: ${dumpID}\n`);
}
if (shouldClearMinidumps) {
removeFile(minidumpDirectory, dumpID + ".dmp");
removeFile(minidumpDirectory, dumpID + ".extra");
}
});
}
removalPromise.then(() => {
dump("\nCrash cleaned up\n");
// There might be other ipc:content-shutdown handlers that need to
// run before we want to continue, so we'll resolve on the next tick
// of the event loop.
TestUtils.executeSoon(() => resolve());
});
};
Services.obs.addObserver(observer, "ipc:content-shutdown");
});
expectedPromises.push(crashCleanupPromise);
if (shouldShowTabCrashPage) {
expectedPromises.push(
new Promise((resolve, reject) => {
browser.addEventListener(
"AboutTabCrashedReady",
function onCrash() {
browser.removeEventListener("AboutTabCrashedReady", onCrash);
dump("\nabout:tabcrashed loaded and ready\n");
resolve();
},
false,
true
);
})
);
}
// Trigger crash by sending a message to BrowserTestUtils actor.
this.sendAsyncMessage(
browsingContext || browser.browsingContext,
"BrowserTestUtils:CrashFrame",
{
crashType: options.crashType || "",
asyncCrash: options.asyncCrash || false,
}
);
await Promise.all(expectedPromises);
if (shouldShowTabCrashPage) {
let gBrowser = browser.ownerGlobal.gBrowser;
let tab = gBrowser.getTabForBrowser(browser);
if (tab.getAttribute("crashed") != "true") {
throw new Error("Tab should be marked as crashed");
}
}
return extra;
},
/**
* Attempts to simulate a launch fail by crashing a browser, but
* stripping the browser of its childID so that the TabCrashHandler
* thinks it was a launch fail.
*
* @param browser (<xul:browser>)
* The browser to simulate a content process launch failure on.
* @return Promise
* @resolves undefined
* Resolves when the TabCrashHandler should be done handling the
* simulated crash.
*/
simulateProcessLaunchFail(browser, dueToBuildIDMismatch = false) {
const NORMAL_CRASH_TOPIC = "ipc:content-shutdown";
Object.defineProperty(browser.frameLoader, "childID", {
get: () => 0,
});
let sawNormalCrash = false;
let observer = (subject, topic, data) => {
sawNormalCrash = true;
};
Services.obs.addObserver(observer, NORMAL_CRASH_TOPIC);
Services.obs.notifyObservers(
browser.frameLoader,
"oop-frameloader-crashed"
);
let eventType = dueToBuildIDMismatch
? "oop-browser-buildid-mismatch"
: "oop-browser-crashed";
let event = new browser.ownerGlobal.CustomEvent(eventType, {
bubbles: true,
});
event.isTopFrame = true;
browser.dispatchEvent(event);
Services.obs.removeObserver(observer, NORMAL_CRASH_TOPIC);
if (sawNormalCrash) {
throw new Error(`Unexpectedly saw ${NORMAL_CRASH_TOPIC}`);
}
return new Promise(resolve => TestUtils.executeSoon(resolve));
},
/**
* Returns a promise that is resolved when element gains attribute (or,
* optionally, when it is set to value).
* @param {String} attr
* The attribute to wait for
* @param {Element} element
* The element which should gain the attribute
* @param {String} value (optional)
* Optional, the value the attribute should have.
*
* @returns {Promise}
*/
waitForAttribute(attr, element, value) {
let MutationObserver = element.ownerGlobal.MutationObserver;
return new Promise(resolve => {
let mut = new MutationObserver(mutations => {
if (
(!value && element.hasAttribute(attr)) ||
(value && element.getAttribute(attr) === value)
) {
resolve();
mut.disconnect();
}
});
mut.observe(element, { attributeFilter: [attr] });
});
},
/**
* Returns a promise that is resolved when element loses an attribute.
* @param {String} attr
* The attribute to wait for
* @param {Element} element
* The element which should lose the attribute
*
* @returns {Promise}
*/
waitForAttributeRemoval(attr, element) {
if (!element.hasAttribute(attr)) {
return Promise.resolve();
}
let MutationObserver = element.ownerGlobal.MutationObserver;
return new Promise(resolve => {
dump("Waiting for removal\n");
let mut = new MutationObserver(mutations => {
if (!element.hasAttribute(attr)) {
resolve();
mut.disconnect();
}
});
mut.observe(element, { attributeFilter: [attr] });
});
},
/**
* Version of EventUtils' `sendChar` function; it will synthesize a keypress
* event in a child process and returns a Promise that will resolve when the
* event was fired. Instead of a Window, a Browser or Browsing Context
* is required to be passed to this function.
*
* @param {String} char
* A character for the keypress event that is sent to the browser.
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
*
* @returns {Promise}
* @resolves True if the keypress event was synthesized.
*/
sendChar(char, browsingContext) {
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SendChar", { char });
},
/**
* Version of EventUtils' `synthesizeKey` function; it will synthesize a key
* event in a child process and returns a Promise that will resolve when the
* event was fired. Instead of a Window, a Browser or Browsing Context
* is required to be passed to this function.
*
* @param {String} key
* See the documentation available for EventUtils#synthesizeKey.
* @param {Object} event
* See the documentation available for EventUtils#synthesizeKey.
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
*
* @returns {Promise}
*/
synthesizeKey(key, event, browsingContext) {
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SynthesizeKey", {
key,
event,
});
},
/**
* Version of EventUtils' `synthesizeComposition` function; it will synthesize
* a composition event in a child process and returns a Promise that will
* resolve when the event was fired. Instead of a Window, a Browser or
* Browsing Context is required to be passed to this function.
*
* @param {Object} event
* See the documentation available for EventUtils#synthesizeComposition.
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
*
* @returns {Promise}
* @resolves False if the composition event could not be synthesized.
*/
synthesizeComposition(event, browsingContext) {
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SynthesizeComposition", {
event,
});
},
/**
* Version of EventUtils' `synthesizeCompositionChange` function; it will
* synthesize a compositionchange event in a child process and returns a
* Promise that will resolve when the event was fired. Instead of a Window, a
* Browser or Browsing Context object is required to be passed to this function.
*
* @param {Object} event
* See the documentation available for EventUtils#synthesizeCompositionChange.
* @param {BrowserContext|MozFrameLoaderOwner} browsingContext
* Browsing context or browser element, must not be null
*
* @returns {Promise}
*/
synthesizeCompositionChange(event, browsingContext) {
browsingContext = this.getBrowsingContextFrom(browsingContext);
return this.sendQuery(browsingContext, "Test:SynthesizeCompositionChange", {
event,
});
},
// TODO: Fix consumers and remove me.
waitForCondition: TestUtils.waitForCondition,
/**
* Waits for a <xul:notification> with a particular value to appear
* for the <xul:notificationbox> of the passed in browser.
*
* @param {xul:tabbrowser} tabbrowser
* The gBrowser that hosts the browser that should show
* the notification. For most tests, this will probably be
* gBrowser.
* @param {xul:browser} browser
* The browser that should be showing the notification.
* @param {String} notificationValue
* The "value" of the notification, which is often used as
* a unique identifier. Example: "plugin-crashed".
*
* @return {Promise}
* Resolves to the <xul:notification> that is being shown.
*/
waitForNotificationBar(tabbrowser, browser, notificationValue) {
let notificationBox = tabbrowser.getNotificationBox(browser);
return this.waitForNotificationInNotificationBox(
notificationBox,
notificationValue
);
},
/**
* Waits for a <xul:notification> with a particular value to appear
* in the global <xul:notificationbox> of the given browser window.
*
* @param {Window} win
* The browser window in whose global notificationbox the
* notification is expected to appear.
* @param {String} notificationValue
* The "value" of the notification, which is often used as
* a unique identifier. Example: "captive-portal-detected".
*
* @return {Promise}
* Resolves to the <xul:notification> that is being shown.
*/
waitForGlobalNotificationBar(win, notificationValue) {
return this.waitForNotificationInNotificationBox(
win.gNotificationBox,
notificationValue
);
},
waitForNotificationInNotificationBox(notificationBox, notificationValue) {
return new Promise(resolve => {
let check = event => {
return event.target.getAttribute("value") == notificationValue;
};
BrowserTestUtils.waitForEvent(
notificationBox.stack,
"AlertActive",
false,
check
).then(event => {
// The originalTarget of the AlertActive on a notificationbox
// will be the notification itself.
resolve(event.originalTarget);
});
});
},
/**
* Waits for CSS transitions to complete for an element. Tracks any
* transitions that start after this function is called and resolves once all
* started transitions complete.
*
* @param {Element} element
* The element that will transition.
* @param {Number} timeout
* The maximum time to wait in milliseconds. Defaults to 5 seconds.
* @return {Promise}
* Resolves when transitions complete or rejects if the timeout is hit.
*/
waitForTransition(element, timeout = 5000) {
return new Promise((resolve, reject) => {
let cleanup = () => {
element.removeEventListener("transitionrun", listener);
element.removeEventListener("transitionend", listener);
};
let timer = element.ownerGlobal.setTimeout(() => {
cleanup();
reject();
}, timeout);
let transitionCount = 0;
let listener = event => {
if (event.type == "transitionrun") {
transitionCount++;
} else {
transitionCount--;
if (transitionCount == 0) {
cleanup();
element.ownerGlobal.clearTimeout(timer);
resolve();
}
}
};
element.addEventListener("transitionrun", listener);
element.addEventListener("transitionend", listener);
element.addEventListener("transitioncancel", listener);
});
},
_knownAboutPages: new Set(),
_loadedAboutContentScript: false,
/**
* Registers an about: page with particular flags in both the parent
* and any content processes. Returns a promise that resolves when
* registration is complete.
*
* @param {Function} registerCleanupFunction
* The test framework doesn't keep its cleanup stuff anywhere accessible,
* so the first argument is a reference to your cleanup registration
* function, allowing us to clean up after you if necessary.
* @param {String} aboutModule
* The name of the about page.
* @param {String} pageURI
* The URI the about: page should point to.
* @param {Number} flags
* The nsIAboutModule flags to use for registration.
*
* @returns {Promise}
* Promise that resolves when registration has finished.
*/
registerAboutPage(registerCleanupFunction, aboutModule, pageURI, flags) {
// Return a promise that resolves when registration finished.
const kRegistrationMsgId =
"browser-test-utils:about-registration:registered";
let rv = this.waitForMessage(Services.ppmm, kRegistrationMsgId, msg => {
return msg.data == aboutModule;
});
// Load a script that registers our page, then send it a message to execute the registration.
if (!this._loadedAboutContentScript) {
Services.ppmm.loadProcessScript(
kAboutPageRegistrationContentScript,
true
);
this._loadedAboutContentScript = true;
registerCleanupFunction(this._removeAboutPageRegistrations.bind(this));
}
Services.ppmm.broadcastAsyncMessage(
"browser-test-utils:about-registration:register",
{ aboutModule, pageURI, flags }
);
return rv.then(() => {
this._knownAboutPages.add(aboutModule);
});
},
unregisterAboutPage(aboutModule) {
if (!this._knownAboutPages.has(aboutModule)) {
return Promise.reject(
new Error("We don't think this about page exists!")
);
}
const kUnregistrationMsgId =
"browser-test-utils:about-registration:unregistered";
let rv = this.waitForMessage(Services.ppmm, kUnregistrationMsgId, msg => {
return msg.data == aboutModule;
});
Services.ppmm.broadcastAsyncMessage(
"browser-test-utils:about-registration:unregister",
aboutModule
);
return rv.then(() => this._knownAboutPages.delete(aboutModule));
},
async _removeAboutPageRegistrations() {
for (let aboutModule of this._knownAboutPages) {
await this.unregisterAboutPage(aboutModule);
}
Services.ppmm.removeDelayedProcessScript(
kAboutPageRegistrationContentScript
);
},
/**
* Waits for the dialog to open, and clicks the specified button.
*
* @param {string} buttonNameOrElementID
* The name of the button ("accept", "cancel", etc) or element ID to
* click.
* @param {string} uri
* The URI of the dialog to wait for. Defaults to the common dialog.
* @return {Promise}
* A Promise which resolves when a "domwindowopened" notification
* for a dialog has been fired by the window watcher and the
* specified button is clicked.
*/
async promiseAlertDialogOpen(
buttonNameOrElementID,
uri = "chrome://global/content/commonDialog.xhtml",
options = { callback: null, isSubDialog: false }
) {
let win;
if (uri == "chrome://global/content/commonDialog.xhtml") {
[win] = await TestUtils.topicObserved("common-dialog-loaded");
} else if (options.isSubDialog) {
[win] = await TestUtils.topicObserved("subdialog-loaded");
} else {
// The test listens for the "load" event which guarantees that the alert
// class has already been added (it is added when "DOMContentLoaded" is
// fired).
win = await this.domWindowOpenedAndLoaded(null, win => {
return win.document.documentURI === uri;
});
}
if (options.callback) {
await options.callback(win);
return win;
}
if (buttonNameOrElementID) {
let dialog = win.document.querySelector("dialog");
let element =
dialog.getButton(buttonNameOrElementID) ||
win.document.getElementById(buttonNameOrElementID);
element.click();
}
return win;
},
/**
* Wait for the containing dialog with the id `window-modal-dialog` to become
* empty and close.
*
* @param {HTMLDialogElement} dialog
* The dialog to wait on.
* @return {Promise}
* Resolves once the the dialog has closed
*/
async waitForDialogClose(dialog) {
return this.waitForEvent(dialog, "close").then(() => {
return this.waitForMutationCondition(
dialog,
{ childList: true, attributes: true },
() => !dialog.hasChildNodes() && !dialog.open
);
});
},
/**
* Waits for the dialog to open, and clicks the specified button, and waits
* for the dialog to close.
*
* @param {string} buttonNameOrElementID
* The name of the button ("accept", "cancel", etc) or element ID to
* click.
* @param {string} uri
* The URI of the dialog to wait for. Defaults to the common dialog.
*
* @return {Promise}
* A Promise which resolves when a "domwindowopened" notification
* for a dialog has been fired by the window watcher and the
* specified button is clicked, and the dialog has been fully closed.
*/
async promiseAlertDialog(
buttonNameOrElementID,
uri = "chrome://global/content/commonDialog.xhtml",
options = { callback: null, isSubDialog: false }
) {
let win = await this.promiseAlertDialogOpen(
buttonNameOrElementID,
uri,
options
);
if (!win.docShell.browsingContext.embedderElement) {
return this.windowClosed(win);
}
const dialog = win.top.document.getElementById("window-modal-dialog");
return this.waitForDialogClose(dialog);
},
/**
* Opens a tab with a given uri and params object. If the params object is not set
* or the params parameter does not include a triggeringPrincipal then this function
* provides a params object using the systemPrincipal as the default triggeringPrincipal.
*
* @param {xul:tabbrowser} tabbrowser
* The gBrowser object to open the tab with.
* @param {string} uri
* The URI to open in the new tab.
* @param {object} params [optional]
* Parameters object for gBrowser.addTab.
* @param {function} beforeLoadFunc [optional]
* A function to run after that xul:browser has been created but before the URL is
* loaded. Can spawn a content task in the tab, for example.
*/
addTab(tabbrowser, uri, params = {}, beforeLoadFunc = null) {
if (!params.triggeringPrincipal) {
params.triggeringPrincipal =
Services.scriptSecurityManager.getSystemPrincipal();
}
if (!params.allowInheritPrincipal) {
params.allowInheritPrincipal = true;
}
if (beforeLoadFunc) {
let window = tabbrowser.ownerGlobal;
window.addEventListener(
"TabOpen",
function (e) {
beforeLoadFunc(e.target);
},
{ once: true }
);
}
return tabbrowser.addTab(uri, params);
},
/**
* There are two ways to listen for observers in a content process:
* 1. Call contentTopicObserved which will watch for an observer notification
* in a content process to occur, and will return a promise which resolves
* when that notification occurs.
* 2. Enclose calls to contentTopicObserved inside a pair of calls to
* startObservingTopics and stopObservingTopics. Usually this pair will be
* placed at the start and end of a test or set of tests. Any observer
* notification that happens between the start and stop that doesn't match
* any explicitly expected by using contentTopicObserved will cause
* stopObservingTopics to reject with an error.
* For example:
*
* await BrowserTestUtils.startObservingTopics(bc, ["a", "b", "c"]);
* await BrowserTestUtils contentTopicObserved(bc, "a", 2);
* await BrowserTestUtils.stopObservingTopics(bc, ["a", "b", "c"]);
*
* This will expect two "a" notifications to occur, but will fail if more
* than two occur, or if any "b" or "c" notifications occur.
*
* Note that this function doesn't handle adding a listener for the same topic
* more than once. To do that, use the aCount argument.
*
* @param aBrowsingContext
* The browsing context associated with the content process to listen to.
* @param {string} aTopic
* Observer topic to listen to. May be null to listen to any topic.
* @param {number} aCount
* Number of such matching topics to listen to, defaults to 1. A match
* occurs when the topic and filter function match.
* @param {function} aFilterFn
* Function to be evaluated in the content process which should
* return true if the notification matches. This function is passed
* the same arguments as nsIObserver.observe(). May be null to
* always match.
* @returns {Promise} resolves when the notification occurs.
*/
contentTopicObserved(aBrowsingContext, aTopic, aCount = 1, aFilterFn = null) {
return this.sendQuery(aBrowsingContext, "BrowserTestUtils:ObserveTopic", {
topic: aTopic,
count: aCount,
filterFunctionSource: aFilterFn ? aFilterFn.toSource() : null,
});
},
/**
* Starts observing a list of topics in a content process. Use contentTopicObserved
* to allow an observer notification. Any other observer notification that occurs that
* matches one of the specified topics will cause the promise to reject.
*
* Calling this function more than once adds additional topics to be observed without
* replacing the existing ones.
*
* @param {BrowsingContext} aBrowsingContext
* The browsing context associated with the content process to listen to.
* @param {String[]} aTopics array of observer topics
* @returns {Promise} resolves when the listeners have been added.
*/
startObservingTopics(aBrowsingContext, aTopics) {
return this.sendQuery(
aBrowsingContext,
"BrowserTestUtils:StartObservingTopics",
{
topics: aTopics,
}
);
},
/**
* Stop listening to a set of observer topics.
*
* @param {BrowsingContext} aBrowsingContext
* The browsing context associated with the content process to listen to.
* @param {String[]} aTopics array of observer topics. If empty, then all
* current topics being listened to are removed.
* @returns {Promise} promise that fails if an unexpected observer occurs.
*/
stopObservingTopics(aBrowsingContext, aTopics) {
return this.sendQuery(
aBrowsingContext,
"BrowserTestUtils:StopObservingTopics",
{
topics: aTopics,
}
);
},
/**
* Sends a message to a specific BrowserTestUtils window actor.
* @param {BrowsingContext} aBrowsingContext
* The browsing context where the actor lives.
* @param {string} aMessageName
* Name of the message to be sent to the actor.
* @param {object} aMessageData
* Extra information to pass to the actor.
*/
async sendAsyncMessage(aBrowsingContext, aMessageName, aMessageData) {
if (!aBrowsingContext.currentWindowGlobal) {
await this.waitForCondition(() => aBrowsingContext.currentWindowGlobal);
}
let actor =
aBrowsingContext.currentWindowGlobal.getActor("BrowserTestUtils");
actor.sendAsyncMessage(aMessageName, aMessageData);
},
/**
* Sends a query to a specific BrowserTestUtils window actor.
* @param {BrowsingContext} aBrowsingContext
* The browsing context where the actor lives.
* @param {string} aMessageName
* Name of the message to be sent to the actor.
* @param {object} aMessageData
* Extra information to pass to the actor.
*/
async sendQuery(aBrowsingContext, aMessageName, aMessageData) {
let startTime = Cu.now();
if (!aBrowsingContext.currentWindowGlobal) {
await this.waitForCondition(() => aBrowsingContext.currentWindowGlobal);
}
let actor =
aBrowsingContext.currentWindowGlobal.getActor("BrowserTestUtils");
return actor.sendQuery(aMessageName, aMessageData).then(val => {
ChromeUtils.addProfilerMarker(
"BrowserTestUtils",
{ startTime, category: "Test" },
aMessageName
);
return val;
});
},
/**
* A helper function for this test that returns a Promise that resolves
* once either the legacy or new migration wizard appears.
*
* @param {DOMWindow} window
* The top-level window that the about:preferences tab is likely to open
* in if the new migration wizard is enabled.
* @param {boolean} forceLegacy
* True if, despite the browser.migrate.content-modal.enabled pref value,
* the legacy XUL migration wizard is expected.
* @returns {Promise<Element>}
* Resolves to the dialog window in the legacy case, and the
* about:preferences tab otherwise.
*/
async waitForMigrationWizard(window, forceLegacy = false) {
if (!this._usingNewMigrationWizard || forceLegacy) {
return this.waitForCondition(() => {
let win = Services.wm.getMostRecentWindow("Browser:MigrationWizard");
if (win?.document?.readyState == "complete") {
return win;
}
return false;
}, "Wait for migration wizard to open");
}
let wizardReady = this.waitForEvent(window, "MigrationWizard:Ready");
let wizardTab = await this.waitForNewTab(window.gBrowser, url => {
return url.startsWith("about:preferences");
});
await wizardReady;
return wizardTab;
},
/**
* Closes the migration wizard.
*
* @param {Element} wizardWindowOrTab
* The XUL dialog window for the migration wizard in the legacy case, and
* the about:preferences tab otherwise. In general, it's probably best to
* just pass whatever BrowserTestUtils.waitForMigrationWizard resolved to
* into this in order to handle both the old and new migration wizard.
* @param {boolean} forceLegacy
* True if, despite the browser.migrate.content-modal.enabled pref value,
* the legacy XUL migration wizard is expected.
* @returns {Promise<undefined>}
*/
closeMigrationWizard(wizardWindowOrTab, forceLegacy = false) {
if (!this._usingNewMigrationWizard || forceLegacy) {
return BrowserTestUtils.closeWindow(wizardWindowOrTab);
}
return BrowserTestUtils.removeTab(wizardWindowOrTab);
},
};
XPCOMUtils.defineLazyPreferenceGetter(
BrowserTestUtils,
"_httpsFirstEnabled",
"dom.security.https_first",
false
);
XPCOMUtils.defineLazyPreferenceGetter(
BrowserTestUtils,
"_usingNewMigrationWizard",
"browser.migrate.content-modal.enabled",
false
);
Services.obs.addObserver(BrowserTestUtils, "test-complete");
|