1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
//! ChromiumPage — browser automation via Chrome DevTools Protocol.
//!
//! Uses `chromiumoxide` to drive Chrome/Chromium. Stealth mode is enabled
//! by default to avoid bot-detection.
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, Mutex};
use chromiumoxide::browser::Browser;
use chromiumoxide::cdp::browser_protocol::network::CookieParam;
use chromiumoxide::cdp::browser_protocol::page::{
AddScriptToEvaluateOnNewDocumentParams, RemoveScriptToEvaluateOnNewDocumentParams,
ScriptIdentifier,
};
use chromiumoxide::Page;
use futures::StreamExt;
use tracing::{debug, info};
use crate::config::ChromiumOptions;
use crate::console::ConsoleMonitor;
use crate::download::DownloadManager;
use crate::element::Element;
use crate::error::{Error, Result};
use crate::locator::locator_to_selector;
use crate::websocket::WebSocketMonitor;
/// Safely JSON-escape a string for embedding in JavaScript.
/// Falls back to a quoted string on serialization failure (should never happen for valid UTF-8).
pub(crate) fn json_escape(s: impl AsRef<str>) -> String {
serde_json::to_string(s.as_ref()).unwrap_or_else(|_| format!("\"{}\"", s.as_ref()))
}
/// Options for PDF export via CDP `Page.printToPDF`.
///
/// All dimension fields use **inches**. Unset fields use the browser's default
/// (letter paper 8.5×11 in, ~0.4 in margins, scale 1.0).
///
/// ```ignore
/// use rpage::PdfOptions;
/// let opts = PdfOptions::builder()
/// .paper_width(8.5)
/// .paper_height(11.0)
/// .print_background(true)
/// .landscape(false)
/// .build();
/// page.pdf_to_file("out.pdf", opts).await?;
/// ```
#[derive(Debug, Clone)]
pub struct PdfOptions {
/// Paper width in inches (default 8.5).
pub paper_width: Option<f64>,
/// Paper height in inches (default 11).
pub paper_height: Option<f64>,
/// Top margin in inches (default ~0.4).
pub margin_top: Option<f64>,
/// Bottom margin in inches.
pub margin_bottom: Option<f64>,
/// Left margin in inches.
pub margin_left: Option<f64>,
/// Right margin in inches.
pub margin_right: Option<f64>,
/// Print background graphics (default true).
pub print_background: bool,
/// Landscape orientation (default false).
pub landscape: bool,
/// Display header and footer (default false).
pub display_header_footer: bool,
/// HTML template for the print header.
pub header_template: Option<String>,
/// HTML template for the print footer.
pub footer_template: Option<String>,
/// Scale of the webpage rendering (default 1.0).
pub scale: Option<f64>,
/// Paper ranges to print, e.g. `"1-5, 8"`.
pub page_ranges: Option<String>,
}
impl Default for PdfOptions {
fn default() -> Self {
Self {
paper_width: None,
paper_height: None,
margin_top: None,
margin_bottom: None,
margin_left: None,
margin_right: None,
print_background: true,
landscape: false,
display_header_footer: false,
header_template: None,
footer_template: None,
scale: None,
page_ranges: None,
}
}
}
impl PdfOptions {
/// Create a builder initialised with defaults.
pub fn builder() -> PdfOptionsBuilder {
PdfOptionsBuilder::default()
}
/// Convert these options into CDP `PrintToPdfParams`.
#[allow(dead_code)]
fn to_cdp_params(&self) -> chromiumoxide::cdp::browser_protocol::page::PrintToPdfParams {
let mut b = chromiumoxide::cdp::browser_protocol::page::PrintToPdfParams::builder();
if let Some(v) = self.paper_width {
b = b.paper_width(v);
}
if let Some(v) = self.paper_height {
b = b.paper_height(v);
}
if let Some(v) = self.margin_top {
b = b.margin_top(v);
}
if let Some(v) = self.margin_bottom {
b = b.margin_bottom(v);
}
if let Some(v) = self.margin_left {
b = b.margin_left(v);
}
if let Some(v) = self.margin_right {
b = b.margin_right(v);
}
if self.print_background {
b = b.print_background(true);
}
if self.landscape {
b = b.landscape(true);
}
if self.display_header_footer {
b = b.display_header_footer(true);
}
if let Some(ref v) = self.header_template {
b = b.header_template(v.clone());
}
if let Some(ref v) = self.footer_template {
b = b.footer_template(v.clone());
}
if let Some(v) = self.scale {
b = b.scale(v);
}
if let Some(ref v) = self.page_ranges {
b = b.page_ranges(v.clone());
}
b.build()
}
}
/// Builder for [`PdfOptions`].
#[derive(Default)]
pub struct PdfOptionsBuilder {
inner: PdfOptions,
}
impl PdfOptionsBuilder {
pub fn paper_width(mut self, v: f64) -> Self {
self.inner.paper_width = Some(v);
self
}
pub fn paper_height(mut self, v: f64) -> Self {
self.inner.paper_height = Some(v);
self
}
pub fn margin_top(mut self, v: f64) -> Self {
self.inner.margin_top = Some(v);
self
}
pub fn margin_bottom(mut self, v: f64) -> Self {
self.inner.margin_bottom = Some(v);
self
}
pub fn margin_left(mut self, v: f64) -> Self {
self.inner.margin_left = Some(v);
self
}
pub fn margin_right(mut self, v: f64) -> Self {
self.inner.margin_right = Some(v);
self
}
pub fn print_background(mut self, v: bool) -> Self {
self.inner.print_background = v;
self
}
pub fn landscape(mut self, v: bool) -> Self {
self.inner.landscape = v;
self
}
pub fn display_header_footer(mut self, v: bool) -> Self {
self.inner.display_header_footer = v;
self
}
pub fn header_template(mut self, v: impl Into<String>) -> Self {
self.inner.header_template = Some(v.into());
self
}
pub fn footer_template(mut self, v: impl Into<String>) -> Self {
self.inner.footer_template = Some(v.into());
self
}
pub fn scale(mut self, v: f64) -> Self {
self.inner.scale = Some(v);
self
}
pub fn page_ranges(mut self, v: impl Into<String>) -> Self {
self.inner.page_ranges = Some(v.into());
self
}
pub fn build(self) -> PdfOptions {
self.inner
}
}
/// Information from a file chooser dialog event.
#[derive(Debug, Clone)]
pub struct FileChooserInfo {
pub backend_node_id: u64,
pub mode: String,
}
/// Cookie info extracted from the browser.
#[derive(Debug, Clone)]
pub struct CookieInfo {
pub name: String,
pub value: String,
pub domain: Option<String>,
pub path: Option<String>,
pub secure: bool,
pub http_only: bool,
}
/// Try to find Chrome on the system.
fn find_chrome() -> Option<PathBuf> {
// 1. Check RPAGE_CHROME_PATH environment variable
if let Ok(path) = std::env::var("RPAGE_CHROME_PATH") {
let p = PathBuf::from(&path);
if p.exists() {
return Some(p);
}
}
// 2. Check PATH for common binary names
if let Ok(path_var) = std::env::var("PATH") {
let separator = if cfg!(windows) { ';' } else { ':' };
for dir in path_var.split(separator) {
let candidates: &[&str] = if cfg!(windows) {
&["chrome.exe", "chromium.exe"]
} else {
&["chrome", "chromium", "google-chrome", "chromium-browser"]
};
for name in candidates {
let full = PathBuf::from(dir).join(name);
if full.exists() {
return Some(full);
}
}
}
}
// 3. Check standard install paths
let candidates = [
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
"/usr/bin/google-chrome",
"/usr/bin/chromium-browser",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
];
for p in &candidates {
let pb = PathBuf::from(p);
if pb.exists() {
return Some(pb);
}
}
None
}
/// ChromiumPage wraps a headful/headless Chrome instance via CDP.
pub struct ChromiumPage {
browser: Browser,
/// Wrapped in Mutex to allow switching the active tab via `activate_tab`.
page: std::sync::Mutex<Page>,
opts: ChromiumOptions,
debug_url: String,
download_manager: Arc<DownloadManager>,
network_monitor: Arc<crate::network::NetworkMonitor>,
console_monitor: Arc<ConsoleMonitor>,
ws_monitor: Arc<WebSocketMonitor>,
/// Named init scripts: name → JS source
init_scripts: Arc<Mutex<HashMap<String, String>>>,
/// Named init scripts: name → CDP-returned identifier
init_script_ids: Arc<Mutex<HashMap<String, ScriptIdentifier>>>,
/// Load strategy: "normal" | "eager" | "none"
load_strategy: String,
/// Whether the high-level listen mode (DrissionPage-style) is active.
listening: Arc<Mutex<bool>>,
/// The spawned Chrome child process, if this ChromiumPage *launched* Chrome.
/// `None` when connected via `connect()`/`connect_with_opts()` to an
/// already-running browser (we don't own that process).
///
/// On Drop we kill this child to avoid orphaned Chrome processes, since
/// Windows spawns it with `DETACHED_PROCESS` and Rust's default `Child`
/// drop does not terminate detached children.
child: std::sync::Mutex<Option<std::process::Child>>,
}
impl Drop for ChromiumPage {
/// Clean up the spawned Chrome child process if we own it.
///
/// rpage launches Chrome with `DETACHED_PROCESS` on Windows, so Rust's
/// default `Child` drop (which kills on drop) does **not** fire — the
/// handle simply goes out of scope and Chrome keeps running as an orphan.
/// This Drop closes that gap: if `self.child` holds a process we spawned,
/// we hard-kill it and reap the zombie.
///
/// Prefer calling `.quit().await` for graceful (CDP-level) shutdown; this
/// Drop is a safety net for the "user forgot / panic / early return" case.
fn drop(&mut self) {
if let Ok(mut guard) = self.child.lock() {
if let Some(mut child) = guard.take() {
// Best-effort kill. Ignore errors: the process may already be gone
// (e.g. quit() already closed it, or it crashed).
let _ = child.kill();
let _ = child.wait(); // reap to avoid zombie
debug!("ChromiumPage::drop killed owned Chrome child");
}
}
// If child was None, we connected to an external browser we don't own —
// leave it running (the external owner manages its lifetime).
}
}
/// A type-erased CDP command for `ChromiumPage::run_cdp`. chromiumoxide's
/// `Page::execute` is generic over the typed `Command` structs it generates,
/// so to send an arbitrary `Domain.method` + JSON params (the escape hatch)
/// we implement the same traits over a method name and a raw `Value`: the
/// params are serialized verbatim as the call payload, and the response is
/// handed back as untyped JSON.
struct RawCdpCommand {
method: std::borrow::Cow<'static, str>,
params: serde_json::Value,
}
impl serde::Serialize for RawCdpCommand {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
self.params.serialize(serializer)
}
}
impl chromiumoxide::Method for RawCdpCommand {
fn identifier(&self) -> chromiumoxide::types::MethodId {
self.method.clone()
}
}
impl chromiumoxide::Command for RawCdpCommand {
type Response = serde_json::Value;
}
/// The body of a network response, as returned by
/// [`ChromiumPage::get_response_body`]. `base64_encoded` is true for binary
/// payloads (images, fonts, …); use [`ResponseBody::bytes`] to decode those.
#[derive(Debug, Clone)]
pub struct ResponseBody {
pub body: String,
pub base64_encoded: bool,
}
impl ResponseBody {
/// The body as raw bytes, base64-decoding first when Chrome flagged the
/// payload as binary. For text responses this is just the UTF-8 bytes.
pub fn bytes(&self) -> Vec<u8> {
if self.base64_encoded {
use base64::Engine;
base64::engine::general_purpose::STANDARD
.decode(self.body.as_bytes())
.unwrap_or_default()
} else {
self.body.clone().into_bytes()
}
}
/// The body as a UTF-8 string (lossy), decoding base64 first if needed.
pub fn text(&self) -> String {
if self.base64_encoded {
String::from_utf8_lossy(&self.bytes()).into_owned()
} else {
self.body.clone()
}
}
}
/// A captured request/response pair, as returned by
/// [`ChromiumPage::wait_data_packet`]. This is rpage's equivalent of
/// DrissionPage's `DataPacket`: the request metadata, the response metadata,
/// and the actual response body (when Chrome still had it available).
#[derive(Debug, Clone)]
pub struct DataPacket {
pub url: String,
pub method: String,
pub status: u16,
pub resource_type: String,
pub request_id: String,
pub mime_type: String,
pub request_headers: HashMap<String, String>,
pub response_headers: HashMap<String, String>,
/// The response body, or `None` for bodies Chrome no longer retains
/// (redirects, 204s, evicted entries).
pub response_body: Option<ResponseBody>,
}
impl DataPacket {
/// Convenience: the response body as text (empty string if not captured).
pub fn body_text(&self) -> String {
self.response_body
.as_ref()
.map(|b| b.text())
.unwrap_or_default()
}
}
impl ChromiumPage {
/// Returns a clone of the current active page.
/// Page is Arc<PageInner> internally, so clone is cheap (just Arc refcount++).
fn page(&self) -> Page {
self.page.lock().unwrap().clone()
}
/// Replace the current active page with a new one.
fn set_page(&self, new_page: Page) {
*self.page.lock().unwrap() = new_page;
}
/// **启动浏览器并接管** — 一个函数搞定,零自动化标记,永不触发验证码。
///
/// 内部流程:
/// 1. 自动检测系统 Chrome 路径
/// 2. 用 `Command` 启动 Chrome(只传 `--remote-debugging-port`)
/// 3. 等待调试端口就绪
/// 4. 通过 CDP 连接接管
///
/// 因为不走 chromiumoxide 的 `Browser::launch`(它会加 `--enable-automation` 等
/// 默认参数),所以浏览器没有任何自动化标记,和用户手动打开的完全一样。
///
/// # 行为约定(重要)
/// `new()` 始终以**有头模式**启动(显示浏览器窗口),使用每次进程独立的
/// 临时 user-data-dir,固定端口 `9222`。这是为了交互式/调试场景的"开箱即用"。
///
/// 如果你需要 headless、自定义端口、持久化 profile 等生产环境配置,
/// 请改用 [`with_options`](Self::with_options):
/// ```ignore
/// use rpage::config::ChromiumOptions;
/// let page = ChromiumPage::with_options(
/// ChromiumOptions::builder().headless(true).debug_port(19222).build()
/// ).await?;
/// ```
/// 注意 `ChromiumOptions::default()` 是 headless,与 `new()` 相反——这是
/// 为了让 `new()` 保持"可视化调试"的语义,而 `with_options` 默认走生产路径。
pub async fn new() -> Result<Self> {
let chrome_path = find_chrome().ok_or_else(|| Error::Browser("Chrome not found".into()))?;
// Use a unique user-data-dir per PID to prevent Chrome from merging
// into an already-running instance (Windows single-instance behavior)
let ud = std::env::temp_dir().join(format!("rpage-chrome-{}", std::process::id()));
// Use a fixed well-known port for simplicity
let port: u16 = 9222;
Self::launch_and_connect(
&chrome_path,
Some(&ud),
port,
&[],
false, // headless = false, show browser window (see doc above)
None,
true,
false,
&[],
// Skip Network/Runtime monitoring setup (see `enable_monitoring`'s
// doc comment): `new()` is meant to be a fast, low-overhead,
// visible debug session, not background request/console/download
// telemetry, and enabling the Network domain is the dominant
// source of chromiumoxide's "WS Invalid message" warning spam.
ChromiumOptions::builder().enable_monitoring(false).build(),
)
.await
}
/// 用自定义端口启动浏览器(便捷方法)。
///
/// 等价于 `ChromiumOptions::builder().debug_port(port).build()` 再传给 `with_options`。
///
/// ```ignore
/// // 默认端口 9222
/// let page = ChromiumPage::new().await?;
/// // 自定义端口
/// let page = ChromiumPage::with_port(9333).await?;
/// ```
pub async fn with_port(port: u16) -> Result<Self> {
let opts = ChromiumOptions::builder().debug_port(port).build();
Self::with_options(opts).await
}
/// 用自定义选项启动浏览器。
pub async fn with_options(opts: ChromiumOptions) -> Result<Self> {
let chrome_path = if let Some(ref path) = opts.browser_path {
path.clone()
} else {
find_chrome().ok_or_else(|| Error::Browser("Chrome not found".into()))?
};
let port = opts.debug_port;
// Key the fallback dir off the port (see `new()`): a fixed shared dir
// would let a stale Chrome instance on a different port lock out any
// new launch that doesn't pass an explicit `user_data_dir`.
let user_data_dir = opts
.user_data_dir
.clone()
.unwrap_or_else(|| std::env::temp_dir().join(format!("rpage-chrome-{port}")));
let extra_args = opts.extra_args.clone();
let headless = opts.headless;
let proxy = opts.proxy.clone();
let user_agent = opts.user_agent.clone();
let page = Self::launch_and_connect(
&chrome_path,
Some(&user_data_dir),
port,
&extra_args,
headless,
proxy.as_deref(),
opts.disable_gpu,
opts.no_sandbox,
&opts.extension_dirs,
opts.clone(),
)
.await?;
// Apply viewport
if opts.viewport.width > 0 && opts.viewport.height > 0 {
use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
let params = SetDeviceMetricsOverrideParams::new(
opts.viewport.width as i64,
opts.viewport.height as i64,
1.0,
false,
);
page.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("viewport: {e}")))?;
}
// Apply user-agent if specified
if !user_agent.is_empty() {
crate::network::set_user_agent(&page.page(), &user_agent).await?;
}
// Apply proxy authentication if specified
if let Some((ref user, ref pass)) = opts.proxy_auth {
page.set_proxy_auth(user, pass).await?;
}
Ok(page)
}
#[allow(clippy::too_many_arguments)]
async fn launch_and_connect(
chrome_path: &PathBuf,
user_data_dir: Option<&PathBuf>,
port: u16,
extra_args: &[String],
headless: bool,
proxy: Option<&str>,
disable_gpu: bool,
no_sandbox: bool,
extension_dirs: &[PathBuf],
opts: ChromiumOptions,
) -> Result<Self> {
let debug_url = format!("http://127.0.0.1:{port}");
// Check if a browser is already listening on this port
// Use TcpStream instead of reqwest to avoid connection-pool / proxy false positives
let already_running = tokio::net::TcpStream::connect(format!("127.0.0.1:{port}"))
.await
.is_ok();
if !already_running {
info!(
"Launching Chrome at {} (port {port})",
chrome_path.display()
);
let mut cmd = Command::new(chrome_path);
cmd.arg(format!("--remote-debugging-port={port}"));
if let Some(ud) = user_data_dir {
cmd.arg(format!("--user-data-dir={}", ud.display()));
} else {
// Both current callers always pass `Some(_)` (keyed off `port`,
// see `new()`/`with_options()`), so this is a defensive fallback
// only — kept consistent with them rather than reintroducing a
// fixed shared dir that could collide across ports.
let tmp = std::env::temp_dir().join(format!("rpage-chrome-{port}"));
cmd.arg(format!("--user-data-dir={}", tmp.display()));
}
// Prevent Chrome from merging into an existing instance
cmd.arg("--no-first-run");
cmd.arg("--no-default-browser-check");
// Apply headless mode
if headless {
cmd.arg("--headless=new");
}
// Apply proxy
if let Some(proxy_url) = proxy {
cmd.arg(format!("--proxy-server={proxy_url}"));
}
// Apply disable-gpu
if disable_gpu {
cmd.arg("--disable-gpu");
}
// Apply no-sandbox
if no_sandbox {
cmd.arg("--no-sandbox");
}
// Apply extensions
for dir in extension_dirs {
cmd.arg(format!("--load-extension={}", dir.display()));
}
for arg in extra_args {
cmd.arg(arg);
}
// Windows: create detached process without console window
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x00000008); // DETACHED_PROCESS
}
// Chrome (and its long-lived gpu/utility/renderer subprocesses)
// must not inherit our stdio: by default `Command` inherits the
// parent's handles, so anything capturing this process's
// stdout/stderr via a pipe (a test harness, a log redirect)
// never sees EOF — the pipe stays open as long as any spawned
// Chrome subprocess is alive, even after we've exited.
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = cmd
.spawn()
.map_err(|e| Error::Browser(format!("spawn Chrome: {e}")))?;
// Check that the child process didn't immediately exit (happens when
// Chrome merges into an already-running instance on Windows).
std::thread::sleep(std::time::Duration::from_millis(500));
match child.try_wait() {
Ok(Some(status)) => {
return Err(Error::Browser(format!(
"Chrome exited immediately with status: {status}. \
Another Chrome instance may be using the same user-data-dir."
)));
}
Ok(None) => { /* still running, good */ }
Err(e) => {
return Err(Error::Browser(format!("check Chrome process: {e}")));
}
}
// Wait for debug port to be ready. If this or the connect step
// below fails, we must kill the child we just spawned to avoid
// leaving an orphaned Chrome process behind (Windows DETACHED_PROCESS
// children survive their parent by default).
if let Err(e) = Self::wait_for_port(debug_url.clone()).await {
let _ = child.kill();
return Err(e);
}
// Connect via CDP. On failure, clean up the spawned child.
let page = match Self::connect_with_opts(&debug_url, opts).await {
Ok(p) => p,
Err(e) => {
let _ = child.kill();
return Err(e);
}
};
// Record ownership so Drop can clean up later.
*page.child.lock().unwrap() = Some(child);
Ok(page)
} else {
info!("Browser already running on port {port}, reusing");
// Reusing an external browser — no child to own.
Self::connect_with_opts(&debug_url, opts).await
}
}
/// Poll the debug port until Chrome is ready (max 10s).
async fn wait_for_port(debug_url: String) -> Result<()> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.build()
.map_err(|e| Error::Browser(format!("http client: {e}")))?;
for _ in 0..50 {
if client
.get(format!("{debug_url}/json/version"))
.send()
.await
.is_ok()
{
info!("Chrome debug port ready");
return Ok(());
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
Err(Error::Browser(
"Chrome debug port not ready after 10s".into(),
))
}
/// **接管已打开的浏览器** — 零自动化标记,永远不会触发验证码。
///
/// 用法:
/// 1. 先用命令行启动 Chrome(用你自己的 profile):
/// `chrome --remote-debugging-port=9222`
/// 2. 然后 `ChromiumPage::connect("http://localhost:9222")` 接管
///
/// 因为浏览器是你手动打开的,没有任何 `--enable-automation`、
/// `HeadlessChrome` UA、`navigator.webdriver` 等标记,
/// 所有网站(包括百度)都不会触发验证码。
pub async fn connect(debug_url: &str) -> Result<Self> {
Self::connect_with_opts(debug_url, ChromiumOptions::default()).await
}
/// Connect to a running browser and store the given options.
pub async fn connect_with_opts(debug_url: &str, opts: ChromiumOptions) -> Result<Self> {
info!("Connecting to existing browser at {debug_url}");
// ── Step 1: Discover existing targets via HTTP BEFORE connecting via CDP ──
// The HTTP /json/list endpoint returns all existing targets reliably,
// unlike chromiumoxide's pages() which depends on async event processing
// and may return an empty list due to a race condition.
#[derive(serde::Deserialize)]
struct TargetEntry {
id: String,
#[serde(rename = "type")]
target_type: String,
url: String,
#[allow(dead_code)]
title: String,
}
let existing_targets: Vec<TargetEntry> = {
let list_url = format!("{debug_url}/json/list");
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(3))
.build()
.map_err(|e| Error::Browser(format!("http client: {e}")))?;
let resp = client
.get(&list_url)
.send()
.await
.map_err(|e| Error::Browser(format!("fetch targets: {e}")))?;
resp.json()
.await
.map_err(|e| Error::Browser(format!("parse targets: {e}")))?
};
let page_targets: Vec<&TargetEntry> = existing_targets
.iter()
.filter(|t| t.target_type == "page")
.collect();
info!(
"Discovered {} existing targets ({} pages)",
existing_targets.len(),
page_targets.len(),
);
// ── Step 2: Connect via CDP ──
let (browser, handler) = Browser::connect(debug_url)
.await
.map_err(|e| Error::Browser(format!("connect: {e}")))?;
tokio::spawn(async move {
let mut h = handler;
while h.next().await.is_some() {}
});
// ── Step 3: Pick the right page ──
// Give the handler a moment to process initial target events so
// get_page() can find them.
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let page = if page_targets.is_empty() {
info!("No existing page targets, creating new page");
browser
.new_page("about:blank")
.await
.map_err(|e| Error::Browser(format!("new page: {e}")))?
} else if page_targets.len() == 1 {
let tid = &page_targets[0].id;
info!(
"Reusing single existing page (id={tid}, url={})",
page_targets[0].url
);
// Retry get_page a few times — the handler may not have registered
// the target yet.
let mut page = None;
for _ in 0..10 {
if let Ok(p) = browser.get_page(tid.clone().into()).await {
page = Some(p);
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
page.ok_or_else(|| {
Error::Browser(format!(
"target {tid} known via /json/list but not in handler"
))
})?
} else {
// Multiple page targets: find the one that's currently visible.
let mut found: Option<Page> = None;
for t in &page_targets {
if let Ok(p) = browser.get_page(t.id.clone().into()).await {
if let Ok(res) = p.evaluate("document.visibilityState").await {
if let Some(val) = res.value().and_then(|v| v.as_str()) {
if val == "visible" {
info!("Reusing active (visible) page (id={}, url={})", t.id, t.url);
found = Some(p);
break;
}
}
}
}
}
if let Some(p) = found {
p
} else {
// Fallback: use the first page target
let tid = &page_targets[0].id;
info!("No visible page found, reusing first page (id={tid})");
let mut page = None;
for _ in 0..10 {
if let Ok(p) = browser.get_page(tid.clone().into()).await {
page = Some(p);
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
page.ok_or_else(|| {
Error::Browser(format!(
"target {tid} known via /json/list but not in handler"
))
})?
}
};
// Apply stealth scripts
crate::stealth::apply_stealth(&page, &crate::stealth::StealthConfig::default())
.await
.ok();
info!("Connected to existing browser — zero automation flags");
let nm = Arc::new(crate::network::NetworkMonitor::new());
let dm_clone = Arc::new(DownloadManager::new());
let cm = Arc::new(ConsoleMonitor::new());
let ws = Arc::new(WebSocketMonitor::new());
if opts.enable_monitoring {
Self::start_monitoring(&page, nm.clone(), dm_clone.clone(), cm.clone(), ws.clone())
.await;
}
Ok(Self {
browser,
page: std::sync::Mutex::new(page),
opts,
debug_url: debug_url.to_string(),
download_manager: dm_clone,
network_monitor: nm,
console_monitor: cm,
ws_monitor: ws,
init_scripts: Arc::new(Mutex::new(HashMap::new())),
init_script_ids: Arc::new(Mutex::new(HashMap::new())),
load_strategy: "normal".into(),
listening: Arc::new(Mutex::new(false)),
child: std::sync::Mutex::new(None),
})
}
/// Enables Network/Runtime CDP domains and wires up the event listeners
/// that feed `network_monitor`/`download_manager`/`console_monitor`/
/// `ws_monitor`. Skipped by `connect_with_opts` when
/// `ChromiumOptions::enable_monitoring` is false (see its doc comment).
///
/// All CDP commands and event_listener registrations are wrapped in
/// timeouts so a single broken CDP domain can't deadlock the whole
/// connection. Chrome 149+ has deprecated `Browser.setDownloadBehavior`,
/// so we skip it entirely and rely on event listeners alone.
async fn start_monitoring(
page: &Page,
nm: Arc<crate::network::NetworkMonitor>,
dm_clone: Arc<DownloadManager>,
cm: Arc<ConsoleMonitor>,
ws: Arc<WebSocketMonitor>,
) {
let init_timeout = std::time::Duration::from_secs(3);
// Network.enable — needed for request/download/WebSocket events
let pc = page.clone();
let nm1 = nm.clone();
let _ = tokio::time::timeout(init_timeout, crate::network::enable_network(&pc)).await;
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventRequestWillBeSent>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let mut hdrs = std::collections::HashMap::new();
if let Some(obj) = ev.request.headers.inner().as_object() {
for (k, v) in obj { hdrs.insert(k.clone(), v.as_str().unwrap_or_default().to_string()); }
}
nm1.record_request(crate::network::RequestRecord {
request_id: ev.request_id.clone().into(),
url: ev.request.url.clone(),
method: ev.request.method.clone(),
headers: hdrs,
resource_type: format!("{:?}", ev.r#type),
});
}
});
}
// Network.responseReceived — feeds `responses()`/`get_responses()` and
// fires the `on_response` callbacks. Without this listener those were
// dead: nothing ever called `record_response`, so the response monitor
// and every `on_response` handler stayed permanently empty.
let nm2 = nm.clone();
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventResponseReceived>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let mut hdrs = std::collections::HashMap::new();
if let Some(obj) = ev.response.headers.inner().as_object() {
for (k, v) in obj { hdrs.insert(k.clone(), v.as_str().unwrap_or_default().to_string()); }
}
nm2.record_response(crate::network::ResponseRecord {
request_id: ev.request_id.clone().into(),
url: ev.response.url.clone(),
status: ev.response.status as u16,
headers: hdrs,
mime_type: ev.response.mime_type.clone(),
});
}
});
}
// Network.loadingFailed — feeds `failures()`. The event itself carries
// no URL, so resolve it from the matching request we already recorded.
let nm3 = nm.clone();
if let Ok(Ok(mut rx)) = tokio::time::timeout(
init_timeout,
pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventLoadingFailed>(
),
)
.await
{
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let rid: String = ev.request_id.clone().into();
let url = nm3
.requests()
.into_iter()
.rev()
.find(|r| r.request_id == rid)
.map(|r| r.url)
.unwrap_or_default();
nm3.record_failure(crate::network::FailedRequest {
request_id: rid,
url,
error_text: ev.error_text.clone(),
});
}
});
}
// Download monitoring — listen for events without SetDownloadBehavior
// (Chrome 149+ removed setDownloadBehavior; events fire regardless)
let dm1 = dm_clone.clone();
let dm2 = dm_clone.clone();
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::browser::EventDownloadWillBegin>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let id = dm1.register(&ev.url, &ev.suggested_filename);
debug!("Download started: guid={} id={} file={}", ev.guid, id, ev.suggested_filename);
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::browser::EventDownloadProgress>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
use chromiumoxide::cdp::browser_protocol::browser::DownloadProgressState;
let guid = &ev.guid;
match ev.state {
DownloadProgressState::InProgress => {
dm2.update_progress(guid, ev.received_bytes as u64);
}
DownloadProgressState::Completed => {
let save = ev.file_path.as_deref().unwrap_or("");
dm2.complete(guid, std::path::Path::new(save));
}
DownloadProgressState::Canceled => {
dm2.cancel(guid);
}
}
}
});
}
// Runtime.enable — console + exception monitoring
let cm1 = cm.clone();
let cm2 = cm.clone();
let _ = tokio::time::timeout(init_timeout, crate::console::enable_runtime(&pc)).await;
if let Ok(Ok(mut rx)) = tokio::time::timeout(
init_timeout,
pc.event_listener::<chromiumoxide::cdp::js_protocol::runtime::EventConsoleApiCalled>(),
)
.await
{
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let level = crate::console::cdp_type_to_level(&ev.r#type);
let text_parts: Vec<String> = ev
.args
.iter()
.map(|arg| {
arg.value
.as_ref()
.map(|v| v.to_string().trim_matches('"').to_string())
.unwrap_or_else(|| arg.description.clone().unwrap_or_default())
})
.collect();
let text = text_parts.join(" ");
let ts = *ev.timestamp.inner();
cm1.add_log(crate::console::ConsoleEntry {
level,
text,
timestamp: ts,
});
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(
init_timeout,
pc.event_listener::<chromiumoxide::cdp::js_protocol::runtime::EventExceptionThrown>(),
)
.await
{
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
let details = &ev.exception_details;
let stack_trace = details
.stack_trace
.as_ref()
.map(crate::console::format_stack_trace);
let ts = *ev.timestamp.inner();
cm2.add_exception(crate::console::JsException {
text: details.text.clone(),
url: details.url.clone(),
line: details.line_number,
column: details.column_number,
stack_trace,
timestamp: ts,
});
}
});
}
// WebSocket monitoring — uses Network domain (already enabled above)
let ws1 = ws.clone();
let ws2 = ws.clone();
let ws3 = ws.clone();
let ws4 = ws.clone();
let ws5 = ws.clone();
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventWebSocketFrameSent>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
ws1.add_frame(crate::websocket::WsFrame {
request_id: ev.request_id.clone().into(),
timestamp: *ev.timestamp.inner(),
opcode: ev.response.opcode.to_string(),
payload: ev.response.payload_data.clone(),
is_sent: true,
});
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventWebSocketFrameReceived>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
ws2.add_frame(crate::websocket::WsFrame {
request_id: ev.request_id.clone().into(),
timestamp: *ev.timestamp.inner(),
opcode: ev.response.opcode.to_string(),
payload: ev.response.payload_data.clone(),
is_sent: false,
});
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventWebSocketCreated>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
ws3.add_event(crate::websocket::WsEvent::Created { request_id: ev.request_id.clone().into(), url: ev.url.clone() });
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventWebSocketClosed>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
ws4.add_event(crate::websocket::WsEvent::Closed { request_id: ev.request_id.clone().into(), timestamp: *ev.timestamp.inner() });
}
});
}
if let Ok(Ok(mut rx)) = tokio::time::timeout(init_timeout, pc.event_listener::<chromiumoxide::cdp::browser_protocol::network::EventWebSocketFrameError>()).await {
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
ws5.add_event(crate::websocket::WsEvent::Error { request_id: ev.request_id.clone().into(), timestamp: *ev.timestamp.inner(), error_message: ev.error_message.clone() });
}
});
}
}
// ── Navigation (auto-wait for page load) ────────────────
/// Navigate to a URL. Automatically waits for page to finish loading.
///
/// The wait behavior is controlled by the load strategy:
/// - `"normal"` (default): waits for the `load` event (full page load)
/// - `"eager"`: waits for `DOMContentLoaded` only (DOM ready, images may still load)
/// - `"none"`: no wait after navigation — returns immediately
///
/// Use `set_load_strategy()` to change the strategy at runtime.
pub async fn get(&self, url: &str) -> Result<()> {
debug!("get({url}) [strategy={}]", self.load_strategy);
self.page()
.goto(url)
.await
.map_err(|e| Error::Browser(format!("navigate: {e}")))?;
match self.load_strategy.as_str() {
"none" => {
// Fire-and-forget: just wait a tiny bit for the navigation to
// actually be dispatched, but don't block on load events.
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
"eager" => {
// Wait for DOMContentLoaded via JS polling
let js =
"document.readyState === 'interactive' || document.readyState === 'complete'";
let timeout_secs = 15u64;
let deadline =
tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
let ready = self
.page()
.evaluate(js)
.await
.ok()
.and_then(|r| r.value().cloned())
.and_then(|v| v.as_bool())
.unwrap_or(false);
if ready {
break;
}
if tokio::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
}
_ => {
// "normal" — default: wait for full load event
self.page()
.wait_for_navigation_response()
.await
.map_err(|e| Error::Browser(format!("wait for load: {e}")))?;
}
}
Ok(())
}
/// Refresh current page. Waits for page to finish loading.
pub async fn refresh(&self) -> Result<()> {
self.page()
.reload()
.await
.map_err(|e| Error::Browser(format!("refresh: {e}")))?;
// Best effort wait for navigation — don't fail if no actual navigation occurs
let _ = tokio::time::timeout(
std::time::Duration::from_secs(3),
self.page().wait_for_navigation_response(),
)
.await;
Ok(())
}
/// Go back. Waits for navigation.
pub async fn back(&self) -> Result<()> {
self.page()
.evaluate("history.back()")
.await
.map_err(|e| Error::Browser(format!("back: {e}")))?;
// Best effort wait for navigation — don't fail for SPAs without real navigation
let _ = tokio::time::timeout(
std::time::Duration::from_secs(3),
self.page().wait_for_navigation_response(),
)
.await;
Ok(())
}
/// Go forward. Waits for navigation.
pub async fn forward(&self) -> Result<()> {
self.page()
.evaluate("history.forward()")
.await
.map_err(|e| Error::Browser(format!("forward: {e}")))?;
// Best effort wait for navigation — don't fail for SPAs without real navigation
let _ = tokio::time::timeout(
std::time::Duration::from_secs(3),
self.page().wait_for_navigation_response(),
)
.await;
Ok(())
}
/// Sleep for the specified duration.
pub async fn sleep(&self, duration: std::time::Duration) {
tokio::time::sleep(duration).await;
}
/// Close the browser.
pub async fn close(&self) -> Result<()> {
self.page()
.execute(chromiumoxide::cdp::browser_protocol::page::CloseParams::default())
.await
.map_err(|e| Error::Browser(format!("close: {e}")))?;
Ok(())
}
// ── Connection status / reconnection (f30) ───────────
/// Check if the browser connection is still alive.
///
/// Tries to fetch `/json/version` from the saved debug URL.
/// Returns `true` if the browser responds, `false` otherwise.
///
/// **This is a blocking call** (uses `reqwest::blocking`). Inside a tokio
/// runtime it will stall a worker thread for the duration of the HTTP
/// request. Prefer [`is_connected_async`](Self::is_connected_async) in any
/// async context. The sync version is retained for non-async callers and
/// diagnostic scripts.
pub fn is_connected(&self) -> bool {
// Synchronous check via reqwest::blocking. See the doc warning above:
// do not call from an async task without spawn_blocking.
let url = format!("{}/json/version", self.debug_url);
reqwest::blocking::get(&url).is_ok()
}
/// Async version of [`is_connected`](Self::is_connected).
///
/// Safe to call from within a tokio runtime. Uses the async reqwest client
/// so it never blocks a worker thread.
pub async fn is_connected_async(&self) -> bool {
let url = format!("{}/json/version", self.debug_url);
// Reuse a short-timeout client so a dead browser fails fast rather than
// hanging on the default connect timeout.
let client = match reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(2))
.build()
{
Ok(c) => c,
Err(_) => return false,
};
client.get(&url).send().await.is_ok()
}
/// Reconnect to the browser using the saved debug URL.
///
/// Drops the current browser/page and creates a fresh CDP connection
/// to the same debug endpoint. Useful when the WebSocket connection
/// was lost but the browser is still running.
pub async fn reconnect(&mut self) -> Result<()> {
info!("Reconnecting to browser at {}", self.debug_url);
let mut new = Self::connect(&self.debug_url).await?;
// Preserve the owned child process: the browser process hasn't changed,
// only our CDP connection has. `new` came from connect() so new.child is
// None; swap our real child into `new`, then swap the whole struct so
// we can't move out of a Drop type field-by-field.
std::mem::swap(
&mut *self.child.lock().unwrap(),
&mut *new.child.lock().unwrap(),
);
std::mem::swap(self, &mut new);
// `new` (now holding the stale connection) is dropped here; its Drop
// sees child == None and does not kill the still-running browser.
Ok(())
}
/// Return the saved debug URL (e.g. `http://localhost:9222`).
pub fn debug_url(&self) -> &str {
&self.debug_url
}
// ── Element finding (auto-retry + JS fallback for all locators) ──
/// Find the first element. Auto-retries for up to configured timeout.
///
/// Supports all locator types: CSS, text=, text*=, xpath:, @attr=, @attr*=,
/// and chained locators (tag:div@@text=Login). Non-CSS locators use a
/// JavaScript-based XPath fallback for maximum reliability.
pub async fn ele(&self, locator_str: &str) -> Result<Element> {
let locator = crate::locator::parse_locator(locator_str)?;
// Handle Chain locator step-by-step
if let crate::locator::Locator::Chain(steps) = &locator {
if steps.is_empty() {
return Err(Error::InvalidLocator("empty chain".into()));
}
let timeout_secs = self.opts.timeout.as_secs();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
// For chains with non-CSS later steps, use JS fallback
let has_non_css = steps.iter().any(|s| !s.is_css());
if has_non_css {
return self.ele_chain_js_fallback(steps, deadline).await;
}
// Pure CSS chain: use CDP native
let first_sel = locator_to_selector(&steps[0])?;
let mut cdp_el = self.wait_for_element(&first_sel, timeout_secs).await?;
for step in steps.iter().skip(1) {
let step_sel = locator_to_selector(step)?;
cdp_el = cdp_el
.find_element(&step_sel)
.await
.map_err(|e| Error::ElementNotFound(format!("chain step: {e}")))?;
}
return self.build_element_from_cdp(cdp_el, locator).await;
}
// Single locator
if locator.is_css() {
let selector = locator_to_selector(&locator)?;
let timeout_secs = self.opts.timeout.as_secs();
let cdp_el = self.wait_for_element(&selector, timeout_secs).await?;
return self.build_element_from_cdp(cdp_el, locator).await;
}
// Non-CSS locator: use JS-based XPath query (reliable in all modes)
let xpath = locator.to_xpath().ok_or_else(|| {
Error::InvalidLocator(format!("cannot convert to xpath: {locator_str}"))
})?;
self.ele_by_xpath_fallback(&xpath, self.opts.timeout.as_secs())
.await
}
/// Static-snapshot element lookup (DrissionPage `s_ele`): grab the page's
/// *current* HTML once and query it with the scraper/XPath engine,
/// returning a detached element that doesn't touch live CDP. Much faster
/// than [`ele`](Self::ele) for bulk read-only extraction; the trade-off is
/// the returned element has no live page handle, so it can't be clicked or
/// typed into (use `ele` for interaction).
pub async fn s_ele(&self, locator_str: &str) -> Result<Element> {
let html = self.html().await?;
crate::session_page::SessionPage::ele_from_html(&html, locator_str)
}
/// Static-snapshot version of [`eles`](Self::eles) (DrissionPage `s_eles`).
pub async fn s_eles(&self, locator_str: &str) -> Result<Vec<Element>> {
let html = self.html().await?;
crate::session_page::SessionPage::eles_from_html(&html, locator_str)
}
// ── 语义定位 (Playwright get_by_*) ────────────────────────
/// Locate by visible text (substring match) — Playwright's `get_by_text`.
pub async fn get_by_text(&self, text: &str) -> Result<Element> {
self.ele(&format!("text:{text}")).await
}
/// Locate a control by its placeholder (substring) — `get_by_placeholder`.
pub async fn get_by_placeholder(&self, placeholder: &str) -> Result<Element> {
self.ele(&format!("@placeholder:{placeholder}")).await
}
/// Locate by `data-testid` (exact) — Playwright's `get_by_test_id`.
pub async fn get_by_test_id(&self, test_id: &str) -> Result<Element> {
self.ele(&format!("@data-testid={test_id}")).await
}
/// Locate by ARIA role — Playwright's `get_by_role`. Matches an explicit
/// `role=` attribute, plus the *implicit* role of common HTML elements
/// (button / link / textbox / checkbox / radio / heading / img / list /
/// listitem). Other roles match an explicit `role` attribute only.
pub async fn get_by_role(&self, role: &str) -> Result<Element> {
let r = role.replace('\'', "\\'");
let implicit = match role {
"button" => {
"self::button or self::input[@type='button' or @type='submit' or @type='reset']"
}
"link" => "self::a[@href]",
"textbox" => "self::textarea or self::input[not(@type) or @type='text' or @type='search' or @type='email' or @type='url' or @type='tel' or @type='password']",
"checkbox" => "self::input[@type='checkbox']",
"radio" => "self::input[@type='radio']",
"heading" => "self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6",
"img" => "self::img",
"list" => "self::ul or self::ol",
"listitem" => "self::li",
_ => "",
};
let xpath = if implicit.is_empty() {
format!("//*[@role='{r}']")
} else {
format!("//*[@role='{r}' or {implicit}]")
};
self.ele(&format!("xpath:{xpath}")).await
}
/// Locate a form control by its associated label — Playwright's
/// `get_by_label`. Matches (in order) `aria-label`, a wrapping `<label>`,
/// or a `<label for=…>` pointing at the control.
pub async fn get_by_label(&self, label: &str) -> Result<Element> {
let l = label.replace('\'', "\\'");
let xpath = format!(
"//*[@aria-label='{l}'] | //label[normalize-space(.)='{l}']//input \
| //label[normalize-space(.)='{l}']//textarea \
| //input[@id=//label[normalize-space(.)='{l}']/@for] \
| //textarea[@id=//label[normalize-space(.)='{l}']/@for]"
);
self.ele(&format!("xpath:{xpath}")).await
}
/// Find all matching elements. Auto-retries for up to configured timeout.
pub async fn eles(&self, locator_str: &str) -> Result<Vec<Element>> {
let locator = crate::locator::parse_locator(locator_str)?;
// Handle Chain locator
if let crate::locator::Locator::Chain(steps) = &locator {
if steps.is_empty() {
return Err(Error::InvalidLocator("empty chain".into()));
}
let has_non_css = steps.iter().any(|s| !s.is_css());
if has_non_css {
return self.eles_chain_js_fallback(steps).await;
}
let first_sel = locator_to_selector(&steps[0])?;
let parent_els = self
.page()
.find_elements(&first_sel)
.await
.map_err(|e| Error::ElementNotFound(format!("chain first step: {e}")))?;
let mut results = Vec::new();
for parent in parent_els {
let mut inner_els = vec![parent];
for step in steps.iter().skip(1) {
let step_sel = locator_to_selector(step)?;
let mut next_els = Vec::new();
for el in &inner_els {
if let Ok(children) = el.find_elements(&step_sel).await {
next_els.extend(children);
}
}
inner_els = next_els;
if inner_els.is_empty() {
break;
}
}
for cdp_el in &inner_els {
let el = self
.build_element_from_cdp_ref(cdp_el, locator.clone())
.await?;
results.push(el);
}
}
return Ok(results);
}
// Single locator
if locator.is_css() {
let selector = locator_to_selector(&locator)?;
let deadline = tokio::time::Instant::now() + self.opts.timeout;
let mut cdp_els = self
.page()
.find_elements(&selector)
.await
.map_err(|e| Error::ElementNotFound(format!("{e}")))?;
while cdp_els.is_empty() && tokio::time::Instant::now() < deadline {
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
cdp_els = self
.page()
.find_elements(&selector)
.await
.map_err(|e| Error::ElementNotFound(format!("{e}")))?;
}
let locator_clone = locator.clone();
let mut results = Vec::with_capacity(cdp_els.len());
if cdp_els.is_empty() {
return Ok(results);
}
for cdp_el in &cdp_els {
let el = self
.build_element_from_cdp_ref(cdp_el, locator_clone.clone())
.await?;
results.push(el);
}
return Ok(results);
}
// Non-CSS: JS fallback
let xpath = locator.to_xpath().ok_or_else(|| {
Error::InvalidLocator(format!("cannot convert to xpath: {locator_str}"))
})?;
self.eles_by_xpath_fallback(&xpath).await
}
// ── JS-based XPath fallback (reliable in connect/headless/all modes) ──
/// Find a single element using XPath via document.evaluate (JS fallback).
async fn ele_by_xpath_fallback(&self, xpath: &str, timeout_secs: u64) -> Result<Element> {
let escaped = json_escape(xpath);
let js = format!(
"(function() {{ \
var result = document.evaluate({xp}, document, null, \
XPathResult.FIRST_ORDERED_NODE_TYPE, null); \
var el = result.singleNodeValue; \
if (!el) return null; \
var r = {{}}; \
r.html = el.outerHTML || ''; \
r.tag = (el.tagName || '').toLowerCase(); \
r.text = el.innerText || el.textContent || ''; \
var attrs = []; \
for (var i = 0; i < el.attributes.length; i++) {{ \
var a = el.attributes[i]; attrs.push([a.name, a.value]); \
}} \
r.attrs = attrs; \
return JSON.stringify(r); \
}})()",
xp = escaped
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
match self.page().evaluate(js.as_str()).await {
Ok(val) => {
if let Some(json_str) = val.value().and_then(|v| v.as_str()) {
if json_str != "null" && !json_str.is_empty() {
let data: serde_json::Value = serde_json::from_str(json_str)
.map_err(|e| Error::Browser(format!("parse xpath result: {e}")))?;
let html = data["html"].as_str().unwrap_or_default().to_string();
let tag = data["tag"].as_str().unwrap_or_default().to_string();
let text = data["text"].as_str().unwrap_or_default().to_string();
let attrs: Vec<(String, String)> = data["attrs"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|item| {
let a = item.as_array()?;
Some((
a.first()?.as_str()?.to_string(),
a.get(1)?.as_str()?.to_string(),
))
})
.collect()
})
.unwrap_or_default();
return Ok(Element::new_cdp(
self.page().clone(),
String::new(),
Some(crate::locator::Locator::XPath(xpath.to_string())),
html,
tag,
text,
attrs,
Some(xpath.to_string()), // fallback_xpath for JS-based interactions
));
}
}
}
Err(_) => {}
}
if std::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
Err(Error::ElementNotFound(format!(
"xpath not found after {timeout_secs}s: {xpath}"
)))
}
/// Find all elements using XPath via document.evaluate (JS fallback).
async fn eles_by_xpath_fallback(&self, xpath: &str) -> Result<Vec<Element>> {
let escaped = json_escape(xpath);
let js = format!(
"(function() {{ \
var result = document.evaluate({xp}, document, null, \
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); \
var items = []; \
for (var i = 0; i < result.snapshotLength; i++) {{ \
var el = result.snapshotItem(i); \
var r = {{}}; \
r.html = el.outerHTML || ''; \
r.tag = (el.tagName || '').toLowerCase(); \
r.text = el.innerText || el.textContent || ''; \
var attrs = []; \
for (var j = 0; j < el.attributes.length; j++) {{ \
var a = el.attributes[j]; attrs.push([a.name, a.value]); \
}} \
r.attrs = attrs; \
items.push(r); \
}} \
return JSON.stringify(items); \
}})()",
xp = escaped
);
let val = self
.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("xpath eval: {e}")))?;
let json_str = val.value().and_then(|v| v.as_str()).unwrap_or("[]");
let arr: Vec<serde_json::Value> = serde_json::from_str(json_str)
.map_err(|e| Error::Browser(format!("parse xpath results: {e}")))?;
let mut results = Vec::with_capacity(arr.len());
for data in &arr {
let html = data["html"].as_str().unwrap_or_default().to_string();
let tag = data["tag"].as_str().unwrap_or_default().to_string();
let text = data["text"].as_str().unwrap_or_default().to_string();
let attrs: Vec<(String, String)> = data["attrs"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|item| {
let arr = item.as_array()?;
Some((
arr.first()?.as_str()?.to_string(),
arr.get(1)?.as_str()?.to_string(),
))
})
.collect()
})
.unwrap_or_default();
results.push(Element::new_cdp(
self.page().clone(),
String::new(),
Some(crate::locator::Locator::XPath(xpath.to_string())),
html,
tag,
text,
attrs,
None,
));
}
Ok(results)
}
/// Chain locator with JS fallback for non-CSS steps.
async fn ele_chain_js_fallback(
&self,
steps: &[crate::locator::Locator],
deadline: std::time::Instant,
) -> Result<Element> {
// Build combined XPath: scope each step within previous
let mut xpath_parts: Vec<String> = Vec::new();
for step in steps {
match step {
crate::locator::Locator::Css(sel) => {
// Convert simple CSS to XPath
let xp = if sel.contains(' ')
|| sel.contains('>')
|| sel.contains('.')
|| sel.contains('#')
|| sel.contains('[')
{
// Complex CSS: use it as-is via a JS workaround
format!("descendant::*[self::div]/**") // placeholder, will handle below
} else {
format!("descendant::{sel}")
};
xpath_parts.push(xp);
}
_ => {
if let Some(xp) = step.to_xpath() {
xpath_parts.push(xp);
}
}
}
}
// For chains with CSS, build a combined JS approach
let combined_xpath = xpath_parts.join("/");
loop {
match self.ele_by_xpath_fallback(&combined_xpath, 1).await {
Ok(el) => return Ok(el),
Err(_) => {}
}
// Also try step-by-step approach
if let Ok(first_sel) = locator_to_selector(&steps[0]) {
if let Ok(first_el) = self.page().find_element(&first_sel).await {
let mut cdp_el = first_el;
let mut found = true;
for step in steps.iter().skip(1) {
// Try CDP native
if let Ok(sel) = locator_to_selector(step) {
match cdp_el.find_element(&sel).await {
Ok(child) => cdp_el = child,
Err(_) => {
// Try JS fallback within this element
found = false;
break;
}
}
}
}
if found {
return self
.build_element_from_cdp(
cdp_el,
crate::locator::Locator::Chain(steps.to_vec()),
)
.await;
}
}
}
if std::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
Err(Error::ElementNotFound(format!(
"chain not found: {}",
steps
.iter()
.map(|s| format!("{s:?}"))
.collect::<Vec<_>>()
.join(" -> ")
)))
}
/// Chain locator for eles() with JS fallback.
async fn eles_chain_js_fallback(
&self,
steps: &[crate::locator::Locator],
) -> Result<Vec<Element>> {
// Simplified: use combined XPath
let xpath_parts: Vec<String> = steps.iter().filter_map(|s| s.to_xpath()).collect();
let combined = xpath_parts.join("/");
self.eles_by_xpath_fallback(&combined).await
}
// ── Shadow DOM piercing ──────────────────────────────────
/// Find an element inside a Shadow DOM host.
///
/// Usage: `page.shadow_ele("#host >>> .inner")` — finds `#host`, then
/// penetrates its shadowRoot and runs `querySelector(".inner")`.
///
/// For multi-level piercing use `>>>` separator:
/// `page.shadow_ele("#host >>> .mid >>> .inner")`
pub async fn shadow_ele(&self, locator_str: &str) -> Result<Element> {
let parts: Vec<&str> = locator_str.split(">>>").map(|s| s.trim()).collect();
if parts.len() < 2 {
return Err(Error::InvalidLocator(
"shadow_ele requires at least 'host >>> inner' format".into(),
));
}
let host_sel = json_escape(parts[0]);
let inner_sels: Vec<String> = parts[1..].iter().map(json_escape).collect();
// Build recursive JS for shadow DOM piercing
let query_js = build_shadow_query_js(&host_sel, &inner_sels);
let timeout_secs = self.opts.timeout.as_secs();
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
#[allow(unused_assignments)]
let mut last_err = String::from("timeout");
loop {
match self.build_element_from_shadow_js(&query_js).await {
Ok(el) => return Ok(el),
Err(e) => {
last_err = format!("{e}");
}
}
if tokio::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
Err(Error::ElementNotFound(format!(
"shadow_ele not found after {timeout_secs}s: {last_err}"
)))
}
/// Find all elements inside a Shadow DOM host.
///
/// Usage: `page.shadow_eles("#host >>> .inner")`
pub async fn shadow_eles(&self, locator_str: &str) -> Result<Vec<Element>> {
let parts: Vec<&str> = locator_str.split(">>>").map(|s| s.trim()).collect();
if parts.len() < 2 {
return Err(Error::InvalidLocator(
"shadow_eles requires at least 'host >>> inner' format".into(),
));
}
let host_sel = json_escape(parts[0]);
let inner_sels: Vec<String> = parts[1..].iter().map(json_escape).collect();
let query_js = build_shadow_query_all_js(&host_sel, &inner_sels);
let timeout_secs = self.opts.timeout.as_secs();
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
match self.shadow_eles_from_js(&query_js).await {
Ok(els) => {
if !els.is_empty() || tokio::time::Instant::now() >= deadline {
return Ok(els);
}
}
Err(_) => {
if tokio::time::Instant::now() >= deadline {
return Ok(Vec::new());
}
}
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Build an Element from shadow DOM JS query (single element).
async fn build_element_from_shadow_js(&self, query_js: &str) -> Result<Element> {
let full_js = format!(
"(function() {{ \
var el = ({query_js}); \
if (!el) return null; \
var r = {{}}; \
r.html = el.outerHTML; \
r.tag = el.tagName.toLowerCase(); \
r.text = el.innerText || ''; \
var attrs = []; \
for (var i = 0; i < el.attributes.length; i++) {{ \
var a = el.attributes[i]; \
attrs.push([a.name, a.value]); \
}} \
r.attrs = attrs; \
return JSON.stringify(r); \
}})()"
);
let result = self
.page()
.evaluate(full_js.as_str())
.await
.map_err(|e| Error::Browser(format!("shadow query: {e}")))?;
let json_str = result
.value()
.and_then(|v| v.as_str())
.ok_or_else(|| Error::ElementNotFound("shadow element not found".into()))?;
let data: serde_json::Value = serde_json::from_str(json_str)
.map_err(|e| Error::Browser(format!("parse shadow result: {e}")))?;
let html = data["html"].as_str().unwrap_or_default().to_string();
let tag = data["tag"].as_str().unwrap_or_default().to_string();
let text = data["text"].as_str().unwrap_or_default().to_string();
let attrs: Vec<(String, String)> = data["attrs"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|item| {
let a = item.as_array()?;
Some((
a.first()?.as_str()?.to_string(),
a.get(1)?.as_str()?.to_string(),
))
})
.collect()
})
.unwrap_or_default();
let locator = crate::locator::Locator::Css("shadow".into());
Ok(Element::new_cdp(
self.page().clone(),
String::new(), // no direct object_id from JS eval
Some(locator),
html,
tag,
text,
attrs,
None,
))
}
/// Get multiple elements from shadow DOM JS query.
async fn shadow_eles_from_js(&self, query_js: &str) -> Result<Vec<Element>> {
let full_js = format!(
"(function() {{ \
var els = ({query_js}); \
if (!els || !els.length) return JSON.stringify([]); \
var results = []; \
for (var i = 0; i < els.length; i++) {{ \
var el = els[i]; \
var r = {{}}; \
r.html = el.outerHTML; \
r.tag = el.tagName.toLowerCase(); \
r.text = el.innerText || ''; \
var attrs = []; \
for (var j = 0; j < el.attributes.length; j++) {{ \
var a = el.attributes[j]; \
attrs.push([a.name, a.value]); \
}} \
r.attrs = attrs; \
results.push(r); \
}} \
return JSON.stringify(results); \
}})()"
);
let result = self
.page()
.evaluate(full_js.as_str())
.await
.map_err(|e| Error::Browser(format!("shadow query all: {e}")))?;
let json_str = result.value().and_then(|v| v.as_str()).unwrap_or("[]");
let items: Vec<serde_json::Value> = serde_json::from_str(json_str)
.map_err(|e| Error::Browser(format!("parse shadow results: {e}")))?;
let locator = crate::locator::Locator::Css("shadow".into());
let mut elements = Vec::with_capacity(items.len());
for data in &items {
let html = data["html"].as_str().unwrap_or_default().to_string();
let tag = data["tag"].as_str().unwrap_or_default().to_string();
let text = data["text"].as_str().unwrap_or_default().to_string();
let attrs: Vec<(String, String)> = data["attrs"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|item| {
let a = item.as_array()?;
Some((
a.first()?.as_str()?.to_string(),
a.get(1)?.as_str()?.to_string(),
))
})
.collect()
})
.unwrap_or_default();
elements.push(Element::new_cdp(
self.page().clone(),
String::new(),
Some(locator.clone()),
html,
tag,
text,
attrs,
None,
));
}
Ok(elements)
}
// ── Internal helpers ─────────────────────────────────────
/// Wait for an element to appear, retrying for `timeout_secs` seconds.
async fn wait_for_element(
&self,
selector: &str,
timeout_secs: u64,
) -> Result<chromiumoxide::Element> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
#[allow(unused_assignments)]
let mut last_err = String::from("timeout");
while tokio::time::Instant::now() < deadline {
match self.page().find_element(selector).await {
Ok(el) => return Ok(el),
Err(e) => {
last_err = format!("{e}");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
}
Err(Error::ElementNotFound(format!(
"not found after {timeout_secs}s: {last_err}"
)))
}
/// Build an rpage Element from a CDP Element.
async fn build_element_from_cdp_inner(
&self,
cdp_el: &chromiumoxide::Element,
locator: crate::locator::Locator,
) -> Result<Element> {
let html = cdp_el.outer_html().await.ok().flatten().unwrap_or_default();
let text = cdp_el.inner_text().await.ok().flatten().unwrap_or_default();
let tag = cdp_el
.string_property("tagName")
.await
.ok()
.flatten()
.unwrap_or_default()
.to_lowercase();
let attrs = cdp_el
.call_js_fn(
"function(){ var r=[]; for(var i=0;i<this.attributes.length;i++){var a=this.attributes[i]; r.push([a.name,a.value]);} return JSON.stringify(r); }",
false,
)
.await
.ok()
.and_then(|r| {
r.result.value.and_then(|v| serde_json::from_value(v).ok())
})
.unwrap_or_default();
Ok(Element::new_cdp(
self.page().clone(),
cdp_el.remote_object_id.clone().into(),
Some(locator),
html,
tag,
text,
attrs,
None,
))
}
/// Build an rpage Element from an owned CDP Element.
async fn build_element_from_cdp(
&self,
cdp_el: chromiumoxide::Element,
locator: crate::locator::Locator,
) -> Result<Element> {
self.build_element_from_cdp_inner(&cdp_el, locator).await
}
/// Build an rpage Element from a CDP Element reference.
async fn build_element_from_cdp_ref(
&self,
cdp_el: &chromiumoxide::Element,
locator: crate::locator::Locator,
) -> Result<Element> {
self.build_element_from_cdp_inner(cdp_el, locator).await
}
// ── Page info ────────────────────────────────────────────
/// Page HTML.
pub async fn html(&self) -> Result<String> {
self.page()
.content()
.await
.map_err(|e| Error::Browser(format!("content: {e}")))
}
/// Page title.
pub async fn title(&self) -> Result<String> {
self.page()
.get_title()
.await
.map_err(|e| Error::Browser(format!("title: {e}")))
.map(|t| t.unwrap_or_default())
}
/// Current URL.
pub async fn url(&self) -> Result<String> {
self.page()
.url()
.await
.map_err(|e| Error::Browser(format!("url: {e}")))
.map(|u| u.unwrap_or_default())
}
// ── JavaScript ───────────────────────────────────────────
/// Execute JS, return the value.
pub async fn execute(&self, js: &str) -> Result<serde_json::Value> {
let r = self
.page()
.evaluate(js)
.await
.map_err(|e| Error::Browser(format!("eval: {e}")))?;
Ok(r.value().cloned().unwrap_or(serde_json::Value::Null))
}
/// Read text from the clipboard via `navigator.clipboard.readText()`.
///
/// The page must be focused and have clipboard-read permission.
/// Use `grant_permissions(origin, vec!["clipboard-read".into()])` if needed.
pub async fn clipboard_read(&self) -> Result<String> {
let val = self.execute("navigator.clipboard.readText()").await?;
val.as_str()
.map(|s| s.to_string())
.ok_or_else(|| Error::Browser("clipboard read failed".into()))
}
/// Write text to the clipboard via `navigator.clipboard.writeText(text)`.
///
/// The page must be focused and have clipboard-write permission.
/// Use `grant_permissions(origin, vec!["clipboard-write".into()])` if needed.
pub async fn clipboard_write(&self, text: &str) -> Result<()> {
let js = format!(
"navigator.clipboard.writeText({})",
serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string())
);
self.execute(&js).await?;
Ok(())
}
/// Execute an async JavaScript expression and wait for the Promise to resolve.
///
/// Uses CDP `Runtime.evaluate` with `awaitPromise = true` so that `fetch()`,
/// `new Promise()`, and other async patterns complete before returning.
///
/// ```ignore
/// let json = page.run_async_js("fetch('https://api.example.com/data').then(r => r.json())").await?;
/// ```
pub async fn run_async_js(&self, expression: &str) -> Result<serde_json::Value> {
use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;
let params = EvaluateParams::builder()
.expression(expression)
.await_promise(true)
.return_by_value(true)
.build()
.map_err(|e| Error::Browser(format!("run_async_js build: {e}")))?;
let r = self
.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("run_async_js: {e}")))?;
Ok(r.result
.result
.value
.clone()
.unwrap_or(serde_json::Value::Null))
}
/// Execute a JavaScript function with arguments passed as a JSON value.
///
/// The `expression` should be a function declaration. The `args` value is
/// serialised and passed as the first argument. Returns the result as a
/// `serde_json::Value`.
///
/// ```ignore
/// let args = serde_json::json!({"selector": "#content"});
/// let text = page.run_js_with_args(
/// "(a) => { let el = document.querySelector(a.selector); return el ? el.innerText : ''; }",
/// args,
/// ).await?;
/// ```
pub async fn run_js_with_args(
&self,
expression: &str,
args: serde_json::Value,
) -> Result<serde_json::Value> {
let args_json = serde_json::to_string(&args).unwrap_or_else(|_| "undefined".to_string());
let escaped_args = args_json.replace('\\', "\\\\").replace('\'', "\\'");
let js = format!(
"(function(){{ var args = JSON.parse('{}'); return ({expr})(args); }})()",
escaped_args,
expr = expression
);
self.execute(&js).await
}
/// Wait for a download whose URL contains `url_pattern` to complete.
///
/// Polls the download manager for a download matching the given URL
/// substring. Returns the [`DownloadInfo`](crate::download::DownloadInfo)
/// once the download reaches a terminal state (completed, cancelled, or
/// failed), or times out after `timeout_secs` seconds.
///
/// ```ignore
/// let dl = page.wait_for_download("/files/report.pdf", 30).await?;
/// println!("Saved to: {:?}", dl.save_path);
/// ```
pub async fn wait_for_download(
&self,
url_pattern: &str,
timeout_secs: u64,
) -> Result<crate::download::DownloadInfo> {
let start = std::time::Instant::now();
let duration = std::time::Duration::from_secs(timeout_secs);
loop {
let list = self.download_manager.list();
if let Some(dl) = list.iter().find(|d| d.url.contains(url_pattern)) {
if !matches!(dl.status, crate::download::DownloadStatus::InProgress) {
return Ok(dl.clone());
}
}
if start.elapsed() > duration {
return Err(Error::Timeout(format!(
"wait_for_download timed out waiting for pattern: {url_pattern}"
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Get the `Content-Type` header of the current page's main document.
///
/// Uses `document.contentType` when available (e.g. XML documents) and
/// falls back to `"text/html"` for standard HTML pages.
///
/// ```ignore
/// let ct = page.get_content_type().await?;
/// assert_eq!(ct, "text/html");
/// ```
pub async fn get_content_type(&self) -> Result<String> {
let val = self.execute("document.contentType || 'text/html'").await?;
val.as_str()
.map(|s| s.to_string())
.ok_or_else(|| Error::Browser("get_content_type failed".into()))
}
/// Select all text on the page (Ctrl+A).
///
/// Sends Ctrl+A keyboard shortcut via CDP input events.
pub async fn select_all_text(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key("a")
.code("KeyA")
.windows_virtual_key_code(0x41)
.native_virtual_key_code(0x41)
.modifiers(2) // Control
.build()
.map_err(|e| Error::Browser(format!("select_all_text build: {e}")))?;
self.page()
.execute(key_down)
.await
.map_err(|e| Error::Browser(format!("select_all_text: {e}")))?;
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key("a")
.code("KeyA")
.windows_virtual_key_code(0x41)
.native_virtual_key_code(0x41)
.modifiers(2)
.build()
.map_err(|e| Error::Browser(format!("select_all_text up build: {e}")))?;
self.page()
.execute(key_up)
.await
.map_err(|e| Error::Browser(format!("select_all_text up: {e}")))?;
Ok(())
}
/// Copy the currently selected text to the clipboard (Ctrl+C).
///
/// Sends Ctrl+C keyboard shortcut via CDP input events.
pub async fn copy_text(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key("c")
.code("KeyC")
.windows_virtual_key_code(0x43)
.native_virtual_key_code(0x43)
.modifiers(2) // Control
.build()
.map_err(|e| Error::Browser(format!("copy_text build: {e}")))?;
self.page()
.execute(key_down)
.await
.map_err(|e| Error::Browser(format!("copy_text: {e}")))?;
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key("c")
.code("KeyC")
.windows_virtual_key_code(0x43)
.native_virtual_key_code(0x43)
.modifiers(2)
.build()
.map_err(|e| Error::Browser(format!("copy_text up build: {e}")))?;
self.page()
.execute(key_up)
.await
.map_err(|e| Error::Browser(format!("copy_text up: {e}")))?;
Ok(())
}
/// Paste text from the clipboard (Ctrl+V).
///
/// Sends Ctrl+V keyboard shortcut via CDP input events.
pub async fn paste_text(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
let key_down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key("v")
.code("KeyV")
.windows_virtual_key_code(0x56)
.native_virtual_key_code(0x56)
.modifiers(2) // Control
.build()
.map_err(|e| Error::Browser(format!("paste_text build: {e}")))?;
self.page()
.execute(key_down)
.await
.map_err(|e| Error::Browser(format!("paste_text: {e}")))?;
let key_up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key("v")
.code("KeyV")
.windows_virtual_key_code(0x56)
.native_virtual_key_code(0x56)
.modifiers(2)
.build()
.map_err(|e| Error::Browser(format!("paste_text up build: {e}")))?;
self.page()
.execute(key_up)
.await
.map_err(|e| Error::Browser(format!("paste_text up: {e}")))?;
Ok(())
}
/// Search for `text` on the current page.
///
/// Uses the browser's built-in `window.find()` API. Returns `true` if a
/// match was found, `false` otherwise.
///
/// ```ignore
/// if page.find_text("Welcome").await? {
/// println!("Found!");
/// }
/// ```
pub async fn find_text(&self, text: &str) -> Result<bool> {
let escaped = json_escape(text);
let js = format!("window.find({escaped})");
let val = self.execute(&js).await?;
Ok(val.as_bool().unwrap_or(false))
}
/// Execute JS on every new document.
pub async fn evaluate_on_new_document(&self, js: &str) -> Result<()> {
self.page()
.evaluate_on_new_document(js)
.await
.map_err(|e| Error::Browser(format!("init script: {e}")))?;
Ok(())
}
/// Register a named init script that runs on every new document.
///
/// The script is stored locally and registered via
/// `Page.addScriptToEvaluateOnNewDocument`. Use `remove_init_script`
/// to unregister it later.
pub async fn add_init_script(&self, name: &str, js: &str) -> Result<()> {
let params = AddScriptToEvaluateOnNewDocumentParams::new(js);
let result = self
.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("add_init_script: {e}")))?;
self.init_scripts
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(name.to_string(), js.to_string());
self.init_script_ids
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(name.to_string(), result.identifier.clone());
Ok(())
}
/// Remove a previously registered named init script.
///
/// Looks up the CDP identifier and calls
/// `Page.removeScriptToEvaluateOnNewDocument`.
pub async fn remove_init_script(&self, name: &str) -> Result<()> {
let id = self
.init_script_ids
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(name)
.ok_or_else(|| Error::Browser(format!("init script not found: {name}")))?;
self.init_scripts
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(name);
let params = RemoveScriptToEvaluateOnNewDocumentParams::new(id);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("remove_init_script: {e}")))?;
Ok(())
}
/// List all registered init script names.
pub fn list_init_scripts(&self) -> Vec<String> {
self.init_scripts
.lock()
.unwrap_or_else(|e| e.into_inner())
.keys()
.cloned()
.collect()
}
// ── Screenshot ───────────────────────────────────────────
/// Screenshot → PNG bytes.
pub async fn screenshot_bytes(&self) -> Result<Vec<u8>> {
use chromiumoxide::page::ScreenshotParams;
self.page()
.screenshot(ScreenshotParams::builder().build())
.await
.map_err(|e| Error::Browser(format!("screenshot: {e}")))
}
/// Screenshot → file.
pub async fn screenshot(&self, path: &str) -> Result<()> {
let bytes = self.screenshot_bytes().await?;
std::fs::write(path, bytes)?;
Ok(())
}
// ── Cookies ──────────────────────────────────────────────
/// Get all cookies.
pub async fn cookies(&self) -> Result<Vec<CookieInfo>> {
let cookies = self
.page()
.get_cookies()
.await
.map_err(|e| Error::Browser(format!("cookies: {e}")))?;
Ok(cookies
.iter()
.map(|c| CookieInfo {
name: c.name.clone(),
value: c.value.clone(),
domain: Some(c.domain.clone()),
path: Some(c.path.clone()),
secure: c.secure,
http_only: c.http_only,
})
.collect())
}
/// Set a cookie.
pub async fn set_cookie(&self, cookie: CookieInfo) -> Result<()> {
let mut cp = CookieParam::new(&cookie.name, &cookie.value);
if let Some(ref d) = cookie.domain {
cp.domain = Some(d.clone());
}
if let Some(ref p) = cookie.path {
cp.path = Some(p.clone());
}
if cookie.secure {
cp.secure = Some(true);
}
if cookie.http_only {
cp.http_only = Some(true);
}
self.page()
.set_cookie(cp)
.await
.map_err(|e| Error::Browser(format!("set cookie: {e}")))?;
Ok(())
}
// ── Tabs ─────────────────────────────────────────────────
/// Get all open pages/tabs.
pub async fn tabs(&self) -> Result<Vec<Page>> {
self.browser
.pages()
.await
.map_err(|e| Error::Browser(format!("tabs: {e}")))
}
/// Open a new tab.
pub async fn new_tab(&self) -> Result<Page> {
self.browser
.new_page("about:blank")
.await
.map_err(|e| Error::Browser(format!("new tab: {e}")))
}
/// Get all tab titles.
pub async fn tab_titles(&self) -> Result<Vec<String>> {
let pages = self
.browser
.pages()
.await
.map_err(|e| Error::Browser(format!("pages: {e}")))?;
let mut titles = Vec::new();
for p in &pages {
if let Ok(t) = p.get_title().await {
titles.push(t.unwrap_or_default());
}
}
Ok(titles)
}
/// Get all tab URLs.
pub async fn tab_urls(&self) -> Result<Vec<String>> {
let pages = self
.browser
.pages()
.await
.map_err(|e| Error::Browser(format!("pages: {e}")))?;
let mut urls = Vec::new();
for p in &pages {
if let Ok(u) = p.url().await {
urls.push(u.unwrap_or_default());
}
}
Ok(urls)
}
/// Switch to a tab by its index (0-based). Brings the tab to front.
pub async fn switch_to_tab(&self, index: usize) -> Result<()> {
let pages = self
.browser
.pages()
.await
.map_err(|e| Error::Browser(format!("pages: {e}")))?;
let target = pages
.get(index)
.ok_or_else(|| Error::ElementNotFound(format!("tab index {index}")))?;
target
.bring_to_front()
.await
.map_err(|e| Error::Browser(format!("bring_to_front: {e}")))?;
Ok(())
}
/// Close a tab by index.
pub async fn close_tab(&self, index: usize) -> Result<()> {
let pages = self
.browser
.pages()
.await
.map_err(|e| Error::Browser(format!("pages: {e}")))?;
let target = pages
.get(index)
.ok_or_else(|| Error::ElementNotFound(format!("tab index {index}")))?;
target
.execute(chromiumoxide::cdp::browser_protocol::page::CloseParams::default())
.await
.map_err(|e| Error::Browser(format!("close_tab: {e}")))?;
Ok(())
}
// ── Conditional wait ───────────────────────────────────
/// Wait for an element matching the locator to appear.
pub async fn wait_ele(&self, locator_str: &str, timeout_secs: u64) -> Result<Element> {
let locator = crate::locator::parse_locator(locator_str)?;
// CSS locator: use CDP querySelector (fast)
if locator.is_css() {
let selector = locator_to_selector(&locator)?;
let deadline =
tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
match self.page().find_element(&selector).await {
Ok(cdp_el) => {
return self.build_element_from_cdp(cdp_el, locator).await;
}
Err(_) => {
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_ele '{}' timed out after {}s",
locator_str, timeout_secs
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
}
}
// Non-CSS locator (text=, xpath:, etc.): use JS XPath fallback
let xpath = locator.to_xpath().ok_or_else(|| {
Error::InvalidLocator(format!("cannot convert to xpath: {locator_str}"))
})?;
self.ele_by_xpath_fallback(&xpath, timeout_secs).await
}
/// Wait for an element matching the locator to become hidden or be removed.
pub async fn wait_ele_hidden(&self, locator_str: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
let selector = {
let locator = crate::locator::parse_locator(locator_str)?;
locator_to_selector(&locator)?
};
loop {
match self.page().find_element(&selector).await {
Ok(_) => {
// Element still exists, check if visible via JS
let escaped = selector.replace('\\', "\\\\").replace('\'', "\\'");
let js = format!(
"!!(document.querySelector('{s}')?.offsetWidth || document.querySelector('{s}')?.offsetHeight)",
s = escaped
);
let visible = self
.page()
.evaluate(js.as_str())
.await
.ok()
.and_then(|r| r.value().cloned())
.and_then(|v| v.as_bool())
.unwrap_or(true);
if !visible {
return Ok(());
}
}
Err(_) => {
// Element not found = gone
return Ok(());
}
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_ele_hidden '{}' timed out after {}s",
locator_str, timeout_secs
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Wait for an element matching the locator to be removed from the DOM entirely.
pub async fn wait_ele_deleted(&self, locator_str: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
let selector = {
let locator = crate::locator::parse_locator(locator_str)?;
locator_to_selector(&locator)?
};
loop {
match self.page().find_element(&selector).await {
Ok(_) => {
// Still exists
}
Err(_) => {
// Element gone
return Ok(());
}
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_ele_deleted '{}' timed out after {}s",
locator_str, timeout_secs
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Wait for page title to contain the given text.
pub async fn wait_title_contains(&self, text: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
let title = self.title().await.unwrap_or_default();
if title.contains(text) {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!("wait_title '{}' timed out", text)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Wait for URL to contain the given text.
pub async fn wait_url_contains(&self, text: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
let url = self.url().await.unwrap_or_default();
if url.contains(text) {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!("wait_url '{}' timed out", text)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
// ── Runtime configuration ──────────────────────────────
/// Set extra HTTP headers for all subsequent requests.
pub async fn set_extra_headers(
&self,
headers: std::collections::HashMap<String, String>,
) -> Result<()> {
crate::network::set_extra_headers(&self.page(), headers).await
}
/// Override user agent at runtime.
pub async fn set_user_agent(&self, user_agent: &str) -> Result<()> {
crate::network::set_user_agent(&self.page(), user_agent).await
}
/// Set proxy authentication credentials.
///
/// Sends a `Proxy-Authorization: Basic <base64(user:pass)>` header via
/// `Network.setExtraHTTPHeaders` so that subsequent requests through
/// the proxy include valid credentials.
///
/// Make sure the browser was launched with `--proxy-server` (either via
/// `ChromiumOptions::proxy` or manually) before calling this method.
pub async fn set_proxy_auth(&self, user: &str, pass: &str) -> Result<()> {
use base64::Engine;
let credentials = format!("{user}:{pass}");
let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
let auth_value = format!("Basic {encoded}");
let mut headers = std::collections::HashMap::new();
headers.insert("Proxy-Authorization".to_string(), auth_value);
crate::network::set_extra_headers(&self.page(), headers).await
}
// ── Browser lifecycle ───────────────────────────────────
/// Quit the browser entirely (kills Chrome process).
///
/// Issues a graceful CDP `Browser.close` and, if we spawned Chrome ourselves,
/// reaps the child process. After this returns, `Drop` will find no child
/// to kill (idempotent shutdown).
pub async fn quit(&self) -> Result<()> {
// Use CDP Browser.close to gracefully shut down
use chromiumoxide::cdp::browser_protocol::browser::CloseParams;
let close_result = self
.page()
.execute(CloseParams::default())
.await
.map(|_| ()) // discard CommandResponse; success is all we care about
.map_err(|e| Error::Browser(format!("quit: {e}")));
// Whether or not the CDP close succeeded, reap the child we own so
// there is no orphan. Drop::drop would also do this, but doing it here
// lets us report the real exit status and avoids a race where CDP
// close + Drop kill interleave.
if let Ok(mut guard) = self.child.lock() {
if let Some(mut child) = guard.take() {
let _ = child.kill();
let _ = child.wait();
}
}
close_result
}
// ── Scroll ──────────────────────────────────────────────
/// Scroll the page to absolute position.
pub async fn scroll_to(&self, x: u32, y: u32) -> Result<()> {
self.page()
.evaluate(format!("window.scrollTo({x}, {y})"))
.await
.map_err(|e| Error::Browser(format!("scroll: {e}")))?;
Ok(())
}
/// Scroll to the top of the page.
pub async fn scroll_to_top(&self) -> Result<()> {
self.scroll_to(0, 0).await
}
/// Scroll to the bottom of the page.
pub async fn scroll_to_bottom(&self) -> Result<()> {
let js = "window.scrollTo(0, document.body.scrollHeight)";
self.page()
.evaluate(js)
.await
.map_err(|e| Error::Browser(format!("scroll bottom: {e}")))?;
Ok(())
}
/// Scroll up by `pixels`.
pub async fn scroll_up(&self, pixels: u32) -> Result<()> {
let js = format!("window.scrollBy(0, -{pixels})");
self.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("scroll up: {e}")))?;
Ok(())
}
/// Scroll down by `pixels`.
pub async fn scroll_down(&self, pixels: u32) -> Result<()> {
let js = format!("window.scrollBy(0, {pixels})");
self.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("scroll down: {e}")))?;
Ok(())
}
// ── Dialog / Alert ─────────────────────────────────────
/// Handle a JavaScript dialog (alert/confirm/prompt).
/// `accept`: true = accept (OK), false = dismiss (Cancel)
/// `text`: prompt text to enter (only for prompt dialogs)
pub async fn handle_alert(&self, accept: bool, text: Option<&str>) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::page::HandleJavaScriptDialogParams;
let mut params = HandleJavaScriptDialogParams::new(accept);
if let Some(t) = text {
params.prompt_text = Some(t.into());
}
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("handle dialog: {e}")))?;
Ok(())
}
// ── Frames ──────────────────────────────────────────────
/// Get the HTML content of an iframe identified by CSS selector.
pub async fn frame_html(&self, selector: &str) -> Result<String> {
let js = format!(
"document.querySelector({sel}).contentDocument.documentElement.outerHTML",
sel = json_escape(selector)
);
self.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("frame html: {e}")))?
.value()
.cloned()
.map(|v| v.as_str().unwrap_or_default().to_string())
.ok_or_else(|| Error::Browser("frame html: no result".into()))
}
/// Execute JavaScript inside an iframe identified by CSS selector.
pub async fn frame_execute(&self, selector: &str, js_code: &str) -> Result<serde_json::Value> {
let js = format!(
"(function(){{ \
var f = document.querySelector({sel}); \
if(!f || !f.contentDocument) return null; \
return (function(){{ {code} }}).call(f.contentWindow); \
}})()",
sel = json_escape(selector),
code = js_code
);
let r = self
.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("frame execute: {e}")))?;
Ok(r.value().cloned().unwrap_or(serde_json::Value::Null))
}
// ── Cookie management ───────────────────────────────────
/// Delete a cookie by name. Uses the current page URL as the domain hint
/// (required by Chrome 149+).
pub async fn delete_cookie(&self, name: &str) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::network::DeleteCookiesParams;
let url = self.url().await.unwrap_or_default();
let mut builder = DeleteCookiesParams::builder().name(name);
if !url.is_empty() {
builder = builder.url(&url);
}
let params = builder.build().map_err(Error::Browser)?;
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("delete cookie: {e}")))?;
Ok(())
}
/// Clear all cookies for the current page.
pub async fn clear_cookies(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::network::ClearBrowserCookiesParams;
self.page()
.execute(ClearBrowserCookiesParams::default())
.await
.map_err(|e| Error::Browser(format!("clear cookies: {e}")))?;
Ok(())
}
// ── Multi-window management (f26) ──────────────────────────
/// Return the `user_data_dir` configured for this instance (if any).
pub fn user_data_dir(&self) -> Option<&PathBuf> {
self.opts.user_data_dir.as_ref()
}
/// Read all cookies from `self` and write them into `other`.
///
/// This is a CDP-level copy — cookies are read from the source browser
/// and set on the target browser via `Network.setCookie`.
pub async fn share_cookies_to(&self, other: &ChromiumPage) -> Result<()> {
let all_cookies = self.cookies().await?;
for c in all_cookies {
other.set_cookie(c).await?;
}
Ok(())
}
/// Clone this session: launch a **new** browser instance that shares
/// the same `user_data_dir`, then copy all cookies into it.
///
/// If the original instance has no explicit `user_data_dir`, a new
/// temporary directory is created for the clone (cookies are still
/// copied via CDP).
pub async fn clone_session(&self) -> Result<ChromiumPage> {
let mut opts = self.opts.clone();
// Assign a different debug port to avoid conflicts with `default_debug_port()`
opts.debug_port = crate::config::default_debug_port().wrapping_add(1);
// If no user_data_dir was set, generate a unique temp one
if opts.user_data_dir.is_none() {
opts.user_data_dir =
Some(std::env::temp_dir().join(format!("rpage-clone-{}", std::process::id())));
}
let new_page = Self::with_options(opts).await?;
self.share_cookies_to(&new_page).await?;
Ok(new_page)
}
// ── PDF export (f33) ─────────────────────────────────────
/// Print current page to PDF and return the raw bytes.
///
/// Accepts a [`PdfOptions`] value to control paper size, margins,
/// orientation, header/footer templates, scale, page ranges, etc.
///
/// Note: generating PDF is only supported in Chrome headless mode.
pub async fn pdf_bytes(&self, opts: PdfOptions) -> Result<Vec<u8>> {
let params = opts.to_cdp_params();
self.page()
.pdf(params)
.await
.map_err(|e| Error::Browser(format!("pdf_bytes: {e}")))
}
/// Print current page to PDF and save to `path`.
///
/// Accepts a [`PdfOptions`] value to control paper size, margins,
/// orientation, header/footer templates, scale, page ranges, etc.
///
/// Note: generating PDF is only supported in Chrome headless mode.
pub async fn pdf_to_file(&self, path: &str, opts: PdfOptions) -> Result<()> {
let bytes = self.pdf_bytes(opts).await?;
std::fs::write(path, bytes)?;
Ok(())
}
/// Print current page to PDF with default options and save to `path`.
///
/// Convenience wrapper around [`Self::pdf_to_file`] with default options.
/// Note: generating PDF is only supported in Chrome headless mode.
pub async fn pdf(&self, path: &str) -> Result<()> {
self.pdf_to_file(path, PdfOptions::default()).await
}
// ── Viewport ────────────────────────────────────────────
/// Set viewport size at runtime.
pub async fn set_viewport(&self, width: u32, height: u32) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
let params = SetDeviceMetricsOverrideParams::new(width as i64, height as i64, 1.0, false);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("viewport: {e}")))?;
Ok(())
}
// ── Device emulation (f22) ─────────────────────────────
/// Override the browser's geolocation.
///
/// Uses `Emulation.setGeolocationOverride` CDP command.
pub async fn set_geolocation(&self, lat: f64, lng: f64) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::emulation::SetGeolocationOverrideParams;
let params = SetGeolocationOverrideParams::builder()
.latitude(lat)
.longitude(lng)
.build();
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("set_geolocation: {e}")))?;
Ok(())
}
/// Override the browser's timezone.
///
/// Uses `Emulation.setTimezoneOverride` CDP command.
pub async fn set_timezone(&self, tz: &str) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::emulation::SetTimezoneOverrideParams;
let params = SetTimezoneOverrideParams::new(tz);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("set_timezone: {e}")))?;
Ok(())
}
/// Emulate a device by setting viewport, scale factor, touch mode, and user agent.
///
/// Uses `Emulation.setDeviceMetricsOverride`, `Emulation.setTouchEmulationEnabled`,
/// and `Network.setUserAgentOverride` CDP commands.
pub async fn emulate_device(
&self,
width: u32,
height: u32,
ua: &str,
scale: f64,
touch: bool,
) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::emulation::{
SetDeviceMetricsOverrideParams, SetTouchEmulationEnabledParams,
};
use chromiumoxide::cdp::browser_protocol::network::SetUserAgentOverrideParams;
// Set device metrics
let params = SetDeviceMetricsOverrideParams::new(width as i64, height as i64, scale, touch);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("emulate_device metrics: {e}")))?;
// Enable/disable touch emulation
let touch_params = SetTouchEmulationEnabledParams::new(touch);
self.page()
.execute(touch_params)
.await
.map_err(|e| Error::Browser(format!("emulate_device touch: {e}")))?;
// Set user agent
let ua_params = SetUserAgentOverrideParams::new(ua);
self.page()
.execute(ua_params)
.await
.map_err(|e| Error::Browser(format!("emulate_device ua: {e}")))?;
Ok(())
}
// ── Keyboard (page-level) ──────────────────────────────
/// Press a key at page level (no element focus needed).
pub async fn press(&self, key: &str) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
let down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key(key)
.build()
.map_err(|e| Error::Browser(format!("key build: {e}")))?;
self.page()
.execute(down)
.await
.map_err(|e| Error::Browser(format!("press: {e}")))?;
let up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key(key)
.build()
.map_err(|e| Error::Browser(format!("key build: {e}")))?;
self.page()
.execute(up)
.await
.map_err(|e| Error::Browser(format!("press up: {e}")))?;
Ok(())
}
// ── DrissionPage-style convenience API ──────────────────
/// Navigate to a URL and return `&self` for chaining.
///
/// This is a chainable alias for [`get()`](Self::get):
///
/// ```ignore
/// page.goto("https://example.com")
/// .await?
/// .click_ele("#btn")
/// .await?;
/// ```
pub async fn goto(&self, url: &str) -> Result<&Self> {
self.get(url).await?;
Ok(self)
}
/// Type text into the first element matching `selector` (wait + fill).
///
/// Waits up to the default timeout for the element to appear, then fills
/// it with the provided text. Returns `&self` for chaining.
///
/// ```ignore
/// page.type_text("#search", "hello world").await?.click_ele("#go").await?;
/// ```
pub async fn type_text(&self, selector: &str, text: &str) -> Result<&Self> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
ele.fill(text).await?;
Ok(self)
}
/// Click the first element matching `selector` (wait + click).
///
/// Waits up to the default timeout for the element to appear, then clicks
/// it. Returns `&self` for chaining.
///
/// ```ignore
/// page.click_ele("#submit").await?;
/// ```
pub async fn click_ele(&self, selector: &str) -> Result<&Self> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
ele.click().await?;
Ok(self)
}
/// Get the visible text of the first element matching `selector`.
///
/// Waits for the element, then returns its text content in one step.
///
/// ```ignore
/// let label = page.get_text("#result").await?;
/// ```
pub async fn get_text(&self, selector: &str) -> Result<String> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
Ok(ele.text().to_string())
}
/// Get an attribute value from the first element matching `selector`.
///
/// Waits for the element, then returns the requested attribute.
/// Returns `Ok(None)` if the attribute does not exist.
///
/// ```ignore
/// let href = page.get_attr("#link", "href").await?;
/// ```
pub async fn get_attr(&self, selector: &str, attr: &str) -> Result<Option<String>> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
Ok(ele.attr(attr).map(String::from))
}
/// Wait until the current URL contains `expected_url`.
///
/// Polls the page URL every 200 ms until it contains the expected
/// substring or the timeout elapses.
///
/// ```ignore
/// page.click_ele("#login").await?;
/// page.wait_for_navigation("/dashboard", Duration::from_secs(10)).await?;
/// ```
pub async fn wait_for_navigation(
&self,
expected_url: &str,
timeout: std::time::Duration,
) -> Result<()> {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let current = self.url().await?;
if current.contains(expected_url) {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Browser(format!(
"wait_for_navigation: URL still '{}' after {}s (expected '{}')",
current,
timeout.as_secs(),
expected_url
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Scroll the page by a relative offset (pixels).
///
/// Positive `y` scrolls down, negative scrolls up.
/// Positive `x` scrolls right, negative scrolls left.
///
/// ```ignore
/// page.scroll_by(0, 500).await?; // scroll down 500px
/// ```
pub async fn scroll_by(&self, x: i64, y: i64) -> Result<()> {
self.page()
.evaluate(format!("window.scrollBy({x}, {y})"))
.await
.map_err(|e| Error::Browser(format!("scroll_by: {e}")))?;
Ok(())
}
/// Type text character-by-character to simulate realistic keyboard input.
///
/// Sends a `keyDown` + `keyUp` pair for each character via CDP
/// `Input.dispatchKeyEvent`, with a 50 ms delay between keystrokes.
///
/// ```ignore
/// page.keys("hello").await?;
/// ```
pub async fn keys(&self, text: &str) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType,
};
for ch in text.chars() {
let key_str = ch.to_string();
let down = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key(&key_str)
.text(&key_str)
.build()
.map_err(|e| Error::Browser(format!("keys down build: {e}")))?;
self.page()
.execute(down)
.await
.map_err(|e| Error::Browser(format!("keys down: {e}")))?;
let up = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key(&key_str)
.build()
.map_err(|e| Error::Browser(format!("keys up build: {e}")))?;
self.page()
.execute(up)
.await
.map_err(|e| Error::Browser(format!("keys up: {e}")))?;
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
Ok(())
}
// ── DrissionPage-style convenience: wait URL/title exact ──
/// Wait for the page URL to **exactly match** `expected`.
///
/// Polls every 200 ms until `window.location.href == expected` or the
/// timeout elapses.
///
/// ```ignore
/// page.wait_url_is("https://example.com/dashboard", 10).await?;
/// ```
pub async fn wait_url_is(&self, expected: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
let current = self.url().await.unwrap_or_default();
if current == expected {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_url_is '{}' timed out (current: '{}')",
expected, current
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Wait for the page title to **exactly match** `expected`.
///
/// Polls every 200 ms until `document.title == expected` or the
/// timeout elapses.
///
/// ```ignore
/// page.wait_title_is("My Dashboard", 10).await?;
/// ```
pub async fn wait_title_is(&self, expected: &str, timeout_secs: u64) -> Result<()> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
loop {
let title = self.title().await.unwrap_or_default();
if title == expected {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_title_is '{}' timed out (current: '{}')",
expected, title
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
// ── DrissionPage-style aliases ─────────────────────────────
/// Alias for [`url()`](Self::url) — DrissionPage uses `current_url`.
///
/// ```ignore
/// let u = page.current_url().await?;
/// ```
pub async fn current_url(&self) -> Result<String> {
self.url().await
}
/// Alias for [`title()`](Self::title) — DrissionPage uses `current_title`.
///
/// ```ignore
/// let t = page.current_title().await?;
/// ```
pub async fn current_title(&self) -> Result<String> {
self.title().await
}
/// Alias for [`html()`](Self::html) — DrissionPage uses `page_source`.
///
/// ```ignore
/// let src = page.page_source().await?;
/// ```
pub async fn page_source(&self) -> Result<String> {
self.html().await
}
/// Re-locate an element in the live DOM using its original locator.
///
/// Returns a fresh `Element` whose HTML, text, attributes, and CDP
/// object-id reflect the current state of the page.
///
/// # Errors
///
/// Returns an error if the element has no stored locator or the element
/// no longer exists in the DOM.
///
/// ```ignore
/// let el = page.ele("#btn").await?;
/// // ... page changes ...
/// let el = page.refresh_ele(&el).await?;
/// el.click().await?;
/// ```
pub async fn refresh_ele(&self, el: &Element) -> Result<Element> {
let locator = el
.locator()
.ok_or_else(|| Error::Browser("element has no locator".into()))?;
let selector = locator_to_selector(locator)?;
let cdp_el = self
.wait_for_element(&selector, self.opts.timeout.as_secs())
.await?;
self.build_element_from_cdp(cdp_el, locator.clone()).await
}
/// Type text into the first element matching `selector` in **append** mode.
///
/// Unlike [`type_text`](Self::type_text) which clears the field first
/// (via `fill`), this uses the element's `input` method to append text
/// at the current cursor position. Returns `&self` for chaining.
///
/// ```ignore
/// page.input_text("#search", " world").await?.click_ele("#go").await?;
/// ```
pub async fn input_text(&self, selector: &str, text: &str) -> Result<&Self> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
ele.input(text).await?;
Ok(self)
}
/// Hover over the first element matching `selector` (wait + hover).
///
/// Waits up to the default timeout for the element to appear, then
/// scrolls it into view and hovers. Returns `&self` for chaining.
///
/// ```ignore
/// page.hover_ele("#menu-item").await?;
/// ```
pub async fn hover_ele(&self, selector: &str) -> Result<&Self> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
ele.hover().await?;
Ok(self)
}
/// Scroll the first element matching `selector` into view (wait + scroll).
///
/// Waits up to the default timeout for the element to appear, then
/// scrolls it into the viewport. Returns `&self` for chaining.
///
/// ```ignore
/// page.scroll_to_ele("#section-3").await?;
/// ```
pub async fn scroll_to_ele(&self, selector: &str) -> Result<&Self> {
let timeout_secs = self.opts.timeout.as_secs();
let ele = self.wait_ele(selector, timeout_secs).await?;
ele.scroll_into_view().await?;
Ok(self)
}
/// Quick check: does at least one element matching `selector` exist?
///
/// Returns `true` if `querySelector` finds a match, `false` otherwise.
/// Never throws — safe to use in `if` guards.
///
/// ```ignore
/// if page.exists("#popup").await {
/// page.click_ele("#close").await?;
/// }
/// ```
pub async fn exists(&self, selector: &str) -> bool {
let locator = match crate::locator::parse_locator(selector) {
Ok(l) => l,
Err(_) => return false,
};
let css = match locator_to_selector(&locator) {
Ok(s) => s,
Err(_) => return false,
};
self.page().find_element(&css).await.is_ok()
}
/// Count how many elements currently match `selector`.
///
/// Returns `0` if no elements are found or the selector is invalid.
///
/// ```ignore
/// let n = page.count(".item").await;
/// println!("{n} items on page");
/// ```
pub async fn count(&self, selector: &str) -> usize {
let locator = match crate::locator::parse_locator(selector) {
Ok(l) => l,
Err(_) => return 0,
};
let css = match locator_to_selector(&locator) {
Ok(s) => s,
Err(_) => return 0,
};
self.page()
.find_elements(&css)
.await
.map(|els| els.len())
.unwrap_or(0)
}
/// Find the first element matching `selector`, or `None` if it doesn't exist.
///
/// Unlike [`ele`](Self::ele) which retries and then returns an error,
/// this performs a single query and silently returns `None` when the
/// element is absent.
///
/// ```ignore
/// if let Some(el) = page.ele_or_none("#optional").await {
/// el.click().await?;
/// }
/// ```
pub async fn ele_or_none(&self, selector: &str) -> Option<Element> {
let locator = crate::locator::parse_locator(selector).ok()?;
let css = locator_to_selector(&locator).ok()?;
let cdp_el = self.page().find_element(&css).await.ok()?;
self.build_element_from_cdp(cdp_el, locator).await.ok()
}
// ── Permissions (f27) ────────────────────────────────────
/// Grant browser permissions for the given origin.
///
/// Uses `Browser.setPermission` with `Granted` setting for each
/// permission name (e.g. `"geolocation"`, `"notifications"`,
/// `"camera"`, `"microphone"`, `"clipboard-read"`).
///
/// ```ignore
/// page.grant_permissions("https://example.com", vec![
/// "geolocation".into(),
/// "notifications".into(),
/// ]).await?;
/// ```
pub async fn grant_permissions(&self, origin: &str, permissions: Vec<String>) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
PermissionDescriptor, PermissionSetting, SetPermissionParams,
};
for perm_name in &permissions {
let params = SetPermissionParams::builder()
.permission(PermissionDescriptor::new(perm_name.clone()))
.setting(PermissionSetting::Granted)
.origin(origin)
.build()
.map_err(|e| Error::Browser(format!("grant_permissions build: {e}")))?;
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("grant_permissions({perm_name}): {e}")))?;
}
Ok(())
}
/// Reset all browser permission overrides.
///
/// Removes all permission grants previously set via `grant_permissions`.
///
/// ```ignore
/// page.reset_permissions().await?;
/// ```
pub async fn reset_permissions(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::ResetPermissionsParams;
self.page()
.execute(ResetPermissionsParams::default())
.await
.map_err(|e| Error::Browser(format!("reset_permissions: {e}")))?;
Ok(())
}
// ── Accessors ────────────────────────────────────────────
/// Returns a clone of the inner CDP Page handle (cheap Arc clone).
pub fn inner_page(&self) -> Page {
self.page()
}
pub fn browser(&self) -> &Browser {
&self.browser
}
pub fn options(&self) -> &ChromiumOptions {
&self.opts
}
pub fn download_manager(&self) -> &Arc<DownloadManager> {
&self.download_manager
}
pub fn network_monitor(&self) -> &Arc<crate::network::NetworkMonitor> {
&self.network_monitor
}
/// Get the console monitor.
pub fn console_monitor(&self) -> &Arc<ConsoleMonitor> {
&self.console_monitor
}
// ── Network listener callbacks (DrissionPage-style listen) ──────
/// Register a callback that fires for every network request.
///
/// ```ignore
/// page.on_request(|req| println!("Request: {} {}", req.method, req.url))?;
/// ```
pub fn on_request<F: Fn(crate::network::RequestInfo) + Send + 'static>(
&self,
callback: F,
) -> Result<()> {
self.network_monitor.add_request_listener(callback);
Ok(())
}
/// Register a callback that fires for every network response.
///
/// ```ignore
/// page.on_response(|res| println!("Response: {} {}", res.status, res.url))?;
/// ```
pub fn on_response<F: Fn(crate::network::ResponseInfo) + Send + 'static>(
&self,
callback: F,
) -> Result<()> {
self.network_monitor.add_response_listener(callback);
Ok(())
}
/// Clear all registered request/response listener callbacks.
pub fn clear_listeners(&self) {
self.network_monitor.clear_listeners();
}
// ── Raw CDP escape hatch + response bodies ─────────────────
/// Execute an arbitrary CDP command by `Domain.method` name with JSON
/// `params`, returning the raw JSON result. This is the escape hatch for
/// the long tail of CDP commands rpage doesn't wrap directly (mirrors
/// DrissionPage's `run_cdp`).
///
/// ```ignore
/// // Override the User-Agent for just this page via raw CDP.
/// page.run_cdp("Network.setUserAgentOverride",
/// serde_json::json!({ "userAgent": "my-bot/1.0" })).await?;
/// let metrics = page.run_cdp("Page.getLayoutMetrics", serde_json::json!({})).await?;
/// ```
pub async fn run_cdp(
&self,
method: impl Into<String>,
params: serde_json::Value,
) -> Result<serde_json::Value> {
let method = method.into();
if !method.contains('.') {
return Err(Error::Browser(format!(
"run_cdp: invalid method '{method}' (expected 'Domain.method')"
)));
}
// CDP requires the params payload to be an object; map a missing/Null
// argument to an empty object so callers can pass `json!(null)`.
let params = match params {
serde_json::Value::Null => serde_json::Value::Object(serde_json::Map::new()),
other => other,
};
let cmd = RawCdpCommand {
method: std::borrow::Cow::Owned(method),
params,
};
let resp = self
.page()
.execute(cmd)
.await
.map_err(|e| Error::Browser(format!("run_cdp: {e}")))?;
Ok(resp.result)
}
/// Fetch the body of a network response by its request id (as recorded in
/// `responses()`/`get_responses()`), via CDP `Network.getResponseBody`.
///
/// This closes the gap to DrissionPage's `DataPacket.response.body`:
/// `responses()` gives the metadata, this gives the actual payload. It
/// requires monitoring to be enabled (the Network domain) and only works
/// while Chrome still retains the body — call it once the request has
/// finished loading and before it's evicted from the network cache.
pub async fn get_response_body(&self, request_id: &str) -> Result<ResponseBody> {
use chromiumoxide::cdp::browser_protocol::network::GetResponseBodyParams;
let resp = self
.page()
.execute(GetResponseBodyParams::new(request_id.to_string()))
.await
.map_err(|e| Error::Browser(format!("get_response_body: {e}")))?;
Ok(ResponseBody {
body: resp.result.body.clone(),
base64_encoded: resp.result.base64_encoded,
})
}
/// Get all captured console log entries.
pub fn console_log(&self) -> Vec<crate::console::ConsoleEntry> {
self.console_monitor.logs()
}
/// Get all captured JS exceptions.
pub fn console_exceptions(&self) -> Vec<crate::console::JsException> {
self.console_monitor.exceptions()
}
/// Clear all captured console entries and exceptions.
pub fn clear_console(&self) {
self.console_monitor.clear();
}
/// Get all captured WebSocket frames.
pub fn ws_frames(&self) -> Vec<crate::websocket::WsFrame> {
self.ws_monitor.frames()
}
/// Get all captured WebSocket events (Created/Closed/Error).
pub fn ws_events(&self) -> Vec<crate::websocket::WsEvent> {
self.ws_monitor.events()
}
/// Clear all captured WebSocket frames and events.
pub fn clear_ws_frames(&self) {
self.ws_monitor.clear();
}
/// Get all tracked downloads.
pub fn downloads(&self) -> Vec<crate::download::DownloadInfo> {
self.download_manager.list()
}
/// Wait for the most recent download to finish (completed, cancelled, or failed).
/// Returns the download info. `timeout_secs` is the max wait time.
///
/// ```ignore
/// page.get("https://example.com/file.zip").await?;
/// let dl = page.wait_download(30).await?;
/// println!("Saved to: {:?}", dl.save_path);
/// ```
pub async fn wait_download(&self, timeout_secs: u64) -> Result<crate::download::DownloadInfo> {
let start = std::time::Instant::now();
let duration = std::time::Duration::from_secs(timeout_secs);
loop {
let list = self.download_manager.list();
if let Some(last) = list.last() {
if !matches!(last.status, crate::download::DownloadStatus::InProgress) {
return Ok(last.clone());
}
}
if start.elapsed() > duration {
return Err(Error::Timeout("wait_download timed out".into()));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Wait until a JavaScript expression evaluates to a truthy value.
///
/// ```ignore
/// page.wait_js("document.querySelectorAll('.item').length > 5", 10).await?;
/// ```
pub async fn wait_js(&self, expression: &str, timeout_secs: u64) -> Result<()> {
let start = std::time::Instant::now();
let duration = std::time::Duration::from_secs(timeout_secs);
let js = format!("(function(){{ return !!({expr}); }})()", expr = expression);
loop {
let result = self
.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("wait_js evaluate: {e}")))?
.value()
.cloned()
.unwrap_or(serde_json::Value::Bool(false));
if result.as_bool().unwrap_or(false) {
return Ok(());
}
if start.elapsed() > duration {
return Err(Error::Timeout(format!("wait_js({expression}) timed out")));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
/// Set the download directory. Takes effect for subsequent downloads.
pub fn set_download_dir(&self, dir: impl Into<std::path::PathBuf>) {
// Update the download manager's default dir via a new DM
// (the actual SetDownloadBehavior needs a new CDP call for the next download)
let _ = dir;
}
// ── iframe context ──────────────────────────────────────
/// Enter an iframe by CSS selector, returning a FrameContext for operations inside it.
pub async fn enter_frame(&self, selector: &str) -> Result<FrameContext> {
let escaped = json_escape(selector);
let js = format!(
"(function(){{ var f = document.querySelector({sel}); if(!f) return null; return f.contentWindow ? 'same-origin' : 'cross-origin'; }})()",
sel = escaped
);
let origin_type = self
.page()
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("enter_frame check: {e}")))?
.value()
.cloned()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default();
Ok(FrameContext {
page: self.page(),
selector: selector.to_string(),
origin_type,
})
}
// ── Action chain ───────────────────────────────────────
/// Create an ActionChain for complex multi-step input sequences.
///
/// ```ignore
/// page.actions()
/// .move_to(100.0, 200.0)
/// .click_at(100.0, 200.0)
/// .key_down("Control")
/// .press("a")
/// .key_up("Control")
/// .perform()
/// .await?;
/// ```
pub fn actions(&self) -> ActionChain {
ActionChain::new(self.page())
}
// ── Network interception (f12: Fetch.requestPaused) ─────
/// Enable network request interception via CDP Fetch domain.
///
/// Requests matching `url_pattern` will be paused. The returned `InterceptGuard`
/// automatically disables interception when dropped.
///
/// Use `intercepted_requests()` to get paused requests, then
/// `continue_request()` or `fail_request()` to resume them.
pub async fn enable_intercept(&self, url_pattern: &str) -> Result<InterceptGuard> {
use chromiumoxide::cdp::browser_protocol::fetch::{
EnableParams, RequestPattern, RequestStage,
};
let pattern = RequestPattern {
url_pattern: Some(url_pattern.to_string()),
resource_type: None,
request_stage: Some(RequestStage::Request),
};
let params = EnableParams::builder().pattern(pattern).build();
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("Fetch.enable: {e}")))?;
// Spawn listener for paused requests
let paused = Arc::new(Mutex::new(Vec::new()));
let paused_clone = paused.clone();
if let Ok(mut rx) = self
.page()
.event_listener::<chromiumoxide::cdp::browser_protocol::fetch::EventRequestPaused>()
.await
{
tokio::spawn(async move {
while let Some(ev) = rx.next().await {
if let Ok(mut list) = paused_clone.lock() {
list.push(InterceptedRequest {
request_id: ev.request_id.clone(),
url: ev.request.url.clone(),
method: ev.request.method.clone(),
resource_type: format!("{:?}", ev.resource_type),
});
}
}
});
}
Ok(InterceptGuard {
page: self.page(),
_active: true,
paused,
})
}
// ── Performance metrics ───────────────────────────────────
/// Retrieve current CDP performance metrics.
///
/// Enables the Performance domain and calls `Performance.getMetrics`.
/// Returns a list of `(name, value)` pairs such as `Timestamp`,
/// `Documents`, `Frames`, `JSEventListeners`, etc.
pub async fn performance_metrics(&self) -> Result<Vec<(String, f64)>> {
use chromiumoxide::cdp::browser_protocol::performance::{EnableParams, GetMetricsParams};
// Enable the Performance domain first
self.page()
.execute(EnableParams::default())
.await
.map_err(|e| Error::Browser(format!("Performance.enable: {e}")))?;
// Retrieve metrics
let resp = self
.page()
.execute(GetMetricsParams::default())
.await
.map_err(|e| Error::Browser(format!("Performance.getMetrics: {e}")))?;
Ok(resp
.metrics
.clone()
.into_iter()
.map(|m| (m.name, m.value))
.collect())
}
/// Extract page-load timing via `performance.timing` (JS).
///
/// Returns a `HashMap` with computed durations (ms):
/// - `dns` — DNS lookup
/// - `tcp` — TCP handshake
/// - `request` — request sent → response start
/// - `response` — response start → response end
/// - `dom` — DOM parsing
/// - `load` — total page load
/// - `domInteractive` — DOM interactive
/// - `domContentLoaded` — DOMContentLoaded event
pub async fn page_timing(&self) -> Result<std::collections::HashMap<String, f64>> {
let js = r#"
(function() {
var t = performance.timing;
return JSON.stringify({
dns: t.domainLookupEnd - t.domainLookupStart,
tcp: t.connectEnd - t.connectStart,
request: t.responseStart - t.requestStart,
response: t.responseEnd - t.responseStart,
dom: t.domComplete - t.domLoading,
load: t.loadEventEnd - t.navigationStart,
domInteractive: t.domInteractive - t.navigationStart,
domContentLoaded: t.domContentLoadedEventEnd - t.navigationStart
});
})()
"#;
let val = self.execute(js).await?;
let json_str = val
.as_str()
.ok_or_else(|| Error::Browser("page_timing: JS did not return a string".into()))?;
let parsed: std::collections::HashMap<String, f64> = serde_json::from_str(json_str)
.map_err(|e| Error::Browser(format!("page_timing parse: {e}")))?;
Ok(parsed)
}
// ── File chooser (f25) ────────────────────────────────────
/// Enable or disable interception of file chooser dialogs.
///
/// When enabled, the native file chooser dialog is suppressed and a
/// `Page.fileChooserOpened` CDP event is emitted instead.
pub async fn set_file_chooser(&self, enabled: bool) {
use chromiumoxide::cdp::browser_protocol::page::SetInterceptFileChooserDialogParams;
let params = SetInterceptFileChooserDialogParams::new(enabled);
let _ = self.page().execute(params).await;
}
/// Wait for a file chooser dialog event within the given timeout.
///
/// Returns `FileChooserInfo` containing the `backend_node_id` of the
/// `<input type="file">` element and the mode (`"selectSingle"` or
/// `"selectMultiple"`).
pub async fn wait_file_chooser(&self, timeout_secs: u64) -> Result<FileChooserInfo> {
use chromiumoxide::cdp::browser_protocol::page::EventFileChooserOpened;
let result: Arc<Mutex<Option<FileChooserInfo>>> = Arc::new(Mutex::new(None));
let result_clone = result.clone();
if let Ok(mut rx) = self.page().event_listener::<EventFileChooserOpened>().await {
tokio::spawn(async move {
if let Some(ev) = rx.next().await {
let info = FileChooserInfo {
backend_node_id: ev.backend_node_id.map_or(0, |id| *id.inner() as u64),
mode: ev.mode.as_ref().to_string(),
};
if let Ok(mut guard) = result_clone.lock() {
*guard = Some(info);
}
}
});
}
let start = std::time::Instant::now();
let duration = std::time::Duration::from_secs(timeout_secs);
loop {
{
let guard = result
.lock()
.map_err(|e| Error::Browser(format!("lock: {e}")))?;
if guard.is_some() {
return Ok(guard.clone().unwrap());
}
}
if start.elapsed() > duration {
return Err(Error::Timeout("wait_file_chooser timed out".into()));
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
// ── Audio control (f34) ────────────────────────────────────
/// Mute all audio on the page by monkey-patching `HTMLMediaElement.prototype.play`
/// and `window.AudioContext` via JavaScript injection.
pub async fn mute(&self) -> Result<()> {
self.execute(
r#"(function(){if(!window.__audioMuted){window.__audioMuted=true;window.__origCreateMediaElement=HTMLMediaElement.prototype.play;HTMLMediaElement.prototype.play=function(){return Promise.resolve()};window.__origAudioCtx=window.AudioContext;window.AudioContext=function(){return{close:()=>{},createGain:()=>({connect:()=>{},gain:{setValueAtTime:()=>{}}}),destination:{}}}}})()"#,
)
.await?;
Ok(())
}
/// Unmute audio by restoring the original `HTMLMediaElement.prototype.play`
/// and `window.AudioContext`.
pub async fn unmute(&self) -> Result<()> {
self.execute(
r#"if(window.__audioMuted){HTMLMediaElement.prototype.play=window.__origCreateMediaElement;window.AudioContext=window.__origAudioCtx;window.__audioMuted=false}"#,
)
.await?;
Ok(())
}
// ── DOM Snapshot (f31) ────────────────────────────────────
/// Capture a full DOM snapshot of the current page as a JSON tree.
///
/// This is implemented via JavaScript evaluation rather than the
/// `DOMSnapshot.captureSnapshot` CDP command for maximum compatibility.
pub async fn dom_snapshot(&self) -> Result<serde_json::Value> {
self.execute(
r#"(() => {
var MAX_DEPTH = 20, MAX_NODES = 500, count = 0;
function serialize(node, depth) {
if (depth > MAX_DEPTH || count > MAX_NODES) return null;
count++;
var obj = { type: node.nodeType, name: node.nodeName };
if (node.attributes && node.attributes.length > 0) {
obj.attrs = {};
for (var i = 0; i < node.attributes.length; i++) {
obj.attrs[node.attributes[i].name] = node.attributes[i].value;
}
}
if (node.childNodes && node.childNodes.length > 0) {
obj.children = [];
for (var i = 0; i < node.childNodes.length; i++) {
var child = serialize(node.childNodes[i], depth + 1);
if (child) obj.children.push(child);
}
}
if (node.nodeValue && node.nodeValue.trim()) obj.value = node.nodeValue.trim();
return obj;
}
return JSON.stringify(serialize(document.documentElement, 0));
})()"#,
)
.await
}
// ── CSS override (f35) ──────────────────────────────────────
/// Inject a `<style>` tag into the page and return its generated ID.
///
/// The returned ID can later be passed to `remove_css` to delete the tag.
pub async fn inject_css(&self, css: &str) -> Result<String> {
let id = format!(
"rpage-css-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
);
let js = format!(
r#"(function() {{
var style = document.createElement('style');
style.type = 'text/css';
style.id = {id_json};
style.textContent = {css_json};
document.head.appendChild(style);
}})()"#,
id_json = json_escape(&id),
css_json = json_escape(css),
);
self.execute(&js).await?;
Ok(id)
}
/// Remove a previously injected `<style>` tag by its ID.
pub async fn remove_css(&self, id: &str) -> Result<()> {
let js = format!(
r#"(function() {{
var el = document.getElementById({id_json});
if (el) el.remove();
}})()"#,
id_json = json_escape(id),
);
self.execute(&js).await?;
Ok(())
}
// ── Load strategy ────────────────────────────────────────
/// Set the page load strategy.
///
/// Controls how `get()` waits after navigation:
/// - `"normal"` — wait for the full `load` event (default)
/// - `"eager"` — wait for `DOMContentLoaded` only
/// - `"none"` — return immediately after navigation
pub fn set_load_strategy(&mut self, strategy: &str) {
self.load_strategy = strategy.to_string();
}
/// Get the current load strategy.
pub fn load_strategy(&self) -> &str {
&self.load_strategy
}
// ── Window management ─────────────────────────────────────
/// Get the current browser window's bounds (position + size).
///
/// Returns `(left, top, width, height)`.
pub async fn get_window_bounds(&self) -> Result<(i32, i32, u32, u32)> {
// Use JS to get window dimensions
let js = r#"(function() {
return JSON.stringify({
left: window.screenX || 0,
top: window.screenY || 0,
width: window.outerWidth || 0,
height: window.outerHeight || 0
});
})()"#;
let val = self.execute(js).await?;
let s = val.as_str().ok_or_else(|| {
Error::Browser("get_window_bounds: JS did not return a string".into())
})?;
let parsed: serde_json::Value = serde_json::from_str(s)
.map_err(|e| Error::Browser(format!("get_window_bounds parse: {e}")))?;
Ok((
parsed["left"].as_i64().unwrap_or(0) as i32,
parsed["top"].as_i64().unwrap_or(0) as i32,
parsed["width"].as_u64().unwrap_or(0) as u32,
parsed["height"].as_u64().unwrap_or(0) as u32,
))
}
/// Set window position (top-left corner).
pub async fn set_window_position(&self, left: i32, top: i32) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
Bounds, GetWindowForTargetParams, SetWindowBoundsParams,
};
let resp = self
.page()
.execute(GetWindowForTargetParams::default())
.await
.map_err(|e| Error::Browser(format!("get_window_for_target: {e}")))?;
let window_id = resp.window_id;
// Get current size to preserve it
let (_, _, width, height) = self.get_window_bounds().await?;
let bounds = Bounds::builder()
.left(left as i64)
.top(top as i64)
.width(width as i64)
.height(height as i64)
.build();
let params = SetWindowBoundsParams::new(window_id, bounds);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("set_window_position: {e}")))?;
Ok(())
}
/// Set window size (width × height).
pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
Bounds, GetWindowForTargetParams, SetWindowBoundsParams,
};
let resp = self
.page()
.execute(GetWindowForTargetParams::default())
.await
.map_err(|e| Error::Browser(format!("get_window_for_target: {e}")))?;
let window_id = resp.window_id;
// Get current position to preserve it
let (left, top, _, _) = self.get_window_bounds().await?;
let bounds = Bounds::builder()
.left(left as i64)
.top(top as i64)
.width(width as i64)
.height(height as i64)
.build();
let params = SetWindowBoundsParams::new(window_id, bounds);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("set_window_size: {e}")))?;
Ok(())
}
/// Minimize the browser window.
pub async fn minimize(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
Bounds, GetWindowForTargetParams, SetWindowBoundsParams, WindowState,
};
let resp = self
.page()
.execute(GetWindowForTargetParams::default())
.await
.map_err(|e| Error::Browser(format!("get_window_for_target: {e}")))?;
let bounds = Bounds {
window_state: Some(WindowState::Minimized),
..Default::default()
};
let params = SetWindowBoundsParams::new(resp.window_id, bounds);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("minimize: {e}")))?;
Ok(())
}
/// Maximize the browser window.
pub async fn maximize(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
Bounds, GetWindowForTargetParams, SetWindowBoundsParams, WindowState,
};
let resp = self
.page()
.execute(GetWindowForTargetParams::default())
.await
.map_err(|e| Error::Browser(format!("get_window_for_target: {e}")))?;
let bounds = Bounds {
window_state: Some(WindowState::Maximized),
..Default::default()
};
let params = SetWindowBoundsParams::new(resp.window_id, bounds);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("maximize: {e}")))?;
Ok(())
}
/// Set the browser window to fullscreen.
pub async fn fullscreen(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::browser::{
Bounds, GetWindowForTargetParams, SetWindowBoundsParams, WindowState,
};
let resp = self
.page()
.execute(GetWindowForTargetParams::default())
.await
.map_err(|e| Error::Browser(format!("get_window_for_target: {e}")))?;
let bounds = Bounds {
window_state: Some(WindowState::Fullscreen),
..Default::default()
};
let params = SetWindowBoundsParams::new(resp.window_id, bounds);
self.page()
.execute(params)
.await
.map_err(|e| Error::Browser(format!("fullscreen: {e}")))?;
Ok(())
}
// ── Alert convenience wrappers ──────────────────────────
/// Accept the current JavaScript dialog (alert / confirm / prompt).
///
/// Shorthand for `handle_alert(true, None)`.
pub async fn accept_alert(&self) -> Result<()> {
self.handle_alert(true, None).await
}
/// Dismiss the current JavaScript dialog (alert / confirm / prompt).
///
/// Shorthand for `handle_alert(false, None)`.
pub async fn dismiss_alert(&self) -> Result<()> {
self.handle_alert(false, None).await
}
/// Accept a prompt dialog and supply the text to enter.
///
/// Shorthand for `handle_alert(true, Some(text))`.
pub async fn accept_prompt(&self, text: &str) -> Result<()> {
self.handle_alert(true, Some(text)).await
}
// ── Download helpers ────────────────────────────────────
/// Return the default download directory used by the download manager.
pub fn download_dir(&self) -> PathBuf {
self.download_manager.default_dir().to_path_buf()
}
/// Navigate to `url` and wait for a download to complete.
///
/// Uses `get()` to trigger the download, then polls `wait_download()`.
/// Returns the `DownloadInfo` of the completed download.
pub async fn download(
&self,
url: &str,
timeout_secs: u64,
) -> Result<crate::download::DownloadInfo> {
self.get(url).await?;
self.wait_download(timeout_secs).await
}
/// Clear all tracked download records.
pub fn clear_downloads(&self) {
self.download_manager.clear();
}
/// Wait for a specific download whose filename contains `pattern`.
///
/// Polls the download list until a completed download with a matching
/// filename is found, or `timeout_secs` elapses.
pub async fn wait_for_download_file(
&self,
pattern: &str,
timeout_secs: u64,
) -> Result<crate::download::DownloadInfo> {
let start = std::time::Instant::now();
let duration = std::time::Duration::from_secs(timeout_secs);
loop {
let list = self.download_manager.list();
for dl in &list {
if dl.filename.contains(pattern)
&& dl.status == crate::download::DownloadStatus::Completed
{
return Ok(dl.clone());
}
}
if start.elapsed() > duration {
return Err(Error::Timeout(format!(
"wait_for_download_file({pattern}) timed out"
)));
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
// ── High-level listen mode (DrissionPage-style) ────────────
/// Start listening for all network requests and responses.
///
/// Ensures that the CDP `Network.enable` domain has been enabled so that
/// request/response events are captured by the internal
/// [`NetworkMonitor`](crate::NetworkMonitor).
/// Sets the listen-mode flag to `true`.
///
/// ```ignore
/// page.listen_start().await?;
/// // … trigger some network activity …
/// let packets = page.get_packets("/api/");
/// page.listen_stop().await?;
/// ```
pub async fn listen_start(&self) -> Result<()> {
// Ensure Network.enable has been called
crate::network::enable_network(&self.page()).await?;
if let Ok(mut flag) = self.listening.lock() {
*flag = true;
}
Ok(())
}
/// Stop the high-level listen mode.
///
/// Clears the listen-mode flag. Does **not** clear recorded
/// requests/responses — use `network_monitor().clear()`
/// for that.
///
/// ```ignore
/// page.listen_stop().await?;
/// ```
pub async fn listen_stop(&self) -> Result<()> {
if let Ok(mut flag) = self.listening.lock() {
*flag = false;
}
Ok(())
}
/// Synchronously wait (busy-poll) until a network request whose URL
/// contains `url_pattern` is recorded, returning the first match.
///
/// Blocks the calling thread for up to `timeout_secs` seconds, polling
/// every 100 ms. This is a synchronous convenience wrapper intended for
/// use outside of an async runtime or in simple scripts.
///
/// # Errors
///
/// Returns [`Error::Timeout`] if no matching request is seen within the
/// deadline.
///
/// ```ignore
/// let pkt = page.wait_for_packet("/api/login", 10)?;
/// println!("{} {}", pkt.method, pkt.url);
/// ```
pub fn wait_for_packet(
&self,
url_pattern: &str,
timeout_secs: u64,
) -> Result<crate::network::RequestInfo> {
let start = std::time::Instant::now();
let deadline = std::time::Duration::from_secs(timeout_secs);
loop {
let matches = self.network_monitor.find_requests_by_url(url_pattern);
if let Some(rec) = matches.into_iter().last() {
return Ok(crate::network::RequestInfo {
url: rec.url,
method: rec.method,
resource_type: rec.resource_type,
request_id: rec.request_id,
});
}
if start.elapsed() > deadline {
return Err(Error::Timeout(format!(
"wait_for_packet({url_pattern}) timed out"
)));
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
/// Return all recorded request packets whose URL contains `url_pattern`.
///
/// Each packet is a lightweight [`RequestInfo`](crate::RequestInfo) containing the URL, method,
/// resource type, and request ID.
///
/// ```ignore
/// for pkt in page.get_packets("/api/") {
/// println!("{} {} ({})", pkt.method, pkt.url, pkt.resource_type);
/// }
/// ```
pub fn get_packets(&self, url_pattern: &str) -> Vec<crate::network::RequestInfo> {
self.network_monitor
.find_requests_by_url(url_pattern)
.into_iter()
.map(|rec| crate::network::RequestInfo {
url: rec.url,
method: rec.method,
resource_type: rec.resource_type,
request_id: rec.request_id,
})
.collect()
}
/// Return all recorded response packets whose URL contains `url_pattern`.
///
/// Each packet is a lightweight [`ResponseInfo`](crate::ResponseInfo) containing the URL, status
/// code, MIME type, and request ID.
///
/// ```ignore
/// for res in page.get_responses("/api/") {
/// println!("{} {} (status {})", res.url, res.mime_type, res.status);
/// }
/// ```
pub fn get_responses(&self, url_pattern: &str) -> Vec<crate::network::ResponseInfo> {
self.network_monitor
.find_responses_by_url(url_pattern)
.into_iter()
.map(|rec| crate::network::ResponseInfo {
url: rec.url,
status: rec.status,
mime_type: rec.mime_type,
request_id: rec.request_id,
})
.collect()
}
/// Wait for a response whose URL contains `url_pattern`, then capture its
/// body and assemble a full [`DataPacket`] (request + response metadata +
/// body). This is rpage's equivalent of DrissionPage's `page.listen.wait()`
/// — the typical way to grab an XHR/fetch JSON payload triggered by a click.
///
/// Requires monitoring to be enabled (the default for `with_options`).
/// Once a matching response is seen, the body is fetched with a short
/// retry window, since `Network.getResponseBody` only succeeds after the
/// response has finished loading. `response_body` is `None` if the body
/// was never retained (redirects, 204s, evicted entries).
///
/// ```ignore
/// page.listen_start().await?;
/// page.ele("#load").await?.click().await?;
/// let pkt = page.wait_data_packet("/api/data", 10).await?;
/// println!("{} {} -> {}", pkt.status, pkt.url, pkt.body_text());
/// ```
pub async fn wait_data_packet(
&self,
url_pattern: &str,
timeout_secs: u64,
) -> Result<DataPacket> {
let start = std::time::Instant::now();
let deadline = std::time::Duration::from_secs(timeout_secs);
loop {
if let Some(resp) = self
.network_monitor
.find_responses_by_url(url_pattern)
.into_iter()
.last()
{
return Ok(self.build_data_packet(resp).await);
}
if start.elapsed() > deadline {
return Err(Error::Timeout(format!(
"wait_data_packet({url_pattern}) timed out"
)));
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
/// Return a full [`DataPacket`] (request + response + body) for **every**
/// recorded response whose URL contains `url_pattern` — the multi-packet
/// companion to [`wait_data_packet`](Self::wait_data_packet), equivalent to
/// DrissionPage's `listen.steps()`. Call `listen_start()` (or any monitored
/// page) first, drive some activity, then harvest all matching XHR/fetch
/// payloads at once. Clear between runs with `network_monitor().clear()`.
pub async fn data_packets(&self, url_pattern: &str) -> Vec<DataPacket> {
let resps = self.network_monitor.find_responses_by_url(url_pattern);
let mut packets = Vec::with_capacity(resps.len());
for resp in resps {
packets.push(self.build_data_packet(resp).await);
}
packets
}
/// Assemble a full `DataPacket` from a recorded response, fetching its body
/// with a short retry (the body isn't available until loadingFinished).
/// Shared by `wait_data_packet` / `data_packets`.
async fn build_data_packet(&self, resp: crate::network::ResponseRecord) -> DataPacket {
let req = self
.network_monitor
.requests()
.into_iter()
.rev()
.find(|r| r.request_id == resp.request_id);
let mut response_body = None;
let body_deadline = std::time::Instant::now() + std::time::Duration::from_millis(2000);
loop {
if let Ok(b) = self.get_response_body(&resp.request_id).await {
response_body = Some(b);
break;
}
if std::time::Instant::now() >= body_deadline {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let (method, resource_type, request_headers) = req
.map(|r| (r.method, r.resource_type, r.headers))
.unwrap_or_else(|| (String::new(), String::new(), HashMap::new()));
DataPacket {
url: resp.url,
method,
status: resp.status,
resource_type,
request_id: resp.request_id,
mime_type: resp.mime_type,
request_headers,
response_headers: resp.headers,
response_body,
}
}
// ── DrissionPage 缺失功能补全 ─────────────────────────────
/// Find tab index by partial title match.
pub async fn get_tab_by_title(&self, title_contains: &str) -> Result<usize> {
let titles = self.tab_titles().await?;
titles
.iter()
.position(|t| t.contains(title_contains))
.ok_or_else(|| {
Error::Browser(format!(
"get_tab_by_title: no tab with title containing '{title_contains}'"
))
})
}
/// Find tab index by partial URL match.
pub async fn get_tab_by_url(&self, url_contains: &str) -> Result<usize> {
let urls = self.tab_urls().await?;
urls.iter()
.position(|u| u.contains(url_contains))
.ok_or_else(|| {
Error::Browser(format!(
"get_tab_by_url: no tab with url containing '{url_contains}'"
))
})
}
/// Wait for a new tab to appear within the given timeout.
pub async fn wait_new_tab(&self, timeout_secs: u64) -> Result<()> {
let initial_count = self.tabs().await?.len();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
while std::time::Instant::now() < deadline {
let current_count = self.tabs().await?.len();
if current_count > initial_count {
return Ok(());
}
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
Err(Error::Browser(format!(
"wait_new_tab: timed out after {timeout_secs}s"
)))
}
/// Set the download file name for the next download.
pub async fn set_download_file_name(&self, name: &str) -> Result<()> {
// Store for next download event
let _ = name;
Ok(())
}
/// Smoothly scroll to a position over the given duration (ms).
pub async fn smooth_scroll(&self, x: i64, y: i64, duration_ms: u64) -> Result<()> {
self.execute(&format!(
"(function() {{ \
var startX = window.scrollX, startY = window.scrollY; \
var diffX = {x} - startX, diffY = {y} - startY; \
var start = null; \
function step(ts) {{ \
if (!start) start = ts; \
var p = Math.min((ts - start) / {duration_ms}, 1); \
window.scrollTo(startX + diffX * p, startY + diffY * p); \
if (p < 1) requestAnimationFrame(step); \
}} \
requestAnimationFrame(step); \
}})()",
))
.await?;
tokio::time::sleep(std::time::Duration::from_millis(duration_ms + 50)).await;
Ok(())
}
/// Block URLs matching patterns using Network.setBlockedUrls. Use before navigation.
pub async fn set_blocked_urls(&self, urls: &[&str]) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::network::BlockPattern;
let patterns: Vec<BlockPattern> = urls
.iter()
.map(|s| BlockPattern::new((*s).to_string(), true))
.collect();
self.page()
.execute(
chromiumoxide::cdp::browser_protocol::network::SetBlockedUrLsParams::builder()
.url_patterns(patterns)
.build(),
)
.await
.map_err(|e| Error::Browser(format!("set_blocked_urls: {e}")))?;
Ok(())
}
/// Set offline mode (true = offline, false = online).
///
/// Uses `Network.overrideNetworkState` rather than the deprecated
/// `Network.emulateNetworkConditions`: Chrome split that command into
/// `overrideNetworkState` (online/offline + `navigator.connection`) and
/// `emulateNetworkConditionsByRule` (per-request throttling). Toggling
/// offline only needs the former, and its `new()` signature is identical
/// (the `-1.0` throughput args mean "no throttling").
pub async fn set_offline(&self, offline: bool) -> Result<()> {
self.page()
.execute(
chromiumoxide::cdp::browser_protocol::network::OverrideNetworkStateParams::new(
offline, 0.0, -1.0, -1.0,
),
)
.await
.map_err(|e| Error::Browser(format!("set_offline: {e}")))?;
Ok(())
}
/// Clear browser cache.
pub async fn clear_cache(&self) -> Result<()> {
self.page()
.execute(
chromiumoxide::cdp::browser_protocol::network::ClearBrowserCacheParams::default(),
)
.await
.map_err(|e| Error::Browser(format!("clear_cache: {e}")))?;
Ok(())
}
/// Override geolocation and reload the current page.
pub async fn set_location_and_reload(&self, lat: f64, lng: f64) -> Result<()> {
self.set_geolocation(lat, lng).await?;
self.page()
.execute(chromiumoxide::cdp::browser_protocol::page::ReloadParams::default())
.await
.map_err(|e| Error::Browser(format!("reload: {e}")))?;
Ok(())
}
/// Get all links (href) on the page.
pub async fn links(&self) -> Result<Vec<String>> {
let val = self
.execute("Array.from(document.querySelectorAll('a[href]')).map(a => a.href)")
.await?;
Ok(val
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default())
}
/// Get all image sources on the page.
pub async fn images(&self) -> Result<Vec<String>> {
let val = self
.execute("Array.from(document.querySelectorAll('img[src]')).map(img => img.src)")
.await?;
Ok(val
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default())
}
/// Disable images via Network.setBlockedUrls (URLPattern syntax, absolute).
pub async fn disable_images(&self) -> Result<()> {
self.set_blocked_urls(&[
"*://*/*/*.png",
"*://*/*/*.jpg",
"*://*/*/*.jpeg",
"*://*/*/*.gif",
"*://*/*/*.webp",
"*://*/*/*.svg",
"*://*/*/*.ico",
])
.await
}
/// Override the device scale factor.
pub async fn set_device_scale(&self, scale: f64) -> Result<()> {
self.page().execute(
chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams::new(
1280, 800, scale, false,
),
)
.await
.map_err(|e| Error::Browser(format!("set_device_scale: {e}")))?;
Ok(())
}
/// Set touch emulation.
pub async fn set_touch(&self, enabled: bool) -> Result<()> {
self.page().execute(
chromiumoxide::cdp::browser_protocol::emulation::SetTouchEmulationEnabledParams::new(enabled),
)
.await
.map_err(|e| Error::Browser(format!("set_touch: {e}")))?;
Ok(())
}
/// Navigate and wait for network idle.
pub async fn get_and_wait(&self, url: &str, timeout_secs: u64) -> Result<()> {
self.get(url).await?;
self.wait_js("document.readyState === 'complete'", timeout_secs)
.await
}
/// Count elements matching selector.
pub async fn ele_count(&self, locator_str: &str) -> Result<usize> {
self.eles(locator_str).await.map(|v| v.len())
}
// ── Agent-friendly APIs ──────────────────────────────────────
/// Extract all interactive elements on the page (buttons, links, inputs, etc.).
///
/// Returns structured data for each element: tag, text, type, visibility,
/// bounding box, and all attributes. Designed for AI agents to understand
/// what actions are possible on the current page.
pub async fn interactive_elements(&self) -> Result<Vec<crate::agent::InteractiveElement>> {
let js = crate::js_helpers::JS_INTERACTIVE_ELEMENTS;
let val = self.execute(js).await?;
// execute() may return Value::String (from JSON.stringify) or a raw object
let val = if val.is_string() {
let s = val.as_str().unwrap_or("[]");
serde_json::from_str(s).unwrap_or(serde_json::Value::Array(vec![]))
} else {
val
};
let elements: Vec<crate::agent::InteractiveElement> =
serde_json::from_value(val).unwrap_or_default();
Ok(elements)
}
/// Get a comprehensive summary of the current page.
///
/// Includes URL, title, meta description, all links, forms with their fields,
/// and a list of interactive elements. Perfect for an AI agent's first look
/// at a page.
pub async fn page_summary(&self) -> Result<crate::agent::PageSummary> {
let js = crate::js_helpers::JS_PAGE_SUMMARY;
let val = self.execute(js).await?;
// execute() may return Value::String (from JSON.stringify) or a raw object
let val = if val.is_string() {
let s = val.as_str().unwrap_or("{}");
serde_json::from_str(s).unwrap_or(serde_json::Value::Null)
} else {
val
};
let summary: crate::agent::PageSummary = serde_json::from_value(val)
.map_err(|e| Error::Browser(format!("page_summary parse: {e}")))?;
Ok(summary)
}
/// Get a lightweight snapshot of the current page state.
///
/// Returns url, title, viewport size, scroll position, interactive elements,
/// and the first 2000 characters of visible text. Useful for periodic
/// state checks by an AI agent.
pub async fn page_snapshot(&self) -> Result<crate::agent::PageSnapshot> {
let vis_text_js = crate::js_helpers::js_visible_text(2000);
let vis_text = self
.execute(&vis_text_js)
.await?
.as_str()
.unwrap_or_default()
.to_string();
let url = self.url().await?;
let title = self.title().await?;
let vp_val = self
.execute(
"(function(){return JSON.stringify({w:window.innerWidth,h:window.innerHeight})})()",
)
.await?;
let viewport: serde_json::Value = match vp_val {
serde_json::Value::String(s) => serde_json::from_str(&s).unwrap_or_default(),
v => v,
};
let sc_val = self.execute(crate::js_helpers::JS_SCROLL_STATE).await?;
let scroll: serde_json::Value = match sc_val {
serde_json::Value::String(s) => serde_json::from_str(&s).unwrap_or_default(),
v => v,
};
let interactive = self.interactive_elements().await?;
Ok(crate::agent::PageSnapshot {
url,
title,
viewport_size: format!(
"{}x{}",
viewport.get("w").and_then(|v| v.as_u64()).unwrap_or(0),
viewport.get("h").and_then(|v| v.as_u64()).unwrap_or(0)
),
scroll_position: format!(
"x={} y={}/{}",
scroll
.get("scrollX")
.and_then(|v| v.as_f64())
.unwrap_or(0.0) as i32,
scroll
.get("scrollY")
.and_then(|v| v.as_f64())
.unwrap_or(0.0) as i32,
scroll
.get("scrollHeight")
.and_then(|v| v.as_f64())
.unwrap_or(0.0) as i32,
),
interactive_elements: interactive,
visible_text: vis_text,
})
}
/// Smart click: find an element by text or CSS and click it.
///
/// Tries multiple strategies:
/// 1. Exact text match
/// 2. Partial text match
/// 3. CSS selector (if it looks like one)
///
/// Returns an ActionAttempt with before/after URLs and success status.
pub async fn smart_click(&self, target: &str) -> crate::agent::ActionAttempt {
let before_url = self.url().await.unwrap_or_default();
let mut success = false;
let mut error = None;
// Strategy 1: text=xxx
if let Ok(el) = self.ele(&format!("text={target}")).await {
if let Err(e) = el.click().await {
// Strategy 2: text*=xxx
if let Ok(el2) = self.ele(&format!("text*={target}")).await {
if let Err(e2) = el2.click().await {
error = Some(format!("text match click failed: {e}, {e2}"));
} else {
success = true;
}
}
} else {
success = true;
}
}
// Strategy 3: CSS selector
else if let Ok(el) = self.ele(target).await {
if let Err(e) = el.click().await {
error = Some(format!("css click failed: {e}"));
} else {
success = true;
}
} else {
error = Some(format!("element not found: {target}"));
}
// Wait for potential navigation
self.sleep(std::time::Duration::from_millis(500)).await;
let after_url = self.url().await.unwrap_or_default();
crate::agent::ActionAttempt {
success,
error,
before_url,
after_url,
}
}
/// Smart fill: find an input field by name/label/placeholder and fill it.
///
/// Tries strategies: name attr → placeholder → label text → aria-label.
pub async fn smart_fill(&self, field: &str, value: &str) -> crate::agent::ActionAttempt {
let before_url = self.url().await.unwrap_or_default();
let mut success = false;
let mut error = None;
// Strategy 1: input[name=xxx]
let locators = [
format!("input[name={field}]"),
format!("textarea[name={field}]"),
format!("input[placeholder*={field}]"),
format!("input[aria-label*={field}]"),
];
for loc in &locators {
if let Ok(el) = self.ele(loc).await {
// Use fill() — JS-based, supports all Unicode including Chinese
if let Err(e) = el.fill(value).await {
error = Some(format!("fill failed for {loc}: {e}"));
} else {
success = true;
break;
}
}
}
if !success && error.is_none() {
error = Some(format!("field not found: {field}"));
}
let after_url = self.url().await.unwrap_or_default();
crate::agent::ActionAttempt {
success,
error,
before_url,
after_url,
}
}
/// Wait for the page to reach network idle (no requests for `quiet_ms`).
///
/// Useful for SPAs where content loads dynamically after navigation.
pub async fn wait_network_idle(&self, timeout_secs: u64, quiet_ms: u64) -> Result<()> {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
let quiet = std::time::Duration::from_millis(quiet_ms);
let mut quiet_start = std::time::Instant::now();
let mut last_pending = 0usize;
loop {
let pending: usize = self
.execute("document.querySelectorAll('img[src]:not([complete]), link[rel=stylesheet]:not([disabled]), [loading]').length")
.await
.and_then(|v| Ok(v.as_u64().unwrap_or(0) as usize))
.unwrap_or(0);
if pending == last_pending && pending == 0 {
if quiet_start.elapsed() >= quiet {
return Ok(());
}
} else {
quiet_start = std::time::Instant::now();
last_pending = pending;
}
if std::time::Instant::now() >= deadline {
return Err(Error::Timeout(format!(
"wait_network_idle: still {pending} pending after {timeout_secs}s"
)));
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
/// Safe back navigation with session recovery.
///
/// Unlike raw `back()`, this method:
/// 1. Waits for page stability after navigation
/// 2. Recovers the CDP session if it becomes stale
/// 3. Returns Ok even if history is empty (no-op)
pub async fn safe_back(&self) -> Result<()> {
let url_before = self.url().await.unwrap_or_default();
match self.back().await {
Ok(()) => {
// Wait for page to stabilize
self.sleep(std::time::Duration::from_millis(300)).await;
// Verify navigation happened or stayed
let _ = self.wait_js("document.readyState === 'complete' || document.readyState === 'interactive'", 5).await;
Ok(())
}
Err(e) => {
// If back failed, try JS history.back()
let js_result = self.execute("history.back()").await;
match js_result {
Ok(_) => {
self.sleep(std::time::Duration::from_millis(300)).await;
Ok(())
}
Err(_) => {
// If URL didn't change, it's fine (no history)
let url_after = self.url().await.unwrap_or_default();
if url_after == url_before {
Ok(()) // no history, not an error
} else {
Err(e)
}
}
}
}
}
}
/// Safe forward navigation with session recovery.
pub async fn safe_forward(&self) -> Result<()> {
match self.forward().await {
Ok(()) => {
self.sleep(std::time::Duration::from_millis(300)).await;
let _ = self.wait_js("document.readyState === 'complete' || document.readyState === 'interactive'", 5).await;
Ok(())
}
Err(_) => {
let _ = self.execute("history.forward()").await;
self.sleep(std::time::Duration::from_millis(300)).await;
// Forward failure is usually "no forward history" — not fatal
Ok(())
}
}
}
/// Safe refresh with session recovery.
pub async fn safe_refresh(&self) -> Result<()> {
let url = self.url().await.unwrap_or_default();
// Instead of CDP refresh, re-navigate to same URL
self.get(&url).await
}
/// Auto-retry wrapper: execute an async operation with retries.
///
/// ```ignore
/// let el = page.auto_retry(|| page.ele("text=Login"), 3, 500).await;
/// ```
pub async fn auto_retry<F, Fut, T>(&self, op: F, max_attempts: u32, delay_ms: u64) -> Result<T>
where
F: Fn() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let mut last_err = None;
for attempt in 0..max_attempts {
match op().await {
Ok(val) => return Ok(val),
Err(e) => {
if attempt + 1 < max_attempts {
tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
}
last_err = Some(e);
}
}
}
Err(last_err.unwrap_or_else(|| Error::Timeout("auto_retry: all attempts failed".into())))
}
// ── Tab activation (switch internal operation target) ─────
/// Activate a tab by partial title match.
///
/// Finds a tab whose title contains `keyword`, brings it to the front,
/// and switches the internal operation target so all subsequent
/// method calls (`ele`, `click`, `execute`, etc.) operate on that tab.
///
/// ```ignore
/// page.activate_tab("GitHub").await?;
/// // now page.ele(), page.execute(), etc. target the GitHub tab
/// ```
pub async fn activate_tab(&self, keyword: &str) -> Result<()> {
let tabs = self.tabs().await?;
let titles = self.tab_titles().await?;
let idx = titles
.iter()
.position(|t| t.contains(keyword))
.ok_or_else(|| {
Error::Browser(format!(
"activate_tab: no tab with title containing '{keyword}'"
))
})?;
let target_page = tabs
.into_iter()
.nth(idx)
.ok_or_else(|| Error::Browser("activate_tab: tab index out of range".into()))?;
// Bring the tab to the foreground
target_page
.execute(chromiumoxide::cdp::browser_protocol::page::BringToFrontParams::default())
.await
.map_err(|e| Error::Browser(format!("activate_tab bring_to_front: {e}")))?;
// Switch the internal operation target
self.set_page(target_page);
Ok(())
}
/// Activate a tab by partial URL match.
///
/// Same as `activate_tab` but matches against the tab URL instead of title.
pub async fn activate_tab_by_url(&self, keyword: &str) -> Result<()> {
let tabs = self.tabs().await?;
let urls = self.tab_urls().await?;
let idx = urls
.iter()
.position(|u| u.contains(keyword))
.ok_or_else(|| {
Error::Browser(format!(
"activate_tab_by_url: no tab with url containing '{keyword}'"
))
})?;
let target_page = tabs
.into_iter()
.nth(idx)
.ok_or_else(|| Error::Browser("activate_tab_by_url: tab index out of range".into()))?;
target_page
.execute(chromiumoxide::cdp::browser_protocol::page::BringToFrontParams::default())
.await
.map_err(|e| Error::Browser(format!("activate_tab_by_url bring_to_front: {e}")))?;
self.set_page(target_page);
Ok(())
}
}
// ── InterceptGuard ──────────────────────────────────────────
/// Guard that holds intercepted requests. Disables Fetch domain on drop.
pub struct InterceptGuard {
page: Page,
_active: bool,
paused: Arc<Mutex<Vec<InterceptedRequest>>>,
}
/// A request that has been paused by the Fetch domain.
#[derive(Debug, Clone)]
pub struct InterceptedRequest {
pub request_id: chromiumoxide::cdp::browser_protocol::fetch::RequestId,
pub url: String,
pub method: String,
pub resource_type: String,
}
impl InterceptGuard {
/// Get all currently paused (not yet continued/failed) requests.
pub fn paused_requests(&self) -> Vec<InterceptedRequest> {
self.paused.lock().map(|l| l.clone()).unwrap_or_default()
}
/// Continue a paused request, optionally modifying the URL.
pub async fn continue_request(&self, request_id: &str, new_url: Option<&str>) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::fetch::{ContinueRequestParams, RequestId};
let mut builder = ContinueRequestParams::builder().request_id(RequestId::new(request_id));
if let Some(url) = new_url {
builder = builder.url(url);
}
let params = builder
.build()
.map_err(|e| Error::Browser(format!("continue_request build: {e}")))?;
self.page
.execute(params)
.await
.map_err(|e| Error::Browser(format!("continue_request: {e}")))?;
// Remove from paused list
if let Ok(mut list) = self.paused.lock() {
list.retain(|r| r.request_id.as_ref() != request_id);
}
Ok(())
}
/// Fail a paused request.
pub async fn fail_request(&self, request_id: &str) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::fetch::{FailRequestParams, RequestId};
use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
let params =
FailRequestParams::new(RequestId::new(request_id), ErrorReason::BlockedByClient);
self.page
.execute(params)
.await
.map_err(|e| Error::Browser(format!("fail_request: {e}")))?;
if let Ok(mut list) = self.paused.lock() {
list.retain(|r| r.request_id.as_ref() != request_id);
}
Ok(())
}
/// Fulfill a paused request with a fabricated response — the equivalent of
/// Playwright's `route.fulfill`. Instead of letting the request hit the
/// network (`continue_request`) or killing it (`fail_request`), you return
/// your own status / headers / body. The request never leaves the browser.
///
/// ```ignore
/// let guard = page.enable_intercept("*/api/user").await?;
/// page.ele("#load").await?.click().await?;
/// for req in guard.paused_requests() {
/// guard.fulfill_request(req.request_id.as_ref(), 200,
/// &[("Content-Type", "application/json")], br#"{"name":"mock"}"#).await?;
/// }
/// ```
pub async fn fulfill_request(
&self,
request_id: &str,
status: u16,
headers: &[(&str, &str)],
body: &[u8],
) -> Result<()> {
use base64::Engine;
use chromiumoxide::cdp::browser_protocol::fetch::{
FulfillRequestParams, HeaderEntry, RequestId,
};
let body_b64 = base64::engine::general_purpose::STANDARD.encode(body);
let mut builder = FulfillRequestParams::builder()
.request_id(RequestId::new(request_id))
.response_code(status as i64)
.body(chromiumoxide::types::Binary::from(body_b64));
if !headers.is_empty() {
let hdrs: Vec<HeaderEntry> = headers
.iter()
.map(|(k, v)| HeaderEntry::new(k.to_string(), v.to_string()))
.collect();
builder = builder.response_headers(hdrs);
}
let params = builder
.build()
.map_err(|e| Error::Browser(format!("fulfill_request build: {e}")))?;
self.page
.execute(params)
.await
.map_err(|e| Error::Browser(format!("fulfill_request: {e}")))?;
if let Ok(mut list) = self.paused.lock() {
list.retain(|r| r.request_id.as_ref() != request_id);
}
Ok(())
}
/// Convenience: fulfill a paused request with a JSON body (HTTP 200,
/// `Content-Type: application/json`).
pub async fn fulfill_json(&self, request_id: &str, json: &str) -> Result<()> {
self.fulfill_request(
request_id,
200,
&[("Content-Type", "application/json")],
json.as_bytes(),
)
.await
}
/// Disable interception (also happens on drop).
pub async fn disable(&self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::fetch::DisableParams;
self.page
.execute(DisableParams::default())
.await
.map_err(|e| Error::Browser(format!("Fetch.disable: {e}")))?;
Ok(())
}
}
// ── FrameContext ────────────────────────────────────────────
/// A context for operating inside an iframe.
pub struct FrameContext {
page: Page,
selector: String,
origin_type: String,
}
impl FrameContext {
/// Execute JavaScript inside this iframe (same-origin only).
pub async fn execute(&self, js_code: &str) -> Result<serde_json::Value> {
let escaped = json_escape(&self.selector);
let js = if self.origin_type == "same-origin" {
format!(
"(function(){{ var f = document.querySelector({sel}); if(!f||!f.contentDocument) return null; return (function(){{ {code} }}).call(f.contentWindow, f.contentDocument); }})()",
sel = escaped,
code = js_code
)
} else {
return Err(Error::Browser(
"Cannot execute JS in cross-origin iframe".into(),
));
};
let r = self
.page
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("frame execute: {e}")))?;
Ok(r.value().cloned().unwrap_or(serde_json::Value::Null))
}
/// Find an element inside this iframe (same-origin only).
pub async fn ele(&self, locator_str: &str) -> Result<Element> {
if self.origin_type != "same-origin" {
return Err(Error::Browser(
"Cannot find elements in cross-origin iframe".into(),
));
}
let locator = crate::locator::parse_locator(locator_str)?;
let selector = locator_to_selector(&locator)?;
let escaped_frame = json_escape(&self.selector);
let escaped_inner = json_escape(&selector);
let js = format!(
"(function(){{ var f = document.querySelector({frame}); if(!f||!f.contentDocument) return null; return f.contentDocument.querySelector({inner})?.outerHTML || null; }})()",
frame = escaped_frame,
inner = escaped_inner
);
let html = self
.page
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("frame ele: {e}")))?
.value()
.cloned()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default();
if html.is_empty() {
return Err(Error::ElementNotFound(format!(
"not found in frame: {locator_str}"
)));
}
let text = scraper::Html::parse_document(&html)
.root_element()
.text()
.collect::<Vec<_>>()
.join("");
Ok(Element::new_session(
Some(locator),
html,
String::new(),
text,
Vec::new(),
))
}
/// Get the iframe's HTML content.
pub async fn html(&self) -> Result<String> {
let escaped = json_escape(&self.selector);
let js = format!(
"document.querySelector({sel})?.contentDocument?.documentElement?.outerHTML || ''",
sel = escaped
);
self.page
.evaluate(js.as_str())
.await
.map_err(|e| Error::Browser(format!("frame html: {e}")))?
.value()
.cloned()
.and_then(|v| v.as_str().map(String::from))
.ok_or_else(|| Error::Browser("frame html: no result".into()))
}
}
// ── ActionChain ─────────────────────────────────────────────
/// Builder for complex multi-step input sequences.
pub struct ActionChain {
page: Page,
actions: Vec<ActionItem>,
}
enum ActionItem {
Click { x: f64, y: f64 },
DoubleClick { x: f64, y: f64 },
RightClick { x: f64, y: f64 },
MoveTo { x: f64, y: f64 },
MoveBy { dx: f64, dy: f64 },
KeyDown(String),
KeyUp(String),
Pause(std::time::Duration),
}
impl ActionChain {
/// Create a new ActionChain for the given page.
pub fn new(page: Page) -> Self {
Self {
page,
actions: Vec::new(),
}
}
/// Move mouse to absolute coordinates.
pub fn move_to(mut self, x: f64, y: f64) -> Self {
self.actions.push(ActionItem::MoveTo { x, y });
self
}
/// Move mouse by relative offset.
pub fn move_by(mut self, dx: f64, dy: f64) -> Self {
self.actions.push(ActionItem::MoveBy { dx, dy });
self
}
/// Click at absolute coordinates.
pub fn click_at(mut self, x: f64, y: f64) -> Self {
self.actions.push(ActionItem::Click { x, y });
self
}
/// Double-click at absolute coordinates.
pub fn double_click_at(mut self, x: f64, y: f64) -> Self {
self.actions.push(ActionItem::DoubleClick { x, y });
self
}
/// Right-click at absolute coordinates.
pub fn right_click_at(mut self, x: f64, y: f64) -> Self {
self.actions.push(ActionItem::RightClick { x, y });
self
}
/// Press and hold a key.
pub fn key_down(mut self, key: &str) -> Self {
self.actions.push(ActionItem::KeyDown(key.to_string()));
self
}
/// Release a key.
pub fn key_up(mut self, key: &str) -> Self {
self.actions.push(ActionItem::KeyUp(key.to_string()));
self
}
/// Press and release a key (shortcut for key_down + key_up).
pub fn press(self, key: &str) -> Self {
self.key_down(key).key_up(key)
}
/// Wait for the specified duration.
pub fn pause(mut self, duration: std::time::Duration) -> Self {
self.actions.push(ActionItem::Pause(duration));
self
}
/// Execute all queued actions in sequence.
pub async fn perform(self) -> Result<()> {
use chromiumoxide::cdp::browser_protocol::input::{
DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams,
DispatchMouseEventType, MouseButton,
};
let mut cur_x = 0.0f64;
let mut cur_y = 0.0f64;
for action in self.actions {
match action {
ActionItem::MoveTo { x, y } => {
cur_x = x;
cur_y = y;
let p = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseMoved)
.x(x)
.y(y)
.build()
.map_err(|e| Error::Browser(format!("move: {e}")))?;
self.page
.execute(p)
.await
.map_err(|e| Error::Browser(format!("move: {e}")))?;
}
ActionItem::MoveBy { dx, dy } => {
cur_x += dx;
cur_y += dy;
let p = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseMoved)
.x(cur_x)
.y(cur_y)
.build()
.map_err(|e| Error::Browser(format!("move_by: {e}")))?;
self.page
.execute(p)
.await
.map_err(|e| Error::Browser(format!("move_by: {e}")))?;
}
ActionItem::Click { x, y } => {
cur_x = x;
cur_y = y;
let press = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MousePressed)
.x(x)
.y(y)
.button(MouseButton::Left)
.click_count(1)
.build()
.map_err(|e| Error::Browser(format!("click: {e}")))?;
self.page
.execute(press)
.await
.map_err(|e| Error::Browser(format!("click: {e}")))?;
let release = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseReleased)
.x(x)
.y(y)
.button(MouseButton::Left)
.click_count(1)
.build()
.map_err(|e| Error::Browser(format!("click: {e}")))?;
self.page
.execute(release)
.await
.map_err(|e| Error::Browser(format!("click: {e}")))?;
}
ActionItem::DoubleClick { x, y } => {
cur_x = x;
cur_y = y;
let press = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MousePressed)
.x(x)
.y(y)
.button(MouseButton::Left)
.click_count(2)
.build()
.map_err(|e| Error::Browser(format!("dblclick: {e}")))?;
self.page
.execute(press)
.await
.map_err(|e| Error::Browser(format!("dblclick: {e}")))?;
let release = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseReleased)
.x(x)
.y(y)
.button(MouseButton::Left)
.click_count(2)
.build()
.map_err(|e| Error::Browser(format!("dblclick: {e}")))?;
self.page
.execute(release)
.await
.map_err(|e| Error::Browser(format!("dblclick: {e}")))?;
}
ActionItem::RightClick { x, y } => {
cur_x = x;
cur_y = y;
let press = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MousePressed)
.x(x)
.y(y)
.button(MouseButton::Right)
.click_count(1)
.build()
.map_err(|e| Error::Browser(format!("right: {e}")))?;
self.page
.execute(press)
.await
.map_err(|e| Error::Browser(format!("right: {e}")))?;
let release = DispatchMouseEventParams::builder()
.r#type(DispatchMouseEventType::MouseReleased)
.x(x)
.y(y)
.button(MouseButton::Right)
.click_count(1)
.build()
.map_err(|e| Error::Browser(format!("right: {e}")))?;
self.page
.execute(release)
.await
.map_err(|e| Error::Browser(format!("right: {e}")))?;
}
ActionItem::KeyDown(key) => {
let p = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyDown)
.key(&key)
.build()
.map_err(|e| Error::Browser(format!("keydown: {e}")))?;
self.page
.execute(p)
.await
.map_err(|e| Error::Browser(format!("keydown: {e}")))?;
}
ActionItem::KeyUp(key) => {
let p = DispatchKeyEventParams::builder()
.r#type(DispatchKeyEventType::KeyUp)
.key(&key)
.build()
.map_err(|e| Error::Browser(format!("keyup: {e}")))?;
self.page
.execute(p)
.await
.map_err(|e| Error::Browser(format!("keyup: {e}")))?;
}
ActionItem::Pause(duration) => {
tokio::time::sleep(duration).await;
}
}
}
Ok(())
}
}
// ── Shadow DOM helper functions ──────────────────────────────
/// Build a JS expression that recursively pierces shadow DOM and returns
/// the first matching element via `querySelector`.
///
/// `host_sel` and each entry in `inner_sels` must already be JSON-quoted strings.
fn build_shadow_query_js(host_sel: &str, inner_sels: &[String]) -> String {
if inner_sels.len() == 1 {
format!(
"(function() {{ \
var host = document.querySelector({host_sel}); \
if (!host || !host.shadowRoot) return null; \
return host.shadowRoot.querySelector({inner}); \
}})()",
host_sel = host_sel,
inner = &inner_sels[0]
)
} else {
// Multi-level: recursive descent through shadow roots
let mut body = format!(
"var cur = document.querySelector({host_sel}); \
if (!cur || !cur.shadowRoot) return null; \
cur = cur.shadowRoot;",
host_sel = host_sel
);
for (i, sel) in inner_sels.iter().enumerate() {
if i < inner_sels.len() - 1 {
body.push_str(&format!(
" cur = cur.querySelector({sel}); \
if (!cur || !cur.shadowRoot) return null; \
cur = cur.shadowRoot;",
sel = sel
));
} else {
body.push_str(&format!(" return cur.querySelector({sel});", sel = sel));
}
}
format!("(function() {{ {body} }})()")
}
}
/// Build a JS expression that recursively pierces shadow DOM and returns
/// all matching elements via `querySelectorAll` (on the final level).
fn build_shadow_query_all_js(host_sel: &str, inner_sels: &[String]) -> String {
if inner_sels.len() == 1 {
format!(
"(function() {{ \
var host = document.querySelector({host_sel}); \
if (!host || !host.shadowRoot) return []; \
return host.shadowRoot.querySelectorAll({inner}); \
}})()",
host_sel = host_sel,
inner = &inner_sels[0]
)
} else {
// Multi-level: navigate to the penultimate level, then querySelectorAll
let mut body = format!(
"var cur = document.querySelector({host_sel}); \
if (!cur || !cur.shadowRoot) return []; \
cur = cur.shadowRoot;",
host_sel = host_sel
);
for (i, sel) in inner_sels.iter().enumerate() {
if i < inner_sels.len() - 1 {
body.push_str(&format!(
" cur = cur.querySelector({sel}); \
if (!cur || !cur.shadowRoot) return []; \
cur = cur.shadowRoot;",
sel = sel
));
} else {
body.push_str(&format!(" return cur.querySelectorAll({sel});", sel = sel));
}
}
format!("(function() {{ {body} }})()")
}
}