rpage 1.0.0

A Rust browser automation library inspired by DrissionPage
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
//! WebPage - unified page combining Chromium and Session modes.
//!
//! The core abstraction: seamlessly switch between browser mode
//! and HTTP request mode with automatic cookie synchronization.

use std::cell::RefCell;
use std::path::PathBuf;
use std::sync::Arc;

use tracing::info;

use crate::chromium_page::ChromiumPage;
use crate::chromium_page::FrameContext;
use crate::chromium_page::{ActionChain, InterceptGuard};
use crate::config::{ChromiumOptions, SessionOptions, WebPageOptions};
use crate::cookie_hub::CookieHub;
use crate::download::DownloadManager;
use crate::element::Element;
use crate::error::{Error, Result};
use crate::network::NetworkMonitor;
use crate::session_page::SessionPage;

/// Current page mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageMode {
    Chromium,
    Session,
}

impl std::fmt::Display for PageMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PageMode::Chromium => write!(f, "Chromium"),
            PageMode::Session => write!(f, "Session"),
        }
    }
}

/// WebPage — switch between browser and HTTP mode with `to_session()` / `to_chromium()`.
///
/// Cookies are automatically synchronized when switching modes.
/// All methods take `&self` (uses interior mutability for Session mode).
pub struct WebPage {
    mode: PageMode,
    chromium: Option<ChromiumPage>,
    session: RefCell<SessionPage>,
    cookie_hub: Arc<CookieHub>,
    opts: WebPageOptions,
}

impl WebPage {
    /// **启动浏览器** — 一个函数搞定,零自动化标记,永不触发验证码。
    /// Uses a random port to avoid multi-instance conflicts.
    pub async fn new() -> Result<Self> {
        let cookie_hub = Arc::new(CookieHub::new());
        let session = SessionPage::with_cookie_hub(cookie_hub.clone(), SessionOptions::default())?;
        let chromium = ChromiumPage::new().await?;
        Ok(Self {
            mode: PageMode::Chromium,
            chromium: Some(chromium),
            session: RefCell::new(session),
            cookie_hub,
            opts: WebPageOptions::default(),
        })
    }

    /// Create with custom options.
    pub async fn with_options(opts: WebPageOptions) -> Result<Self> {
        let cookie_hub = Arc::new(CookieHub::new());
        let session = SessionPage::with_cookie_hub(cookie_hub.clone(), opts.session.clone())?;
        let chromium = if opts.initial_mode == PageMode::Chromium {
            Some(ChromiumPage::with_options(opts.chromium.clone()).await?)
        } else {
            None
        };
        Ok(Self {
            mode: opts.initial_mode,
            chromium,
            session: RefCell::new(session),
            cookie_hub,
            opts,
        })
    }

    /// Create in Session-only mode (no browser).
    pub fn session_only(opts: Option<SessionOptions>) -> Result<Self> {
        let s_opts = opts.unwrap_or_default();
        let cookie_hub = Arc::new(CookieHub::new());
        let session = SessionPage::with_cookie_hub(cookie_hub.clone(), s_opts.clone())?;
        Ok(Self {
            mode: PageMode::Session,
            chromium: None,
            session: RefCell::new(session),
            cookie_hub,
            opts: WebPageOptions {
                chromium: ChromiumOptions::default(),
                session: s_opts,
                initial_mode: PageMode::Session,
            },
        })
    }

    /// **接管已打开的浏览器** — 零自动化标记,永不触发验证码。
    pub async fn connect(debug_url: &str) -> Result<Self> {
        let cookie_hub = Arc::new(CookieHub::new());
        let session = SessionPage::with_cookie_hub(cookie_hub.clone(), SessionOptions::default())?;
        let chromium = ChromiumPage::connect(debug_url).await?;
        Ok(Self {
            mode: PageMode::Chromium,
            chromium: Some(chromium),
            session: RefCell::new(session),
            cookie_hub,
            opts: WebPageOptions::default(),
        })
    }

    // ── Mode ─────────────────────────────────────────────────

    pub fn mode(&self) -> PageMode {
        self.mode
    }

    /// Switch to Session mode. Syncs cookies from browser → store.
    pub async fn to_session(&mut self) -> Result<()> {
        if self.mode == PageMode::Session {
            return Ok(());
        }
        if let Some(ref c) = self.chromium {
            let cookies = c.cookies().await?;
            self.cookie_hub.sync_from_chromium(cookies)?;
        }
        self.mode = PageMode::Session;
        info!("Switched to Session mode");
        Ok(())
    }

    /// Switch to Chromium mode. Launches browser if needed.
    pub async fn to_chromium(&mut self) -> Result<()> {
        if self.mode == PageMode::Chromium {
            return Ok(());
        }
        if self.chromium.is_none() {
            self.chromium = Some(ChromiumPage::with_options(self.opts.chromium.clone()).await?);
        }
        // Sync cookies from session store → browser
        let url_opt = self.session.borrow().url().map(String::from);
        if let (Some(ref c), Some(url)) = (&self.chromium, url_opt) {
            let cookies = self.cookie_hub.get_cookies(&url)?;
            for ck in cookies {
                let info = crate::chromium_page::CookieInfo {
                    name: ck.name().to_string(),
                    value: ck.value().to_string(),
                    domain: Some(match &ck.domain {
                        cookie_store::CookieDomain::Suffix(d) => d.to_string(),
                        cookie_store::CookieDomain::HostOnly(d) => d.to_string(),
                        _ => String::new(),
                    }),
                    path: Some(ck.path.to_string()),
                    secure: ck.secure().unwrap_or(false),
                    http_only: ck.http_only().unwrap_or(false),
                };
                c.set_cookie(info).await.ok();
            }
        }
        self.mode = PageMode::Chromium;
        info!("Switched to Chromium mode");
        Ok(())
    }

    // ── Navigation (all &self) ───────────────────────────────

    /// Navigate to URL. Auto-waits for page load in Chromium mode.
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn get(&self, url: &str) -> Result<()> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .get(url)
                    .await?;
            }
            PageMode::Session => {
                self.session.borrow_mut().get(url).await?;
            }
        }
        Ok(())
    }

    /// POST request.
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn post(&self, url: &str, body: &str) -> Result<String> {
        match self.mode {
            PageMode::Chromium => {
                let c = self
                    .chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?;
                let js = format!(
                    "fetch('{}', {{method:'POST', body:{}}}).then(r=>r.text())",
                    url,
                    serde_json::to_string(body).unwrap_or_else(|_| "\"\"".to_string())
                );
                let val = c.execute(&js).await?;
                Ok(val.as_str().unwrap_or("").to_string())
            }
            PageMode::Session => self.session.borrow_mut().post(url, body.to_string()).await,
        }
    }

    // ── Elements ─────────────────────────────────────────────

    /// Find first element. Auto-retries up to 5s in Chromium mode.
    pub async fn ele(&self, locator_str: &str) -> Result<Element> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .ele(locator_str)
                    .await
            }
            PageMode::Session => self.session.borrow().ele(locator_str),
        }
    }

    /// Find all elements.
    pub async fn eles(&self, locator_str: &str) -> Result<Vec<Element>> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .eles(locator_str)
                    .await
            }
            PageMode::Session => self.session.borrow().eles(locator_str),
        }
    }

    /// Find an element inside a Shadow DOM host (Chromium mode only).
    ///
    /// Usage: `page.shadow_ele("#host >>> .inner")`
    pub async fn shadow_ele(&self, locator_str: &str) -> Result<Element> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("shadow_ele requires Chromium mode".into()))?
            .shadow_ele(locator_str)
            .await
    }

    /// Find all elements inside a Shadow DOM host (Chromium mode only).
    ///
    /// Usage: `page.shadow_eles("#host >>> .inner")`
    pub async fn shadow_eles(&self, locator_str: &str) -> Result<Vec<Element>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("shadow_eles requires Chromium mode".into()))?
            .shadow_eles(locator_str)
            .await
    }

    // ── Page info ────────────────────────────────────────────

    /// Page HTML.
    pub async fn html(&self) -> Result<String> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .html()
                    .await
            }
            PageMode::Session => Ok(self.session.borrow().html().to_string()),
        }
    }

    /// Page title.
    pub async fn title(&self) -> Result<String> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .title()
                    .await
            }
            PageMode::Session => self
                .session
                .borrow()
                .title()
                .ok_or_else(|| Error::Browser("no title".into())),
        }
    }

    /// Current URL.
    pub async fn url(&self) -> Result<String> {
        match self.mode {
            PageMode::Chromium => {
                self.chromium
                    .as_ref()
                    .ok_or_else(|| Error::Browser("no chromium".into()))?
                    .url()
                    .await
            }
            PageMode::Session => self
                .session
                .borrow()
                .url()
                .map(String::from)
                .ok_or_else(|| Error::Browser("no URL".into())),
        }
    }

    // ── JS / Screenshot (Chromium only) ──────────────────────

    /// Execute JavaScript.
    pub async fn execute(&self, js: &str) -> Result<serde_json::Value> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("execute requires Chromium mode".into()))?
            .execute(js)
            .await
    }

    /// Screenshot → file.
    pub async fn screenshot(&self, path: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("screenshot requires Chromium mode".into()))?
            .screenshot(path)
            .await
    }

    /// Screenshot → bytes.
    pub async fn screenshot_bytes(&self) -> Result<Vec<u8>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("screenshot requires Chromium mode".into()))?
            .screenshot_bytes()
            .await
    }

    // ── Navigation helpers ───────────────────────────────────

    pub async fn refresh(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("refresh requires Chromium mode".into()))?
            .refresh()
            .await
    }

    pub async fn back(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("back requires Chromium mode".into()))?
            .back()
            .await
    }

    pub async fn forward(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("forward requires Chromium mode".into()))?
            .forward()
            .await
    }

    /// 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<()> {
        if let Some(ref c) = self.chromium {
            c.close().await?;
        }
        Ok(())
    }

    /// Manually sync cookies from browser → session store.
    pub async fn sync_cookies(&self) -> Result<()> {
        if let Some(ref c) = self.chromium {
            let cookies = c.cookies().await?;
            self.cookie_hub.sync_from_chromium(cookies)?;
        }
        Ok(())
    }

    // ── Browser lifecycle ────────────────────────────────────

    /// Quit the browser entirely.
    pub async fn quit(&self) -> Result<()> {
        if let Some(ref c) = self.chromium {
            c.quit().await?;
        }
        Ok(())
    }

    // ── Connection status / reconnection (f30) ─────────────

    /// Check if the browser connection is still alive (Chromium mode only).
    ///
    /// Returns `false` if there is no chromium instance or the browser is
    /// no longer reachable via its debug URL.
    pub fn is_connected(&self) -> bool {
        self.chromium
            .as_ref()
            .map(|c| c.is_connected())
            .unwrap_or(false)
    }

    /// Reconnect to the browser using the saved debug URL (Chromium mode only).
    ///
    /// Drops the current CDP connection and creates a fresh one to the same
    /// debug endpoint. The browser must still be running for this to succeed.
    pub async fn reconnect(&mut self) -> Result<()> {
        if let Some(ref mut c) = self.chromium {
            c.reconnect().await?;
        } else {
            return Err(Error::Browser("no chromium instance to reconnect".into()));
        }
        Ok(())
    }

    /// Return the saved debug URL (e.g. `http://localhost:9222`) if in Chromium mode.
    pub fn debug_url(&self) -> Option<&str> {
        self.chromium.as_ref().map(|c| c.debug_url())
    }

    // ── Scroll ────────────────────────────────────────────────

    /// Scroll page to absolute position.
    pub async fn scroll_to(&self, x: u32, y: u32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll requires Chromium mode".into()))?
            .scroll_to(x, y)
            .await
    }

    /// Scroll to page top.
    pub async fn scroll_to_top(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll requires Chromium mode".into()))?
            .scroll_to_top()
            .await
    }

    /// Scroll to page bottom.
    pub async fn scroll_to_bottom(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll requires Chromium mode".into()))?
            .scroll_to_bottom()
            .await
    }

    /// Scroll down by pixels.
    pub async fn scroll_down(&self, pixels: u32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll requires Chromium mode".into()))?
            .scroll_down(pixels)
            .await
    }

    /// Scroll up by pixels.
    pub async fn scroll_up(&self, pixels: u32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll requires Chromium mode".into()))?
            .scroll_up(pixels)
            .await
    }

    // ── Dialog / Alert ────────────────────────────────────────

    /// Handle a JavaScript dialog (alert/confirm/prompt).
    pub async fn handle_alert(&self, accept: bool, text: Option<&str>) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("handle_alert requires Chromium mode".into()))?
            .handle_alert(accept, text)
            .await
    }

    // ── Frames ────────────────────────────────────────────────

    /// Read an iframe's HTML content.
    pub async fn frame_html(&self, selector: &str) -> Result<String> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("frame_html requires Chromium mode".into()))?
            .frame_html(selector)
            .await
    }

    /// Execute JS in an iframe context.
    pub async fn frame_execute(&self, selector: &str, js: &str) -> Result<serde_json::Value> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("frame_execute requires Chromium mode".into()))?
            .frame_execute(selector, js)
            .await
    }

    // ── Cookie management ─────────────────────────────────────

    /// Delete a cookie by name.
    pub async fn delete_cookie(&self, name: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("delete_cookie requires Chromium mode".into()))?
            .delete_cookie(name)
            .await
    }

    /// Clear all cookies.
    pub async fn clear_cookies(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("clear_cookies requires Chromium mode".into()))?
            .clear_cookies()
            .await
    }

    // ── Multi-window management (f26) ──────────────────────────

    /// Return the `user_data_dir` configured for this instance (if any).
    pub fn user_data_dir(&self) -> Option<&PathBuf> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("user_data_dir requires Chromium mode".into()))
            .ok()
            .and_then(|c| c.user_data_dir())
    }

    /// Read all cookies from `self` and write them into `other`.
    pub async fn share_cookies_to(&self, other: &WebPage) -> Result<()> {
        let src = self.chromium.as_ref().ok_or_else(|| {
            Error::Browser("share_cookies_to source requires Chromium mode".into())
        })?;
        let dst = other.chromium.as_ref().ok_or_else(|| {
            Error::Browser("share_cookies_to target requires Chromium mode".into())
        })?;
        src.share_cookies_to(dst).await
    }

    /// Clone this session: launch a new browser sharing the same user_data_dir.
    pub async fn clone_session(&self) -> Result<WebPage> {
        let src = self
            .chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("clone_session requires Chromium mode".into()))?;
        let cloned = src.clone_session().await?;
        let mut wp = WebPage::with_options(self.opts.clone()).await?;
        wp.chromium = Some(cloned);
        Ok(wp)
    }

    // ── Cookies (read/set already exist, add tabs) ────────────

    /// Get all open tabs.
    pub async fn tabs(&self) -> Result<Vec<chromiumoxide::Page>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("tabs requires Chromium mode".into()))?
            .tabs()
            .await
    }

    /// Open a new tab.
    pub async fn new_tab(&self) -> Result<chromiumoxide::Page> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("new_tab requires Chromium mode".into()))?
            .new_tab()
            .await
    }

    /// Get all tab titles.
    pub async fn tab_titles(&self) -> Result<Vec<String>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("tab_titles requires Chromium mode".into()))?
            .tab_titles()
            .await
    }

    /// Get all tab URLs.
    pub async fn tab_urls(&self) -> Result<Vec<String>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("tab_urls requires Chromium mode".into()))?
            .tab_urls()
            .await
    }

    /// Switch to a tab by index (0-based).
    pub async fn switch_to_tab(&self, index: usize) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("switch_to_tab requires Chromium mode".into()))?
            .switch_to_tab(index)
            .await
    }

    /// Close a tab by index.
    pub async fn close_tab(&self, index: usize) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("close_tab requires Chromium mode".into()))?
            .close_tab(index)
            .await
    }

    /// Activate a tab by partial title match and switch the internal operation target.
    ///
    /// After calling this, all subsequent methods (`ele`, `click`, `execute`, etc.)
    /// operate on the activated tab.
    pub async fn activate_tab(&self, keyword: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("activate_tab requires Chromium mode".into()))?
            .activate_tab(keyword)
            .await
    }

    /// Activate a tab by partial URL match and switch the internal operation target.
    pub async fn activate_tab_by_url(&self, keyword: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("activate_tab_by_url requires Chromium mode".into()))?
            .activate_tab_by_url(keyword)
            .await
    }

    /// Set a cookie.
    pub async fn set_cookie(&self, cookie: crate::chromium_page::CookieInfo) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_cookie requires Chromium mode".into()))?
            .set_cookie(cookie)
            .await
    }

    /// Get all cookies.
    pub async fn cookies(&self) -> Result<Vec<crate::chromium_page::CookieInfo>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("cookies requires Chromium mode".into()))?
            .cookies()
            .await
    }

    /// Evaluate JS on every new document.
    pub async fn evaluate_on_new_document(&self, js: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("requires Chromium mode".into()))?
            .evaluate_on_new_document(js)
            .await
    }

    /// Register a named init script that runs on every new document.
    pub async fn add_init_script(&self, name: &str, js: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("add_init_script requires Chromium mode".into()))?
            .add_init_script(name, js)
            .await
    }

    /// Remove a previously registered named init script.
    pub async fn remove_init_script(&self, name: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("remove_init_script requires Chromium mode".into()))?
            .remove_init_script(name)
            .await
    }

    /// List all registered init script names.
    pub fn list_init_scripts(&self) -> Vec<String> {
        self.chromium
            .as_ref()
            .map(|c| c.list_init_scripts())
            .unwrap_or_default()
    }

    // ── Press / PDF / Viewport (Chromium only) ──────────────

    /// Press a key at page level.
    pub async fn press(&self, key: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("press requires Chromium mode".into()))?
            .press(key)
            .await
    }

    /// Export page to PDF with default options (backward compatible).
    pub async fn pdf(&self, path: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("pdf requires Chromium mode".into()))?
            .pdf(path)
            .await
    }

    /// Export page to PDF with custom options and save to `path`.
    pub async fn pdf_to_file(
        &self,
        path: &str,
        opts: crate::chromium_page::PdfOptions,
    ) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("pdf_to_file requires Chromium mode".into()))?
            .pdf_to_file(path, opts)
            .await
    }

    /// Export page to PDF with custom options and return raw bytes.
    pub async fn pdf_bytes(&self, opts: crate::chromium_page::PdfOptions) -> Result<Vec<u8>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("pdf_bytes requires Chromium mode".into()))?
            .pdf_bytes(opts)
            .await
    }

    /// Set viewport size at runtime.
    pub async fn set_viewport(&self, width: u32, height: u32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_viewport requires Chromium mode".into()))?
            .set_viewport(width, height)
            .await
    }

    // ── Conditional wait (Chromium only) ──────────────────

    /// Wait for an element matching the locator to appear.
    pub async fn wait_ele(&self, locator_str: &str, timeout_secs: u64) -> Result<Element> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_ele requires Chromium mode".into()))?
            .wait_ele(locator_str, timeout_secs)
            .await
    }

    /// Wait for page title to contain the given text.
    pub async fn wait_title_contains(&self, text: &str, timeout_secs: u64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_title_contains requires Chromium mode".into()))?
            .wait_title_contains(text, timeout_secs)
            .await
    }

    /// Wait for URL to contain the given text.
    pub async fn wait_url_contains(&self, text: &str, timeout_secs: u64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_url_contains requires Chromium mode".into()))?
            .wait_url_contains(text, 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<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_ele_hidden requires Chromium mode".into()))?
            .wait_ele_hidden(locator_str, timeout_secs)
            .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<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_ele_deleted requires Chromium mode".into()))?
            .wait_ele_deleted(locator_str, timeout_secs)
            .await
    }

    // ── Runtime configuration (Chromium only) ─────────────

    /// Set extra HTTP headers for all subsequent requests.
    pub async fn set_extra_headers(
        &self,
        headers: std::collections::HashMap<String, String>,
    ) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_extra_headers requires Chromium mode".into()))?
            .set_extra_headers(headers)
            .await
    }

    /// Override user agent at runtime.
    pub async fn set_user_agent(&self, user_agent: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_user_agent requires Chromium mode".into()))?
            .set_user_agent(user_agent)
            .await
    }

    /// Set proxy authentication (Chromium only).
    ///
    /// Configures `Proxy-Authorization: Basic <base64(user:pass)>` via
    /// `Network.setExtraHTTPHeaders`. The browser must have been launched
    /// with `--proxy-server` (e.g. via `ChromiumOptions::proxy`) for this
    /// to take effect.
    pub async fn set_proxy_auth(&self, user: &str, pass: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_proxy_auth requires Chromium mode".into()))?
            .set_proxy_auth(user, pass)
            .await
    }

    // ── Multipart POST (Session only) ───────────────────────

    /// Send a multipart/form-data POST request with file upload (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn post_multipart(
        &self,
        url: &str,
        fields: std::collections::HashMap<String, String>,
        file_field: &str,
        file_path: &str,
    ) -> Result<String> {
        self.session
            .borrow_mut()
            .post_multipart(url, fields, file_field, file_path)
            .await
    }

    // ── Session convenience proxies ──────────────────────────

    /// Session GET request (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_get(&self, url: &str) -> Result<String> {
        self.session.borrow_mut().get(url).await
    }

    /// Session POST request with plain text body (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_post(&self, url: &str, body: &str) -> Result<String> {
        self.session.borrow_mut().post(url, body.to_string()).await
    }

    /// Session PUT request with plain text body (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_put(&self, url: &str, body: &str) -> Result<String> {
        self.session.borrow_mut().put(url, body.to_string()).await
    }

    /// Session DELETE request (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_delete(&self, url: &str) -> Result<String> {
        self.session.borrow_mut().delete(url).await
    }

    /// Session HEAD request (Session mode). Returns the HTTP status code.
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_head(&self, url: &str) -> Result<reqwest::StatusCode> {
        self.session.borrow_mut().head(url).await
    }

    /// Session POST JSON request (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_post_json(
        &self,
        url: &str,
        json: &serde_json::Value,
    ) -> Result<reqwest::Response> {
        self.session.borrow_mut().post_json(url, json).await
    }

    /// Session PATCH request with plain text body (Session mode).
    #[allow(clippy::await_holding_refcell_ref)]
    pub async fn session_patch(&self, url: &str, body: &str) -> Result<String> {
        self.session.borrow_mut().patch(url, body.to_string()).await
    }

    // ── Cookie save/load ────────────────────────────────────

    /// Save all cookies to a JSON file.
    pub fn save_cookies_to_file(&self, path: &str) -> Result<()> {
        self.cookie_hub.save_to_file(path)
    }

    /// Load cookies from a JSON file.
    pub fn load_cookies_from_file(&self, path: &str) -> Result<()> {
        self.cookie_hub.load_from_file(path)
    }

    // ── Accessors ────────────────────────────────────────────

    pub fn chromium(&self) -> Option<&ChromiumPage> {
        self.chromium.as_ref()
    }
    pub fn session(&self) -> std::cell::Ref<'_, SessionPage> {
        self.session.borrow()
    }
    pub fn session_mut(&self) -> std::cell::RefMut<'_, SessionPage> {
        self.session.borrow_mut()
    }
    pub fn cookie_hub(&self) -> &Arc<CookieHub> {
        &self.cookie_hub
    }

    // ── Low-level access ─────────────────────────────────────

    /// Access the underlying CDP page for advanced operations (cheap Arc clone).
    pub fn inner_page(&self) -> Option<chromiumoxide::Page> {
        self.chromium.as_ref().map(|c| c.inner_page())
    }

    /// Access the browser instance.
    pub fn browser(&self) -> Option<&chromiumoxide::browser::Browser> {
        self.chromium.as_ref().map(|c| c.browser())
    }

    /// Get current ChromiumOptions.
    pub fn options(&self) -> Option<&ChromiumOptions> {
        self.chromium.as_ref().map(|c| c.options())
    }

    /// Get download manager.
    pub fn download_manager(&self) -> Option<&std::sync::Arc<DownloadManager>> {
        self.chromium.as_ref().map(|c| c.download_manager())
    }

    /// Check if in Chromium mode.
    pub fn is_chromium(&self) -> bool {
        matches!(self.mode, PageMode::Chromium)
    }

    /// Check if in Session mode.
    pub fn is_session(&self) -> bool {
        matches!(self.mode, PageMode::Session)
    }

    // ── Advanced features ─────────────────────────────────

    /// Enter an iframe by CSS selector (Chromium mode only).
    pub async fn enter_frame(&self, selector: &str) -> Result<FrameContext> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("Not in Chromium mode".into()))?
            .enter_frame(selector)
            .await
    }

    /// Get the network monitor (Chromium mode only).
    pub fn network_monitor(&self) -> Option<&Arc<NetworkMonitor>> {
        self.chromium.as_ref().map(|c| c.network_monitor())
    }

    /// Get all captured console log entries (Chromium mode only).
    pub fn console_log(&self) -> Vec<crate::console::ConsoleEntry> {
        self.chromium
            .as_ref()
            .map(|c| c.console_log())
            .unwrap_or_default()
    }

    /// Get all captured JS exceptions (Chromium mode only).
    pub fn console_exceptions(&self) -> Vec<crate::console::JsException> {
        self.chromium
            .as_ref()
            .map(|c| c.console_exceptions())
            .unwrap_or_default()
    }

    /// Clear all captured console entries and exceptions (Chromium mode only).
    pub fn clear_console(&self) {
        if let Some(ref c) = self.chromium {
            c.clear_console();
        }
    }

    /// Get all captured WebSocket frames (Chromium mode only).
    pub fn ws_frames(&self) -> Vec<crate::websocket::WsFrame> {
        self.chromium
            .as_ref()
            .map(|c| c.ws_frames())
            .unwrap_or_default()
    }

    /// Get all captured WebSocket lifecycle events (Chromium mode only).
    pub fn ws_events(&self) -> Vec<crate::websocket::WsEvent> {
        self.chromium
            .as_ref()
            .map(|c| c.ws_events())
            .unwrap_or_default()
    }

    /// Clear all captured WebSocket frames and events (Chromium mode only).
    pub fn clear_ws_frames(&self) {
        if let Some(ref c) = self.chromium {
            c.clear_ws_frames();
        }
    }

    /// Create an ActionChain for complex multi-step input sequences.
    ///
    /// ```ignore
    /// let chain = page.actions();
    /// chain.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) -> Option<ActionChain> {
        self.chromium.as_ref().map(|c| c.actions())
    }

    /// Enable network request interception. Returns an `InterceptGuard`
    /// that holds paused requests. Call `continue_request()` or `fail_request()`
    /// to resume them. Interception is disabled when the guard is dropped.
    ///
    /// ```ignore
    /// let guard = page.enable_intercept("*/api/*").await?;
    /// tokio::time::sleep(Duration::from_secs(5)).await;
    /// for req in guard.paused_requests() {
    ///     guard.continue_request(&req.request_id, None).await?;
    /// }
    /// guard.disable().await?;
    /// ```
    pub async fn enable_intercept(&self, url_pattern: &str) -> Result<InterceptGuard> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("Not in Chromium mode".into()))?
            .enable_intercept(url_pattern)
            .await
    }

    /// Get all tracked downloads.
    pub fn downloads(&self) -> Vec<crate::download::DownloadInfo> {
        self.chromium
            .as_ref()
            .map(|c| c.downloads())
            .unwrap_or_default()
    }

    /// Wait for the most recent download to finish.
    pub async fn wait_download(&self, timeout_secs: u64) -> Result<crate::download::DownloadInfo> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("Not in Chromium mode".into()))?
            .wait_download(timeout_secs)
            .await
    }

    /// Wait until a JavaScript expression evaluates to a truthy value.
    pub async fn wait_js(&self, expression: &str, timeout_secs: u64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("Not in Chromium mode".into()))?
            .wait_js(expression, timeout_secs)
            .await
    }

    /// 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('/api/data').then(r => r.json())").await?;
    /// ```
    pub async fn run_async_js(&self, expression: &str) -> Result<serde_json::Value> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("run_async_js requires Chromium mode".into()))?
            .run_async_js(expression)
            .await
    }

    /// 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.
    ///
    /// ```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> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("run_js_with_args requires Chromium mode".into()))?
            .run_js_with_args(expression, args)
            .await
    }

    /// Wait for a download whose URL contains `url_pattern` to complete.
    ///
    /// Polls the download manager and returns the
    /// [`DownloadInfo`](crate::download::DownloadInfo) once a matching
    /// download reaches a terminal state, or times out after `timeout_secs`.
    ///
    /// ```ignore
    /// let dl = page.wait_for_download("/files/report.pdf", 30).await?;
    /// ```
    pub async fn wait_for_download(
        &self,
        url_pattern: &str,
        timeout_secs: u64,
    ) -> Result<crate::download::DownloadInfo> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_for_download requires Chromium mode".into()))?
            .wait_for_download(url_pattern, timeout_secs)
            .await
    }

    /// Get the `Content-Type` of the current page's main document.
    ///
    /// ```ignore
    /// let ct = page.get_content_type().await?;
    /// ```
    pub async fn get_content_type(&self) -> Result<String> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("get_content_type requires Chromium mode".into()))?
            .get_content_type()
            .await
    }

    /// Select all text on the page (Ctrl+A).
    pub async fn select_all_text(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("select_all_text requires Chromium mode".into()))?
            .select_all_text()
            .await
    }

    /// Copy the currently selected text to the clipboard (Ctrl+C).
    pub async fn copy_text(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("copy_text requires Chromium mode".into()))?
            .copy_text()
            .await
    }

    /// Paste text from the clipboard (Ctrl+V).
    pub async fn paste_text(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("paste_text requires Chromium mode".into()))?
            .paste_text()
            .await
    }

    /// Search for `text` on the current page.
    ///
    /// 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> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("find_text requires Chromium mode".into()))?
            .find_text(text)
            .await
    }

    // ── Performance metrics (Chromium only) ──────────────────

    /// Grant browser permissions for the given origin (Chromium only).
    ///
    /// ```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<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("grant_permissions requires Chromium mode".into()))?
            .grant_permissions(origin, permissions)
            .await
    }

    /// Reset all browser permission overrides (Chromium only).
    ///
    /// ```ignore
    /// page.reset_permissions().await?;
    /// ```
    pub async fn reset_permissions(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("reset_permissions requires Chromium mode".into()))?
            .reset_permissions()
            .await
    }

    /// Retrieve current CDP performance metrics.
    ///
    /// Returns a list of `(name, value)` pairs from the browser's
    /// Performance domain (Timestamp, Documents, Frames, …).
    pub async fn performance_metrics(&self) -> Result<Vec<(String, f64)>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("performance_metrics requires Chromium mode".into()))?
            .performance_metrics()
            .await
    }

    /// Extract page-load timing via `performance.timing`.
    ///
    /// Returns a `HashMap` with keys `dns`, `tcp`, `request`, `response`,
    /// `dom`, `load`, `domInteractive`, `domContentLoaded` (values in ms).
    pub async fn page_timing(&self) -> Result<std::collections::HashMap<String, f64>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("page_timing requires Chromium mode".into()))?
            .page_timing()
            .await
    }

    // ── Device emulation (f22, Chromium only) ─────────────────

    /// Override the browser's geolocation (Chromium only).
    pub async fn set_geolocation(&self, lat: f64, lng: f64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_geolocation requires Chromium mode".into()))?
            .set_geolocation(lat, lng)
            .await
    }

    /// Override the browser's timezone (Chromium only).
    pub async fn set_timezone(&self, tz: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_timezone requires Chromium mode".into()))?
            .set_timezone(tz)
            .await
    }

    /// Emulate a device by setting viewport, scale factor, touch mode, and user agent (Chromium only).
    pub async fn emulate_device(
        &self,
        width: u32,
        height: u32,
        ua: &str,
        scale: f64,
        touch: bool,
    ) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("emulate_device requires Chromium mode".into()))?
            .emulate_device(width, height, ua, scale, touch)
            .await
    }

    // ── File chooser (f25) ────────────────────────────────────

    /// Enable or disable interception of file chooser dialogs (Chromium only).
    pub async fn set_file_chooser(&self, enabled: bool) {
        if let Some(ref c) = self.chromium {
            c.set_file_chooser(enabled).await;
        }
    }

    /// Wait for a file chooser dialog event within the given timeout (Chromium only).
    pub async fn wait_file_chooser(
        &self,
        timeout_secs: u64,
    ) -> Result<crate::chromium_page::FileChooserInfo> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_file_chooser requires Chromium mode".into()))?
            .wait_file_chooser(timeout_secs)
            .await
    }

    // ── Audio control (f34) ──────────────────────────────────

    /// Mute all audio on the page (Chromium only).
    pub async fn mute(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("mute requires Chromium mode".into()))?
            .mute()
            .await
    }

    /// Unmute audio on the page (Chromium only).
    pub async fn unmute(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("unmute requires Chromium mode".into()))?
            .unmute()
            .await
    }

    // ── DOM Snapshot (f31) ────────────────────────────────────

    /// Capture a full DOM snapshot of the current page as a JSON tree (Chromium only).
    ///
    /// Each node is represented as `{ type, name, attrs?, children?, value? }`.
    pub async fn dom_snapshot(&self) -> Result<serde_json::Value> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("dom_snapshot requires Chromium mode".into()))?
            .dom_snapshot()
            .await
    }

    // ── Clipboard (f32) ──────────────────────────────────────

    /// Read text from the clipboard (Chromium only).
    ///
    /// The page must be focused and have clipboard-read permission.
    /// Use `grant_permissions` if needed.
    pub async fn clipboard_read(&self) -> Result<String> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("clipboard_read requires Chromium mode".into()))?
            .clipboard_read()
            .await
    }

    /// Write text to the clipboard (Chromium only).
    ///
    /// The page must be focused and have clipboard-write permission.
    /// Use `grant_permissions` if needed.
    pub async fn clipboard_write(&self, text: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("clipboard_write requires Chromium mode".into()))?
            .clipboard_write(text)
            .await
    }

    // ── CSS override (f35) ──────────────────────────────────────

    /// Inject a `<style>` tag into the page and return its generated ID (Chromium only).
    ///
    /// The returned ID can later be passed to `remove_css` to delete the tag.
    pub async fn inject_css(&self, css: &str) -> Result<String> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("inject_css requires Chromium mode".into()))?
            .inject_css(css)
            .await
    }

    /// Remove a previously injected `<style>` tag by its ID (Chromium only).
    pub async fn remove_css(&self, id: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("remove_css requires Chromium mode".into()))?
            .remove_css(id)
            .await
    }

    // ── DrissionPage-style convenience API (Chromium only) ──

    /// Navigate to a URL and return `&self` for chaining (Chromium mode only).
    ///
    /// ```ignore
    /// page.goto("https://example.com").await?.click_ele("#btn").await?;
    /// ```
    pub async fn goto(&self, url: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("goto requires Chromium mode".into()))?
            .goto(url)
            .await?;
        Ok(self)
    }

    /// Type text into the first element matching `selector` — wait + fill in one step (Chromium only).
    ///
    /// ```ignore
    /// page.type_text("#search", "hello").await?.click_ele("#go").await?;
    /// ```
    pub async fn type_text(&self, selector: &str, text: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("type_text requires Chromium mode".into()))?
            .type_text(selector, text)
            .await?;
        Ok(self)
    }

    /// Click the first element matching `selector` — wait + click in one step (Chromium only).
    ///
    /// ```ignore
    /// page.click_ele("#submit").await?;
    /// ```
    pub async fn click_ele(&self, selector: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("click_ele requires Chromium mode".into()))?
            .click_ele(selector)
            .await?;
        Ok(self)
    }

    /// Get the visible text of the first element matching `selector` (Chromium only).
    ///
    /// ```ignore
    /// let label = page.get_text("#result").await?;
    /// ```
    pub async fn get_text(&self, selector: &str) -> Result<String> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("get_text requires Chromium mode".into()))?
            .get_text(selector)
            .await
    }

    /// Get an attribute value from the first element matching `selector` (Chromium only).
    ///
    /// ```ignore
    /// let href = page.get_attr("#link", "href").await?;
    /// ```
    pub async fn get_attr(&self, selector: &str, attr: &str) -> Result<Option<String>> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("get_attr requires Chromium mode".into()))?
            .get_attr(selector, attr)
            .await
    }

    /// Wait until the current URL contains `expected_url` (Chromium only).
    ///
    /// ```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<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_for_navigation requires Chromium mode".into()))?
            .wait_for_navigation(expected_url, timeout)
            .await
    }

    /// Scroll the page by a relative offset in pixels (Chromium only).
    ///
    /// ```ignore
    /// page.scroll_by(0, 500).await?; // scroll down 500px
    /// ```
    pub async fn scroll_by(&self, x: i64, y: i64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll_by requires Chromium mode".into()))?
            .scroll_by(x, y)
            .await
    }

    /// Type text character-by-character to simulate realistic keyboard input (Chromium only).
    ///
    /// ```ignore
    /// page.keys("hello").await?;
    /// ```
    pub async fn keys(&self, text: &str) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("keys requires Chromium mode".into()))?
            .keys(text)
            .await
    }

    // ── DrissionPage-style convenience aliases & helpers ───

    /// Alias for [`url()`](Self::url) — DrissionPage uses `current_url`.
    pub async fn current_url(&self) -> Result<String> {
        self.url().await
    }

    /// Alias for [`title()`](Self::title) — DrissionPage uses `current_title`.
    pub async fn current_title(&self) -> Result<String> {
        self.title().await
    }

    /// Alias for [`html()`](Self::html) — DrissionPage uses `page_source`.
    pub async fn page_source(&self) -> Result<String> {
        self.html().await
    }

    /// Wait for the page URL to **exactly match** `expected` (Chromium only).
    pub async fn wait_url_is(&self, expected: &str, timeout_secs: u64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_url_is requires Chromium mode".into()))?
            .wait_url_is(expected, timeout_secs)
            .await
    }

    /// Wait for the page title to **exactly match** `expected` (Chromium only).
    pub async fn wait_title_is(&self, expected: &str, timeout_secs: u64) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("wait_title_is requires Chromium mode".into()))?
            .wait_title_is(expected, timeout_secs)
            .await
    }

    /// Re-locate an element in the live DOM using its original locator (Chromium only).
    pub async fn refresh_ele(&self, el: &Element) -> Result<Element> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("refresh_ele requires Chromium mode".into()))?
            .refresh_ele(el)
            .await
    }

    /// Type text into the first element matching `selector` in **append** mode (Chromium only).
    ///
    /// Unlike [`type_text`](Self::type_text) which clears the field first, this appends.
    /// Returns `&self` for chaining.
    pub async fn input_text(&self, selector: &str, text: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("input_text requires Chromium mode".into()))?
            .input_text(selector, text)
            .await?;
        Ok(self)
    }

    /// Hover over the first element matching `selector` — wait + hover (Chromium only).
    pub async fn hover_ele(&self, selector: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("hover_ele requires Chromium mode".into()))?
            .hover_ele(selector)
            .await?;
        Ok(self)
    }

    /// Scroll the first element matching `selector` into view — wait + scroll (Chromium only).
    pub async fn scroll_to_ele(&self, selector: &str) -> Result<&WebPage> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("scroll_to_ele requires Chromium mode".into()))?
            .scroll_to_ele(selector)
            .await?;
        Ok(self)
    }

    /// Quick check: does at least one element matching `selector` exist? (Chromium only)
    ///
    /// Returns `false` in Session mode. Never throws.
    pub async fn exists(&self, selector: &str) -> bool {
        match self.chromium.as_ref() {
            Some(c) => c.exists(selector).await,
            None => false,
        }
    }

    /// Count how many elements currently match `selector` (Chromium only).
    ///
    /// Returns `0` in Session mode or when the selector is invalid.
    pub async fn count(&self, selector: &str) -> usize {
        match self.chromium.as_ref() {
            Some(c) => c.count(selector).await,
            None => 0,
        }
    }

    /// Find the first element matching `selector`, or `None` if absent (Chromium only).
    ///
    /// Returns `None` in Session mode.
    pub async fn ele_or_none(&self, selector: &str) -> Option<Element> {
        match self.chromium.as_ref() {
            Some(c) => c.ele_or_none(selector).await,
            None => None,
        }
    }

    // ── Load strategy ────────────────────────────────────────

    /// Set the page load strategy (Chromium only).
    ///
    /// 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) {
        if let Some(c) = self.chromium.as_mut() {
            c.set_load_strategy(strategy);
        }
    }

    /// Get the current load strategy (Chromium only).
    ///
    /// Returns `"normal"`, `"eager"`, or `"none"`.
    pub fn load_strategy(&self) -> Option<&str> {
        self.chromium.as_ref().map(|c| c.load_strategy())
    }

    // ── Window management ─────────────────────────────────────

    /// Get the current browser window's bounds as `(left, top, width, height)` (Chromium only).
    pub async fn get_window_bounds(&self) -> Result<(i32, i32, u32, u32)> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("get_window_bounds requires Chromium mode".into()))?
            .get_window_bounds()
            .await
    }

    /// Set the window position (top-left corner) (Chromium only).
    pub async fn set_window_position(&self, left: i32, top: i32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_window_position requires Chromium mode".into()))?
            .set_window_position(left, top)
            .await
    }

    /// Set the window size (width × height) (Chromium only).
    pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("set_window_size requires Chromium mode".into()))?
            .set_window_size(width, height)
            .await
    }

    /// Minimize the browser window (Chromium only).
    pub async fn minimize(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("minimize requires Chromium mode".into()))?
            .minimize()
            .await
    }

    /// Maximize the browser window (Chromium only).
    pub async fn maximize(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("maximize requires Chromium mode".into()))?
            .maximize()
            .await
    }

    /// Set the browser window to fullscreen (Chromium only).
    pub async fn fullscreen(&self) -> Result<()> {
        self.chromium
            .as_ref()
            .ok_or_else(|| Error::Browser("fullscreen requires Chromium mode".into()))?
            .fullscreen()
            .await
    }
}