-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathbrowser.rs
More file actions
1238 lines (1093 loc) · 39.2 KB
/
browser.rs
File metadata and controls
1238 lines (1093 loc) · 39.2 KB
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
use serde_json::{json, Value};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::Mutex;
use super::cdp::chrome::{
auto_connect_cdp, discover_cdp_url, launch_chrome, ChromeProcess, LaunchOptions,
};
use super::cdp::client::CdpClient;
use super::cdp::lightpanda::{launch_lightpanda, LightpandaLaunchOptions, LightpandaProcess};
use super::cdp::types::*;
// ---------------------------------------------------------------------------
// Launch validation
// ---------------------------------------------------------------------------
/// Validates launch/connect options for incompatible combinations.
/// Returns `Ok(())` if valid, or `Err(msg)` with a user-friendly error.
pub fn validate_launch_options(
extensions: Option<&[String]>,
has_cdp: bool,
profile: Option<&str>,
storage_state: Option<&str>,
allow_file_access: bool,
executable_path: Option<&str>,
) -> Result<(), String> {
let has_extensions = extensions.map(|e| !e.is_empty()).unwrap_or(false);
if has_extensions && has_cdp {
return Err(
"Cannot use extensions with cdp_url (extensions require local browser launch)"
.to_string(),
);
}
if profile.is_some() && has_cdp {
return Err(
"Cannot use profile with cdp_url (profile requires local browser launch)".to_string(),
);
}
if storage_state.is_some() && profile.is_some() {
return Err("Cannot use storage_state with profile".to_string());
}
if storage_state.is_some() && has_extensions {
return Err("Cannot use storage_state with extensions".to_string());
}
if allow_file_access {
if let Some(path) = executable_path {
let lower = path.to_lowercase();
if lower.contains("firefox") || lower.contains("webkit") || lower.contains("safari") {
return Err(
"allow_file_access is not supported with non-Chromium browsers".to_string(),
);
}
}
}
Ok(())
}
/// Validates that Chrome-only options are not used with Lightpanda.
fn validate_lightpanda_options(options: &LaunchOptions) -> Result<(), String> {
if options
.extensions
.as_ref()
.map(|e| !e.is_empty())
.unwrap_or(false)
{
return Err("Extensions are not supported with Lightpanda".to_string());
}
if options.profile.is_some() {
return Err("Profiles are not supported with Lightpanda".to_string());
}
if options.storage_state.is_some() {
return Err("Storage state is not supported with Lightpanda".to_string());
}
if options.allow_file_access {
return Err("File access is not supported with Lightpanda".to_string());
}
if !options.headless {
return Err("Headed mode is not supported with Lightpanda (headless only)".to_string());
}
if !options.args.is_empty() {
return Err(
"Custom Chrome arguments (--args) are not supported with Lightpanda".to_string(),
);
}
Ok(())
}
/// Converts common error messages into AI-friendly, actionable descriptions.
pub fn to_ai_friendly_error(error: &str) -> String {
let lower = error.to_lowercase();
if lower.contains("strict mode violation") {
return "Element matched multiple results. Use a more specific selector.".to_string();
}
if lower.contains("element is not visible") {
return "Element exists but is not visible. Wait for it to become visible or scroll it into view."
.to_string();
}
if lower.contains("intercept") {
return "Another element is covering the target element. Try scrolling or closing overlays."
.to_string();
}
if lower.contains("timeout") {
return "Operation timed out. The page may still be loading or the element may not exist."
.to_string();
}
if lower.contains("not found") || lower.contains("no element") {
return "Element not found. Verify the selector is correct and the element exists in the DOM."
.to_string();
}
error.to_string()
}
#[derive(Debug, Clone)]
pub struct PageInfo {
pub target_id: String,
pub session_id: String,
pub url: String,
pub title: String,
pub target_type: String, // "page" or "webview"
}
#[derive(Debug, Clone, Copy)]
pub enum WaitUntil {
Load,
DomContentLoaded,
NetworkIdle,
}
impl WaitUntil {
pub fn from_str(s: &str) -> Self {
match s {
"domcontentloaded" => Self::DomContentLoaded,
"networkidle" => Self::NetworkIdle,
_ => Self::Load,
}
}
}
pub enum BrowserProcess {
Chrome(ChromeProcess),
Lightpanda(LightpandaProcess),
}
impl BrowserProcess {
pub fn kill(&mut self) {
match self {
BrowserProcess::Chrome(p) => p.kill(),
BrowserProcess::Lightpanda(p) => p.kill(),
}
}
pub fn wait_or_kill(&mut self, timeout: std::time::Duration) {
match self {
BrowserProcess::Chrome(p) => p.wait_or_kill(timeout),
BrowserProcess::Lightpanda(p) => p.kill(),
}
}
}
pub struct BrowserManager {
pub client: CdpClient,
browser_process: Option<BrowserProcess>,
pages: Vec<PageInfo>,
active_page_index: usize,
default_timeout_ms: u64,
}
impl BrowserManager {
pub async fn launch(options: LaunchOptions, engine: Option<&str>) -> Result<Self, String> {
let engine = engine.unwrap_or("chrome");
match engine {
"chrome" => {
validate_launch_options(
options.extensions.as_deref(),
false,
options.profile.as_deref(),
options.storage_state.as_deref(),
options.allow_file_access,
options.executable_path.as_deref(),
)?;
}
"lightpanda" => {
validate_lightpanda_options(&options)?;
}
_ => {
return Err(format!(
"Unknown engine '{}'. Supported engines: chrome, lightpanda",
engine
));
}
}
let ignore_https_errors = options.ignore_https_errors;
let user_agent = options.user_agent.clone();
let color_scheme = options.color_scheme.clone();
let download_path = options.download_path.clone();
let (ws_url, process) = match engine {
"lightpanda" => {
let lp_options = LightpandaLaunchOptions {
executable_path: options.executable_path.clone(),
proxy: options.proxy.clone(),
port: None,
};
let lp = tokio::task::spawn_blocking(move || launch_lightpanda(&lp_options))
.await
.map_err(|e| format!("Lightpanda launch task failed: {}", e))??;
let url = lp.ws_url.clone();
(url, BrowserProcess::Lightpanda(lp))
}
_ => {
let chrome = tokio::task::spawn_blocking(move || launch_chrome(&options))
.await
.map_err(|e| format!("Chrome launch task failed: {}", e))??;
let url = chrome.ws_url.clone();
(url, BrowserProcess::Chrome(chrome))
}
};
let client = CdpClient::connect(&ws_url).await?;
let mut manager = Self {
client,
browser_process: Some(process),
pages: Vec::new(),
active_page_index: 0,
default_timeout_ms: 25_000,
};
manager.discover_and_attach_targets().await?;
let session_id = manager.active_session_id()?.to_string();
if ignore_https_errors {
let _ = manager
.client
.send_command(
"Security.setIgnoreCertificateErrors",
Some(json!({ "ignore": true })),
Some(&session_id),
)
.await;
}
if let Some(ref ua) = user_agent {
let _ = manager
.client
.send_command(
"Emulation.setUserAgentOverride",
Some(json!({ "userAgent": ua })),
Some(&session_id),
)
.await;
}
if let Some(ref scheme) = color_scheme {
let _ = manager
.client
.send_command(
"Emulation.setEmulatedMedia",
Some(json!({ "features": [{ "name": "prefers-color-scheme", "value": scheme }] })),
Some(&session_id),
)
.await;
}
if let Some(ref path) = download_path {
let _ = manager
.client
.send_command(
"Browser.setDownloadBehavior",
Some(json!({ "behavior": "allow", "downloadPath": path })),
None,
)
.await;
}
Ok(manager)
}
pub async fn connect_cdp(url: &str) -> Result<Self, String> {
let ws_url = resolve_cdp_url(url).await?;
let client = CdpClient::connect(&ws_url).await?;
let mut manager = Self {
client,
browser_process: None,
pages: Vec::new(),
active_page_index: 0,
default_timeout_ms: 10_000,
};
manager.discover_and_attach_targets().await?;
Ok(manager)
}
pub async fn connect_auto() -> Result<Self, String> {
let ws_url = auto_connect_cdp().await?;
Self::connect_cdp(&ws_url).await
}
async fn discover_and_attach_targets(&mut self) -> Result<(), String> {
self.client
.send_command_typed::<_, Value>(
"Target.setDiscoverTargets",
&SetDiscoverTargetsParams { discover: true },
None,
)
.await?;
let result: GetTargetsResult = self
.client
.send_command_typed("Target.getTargets", &json!({}), None)
.await?;
let page_targets: Vec<TargetInfo> = result
.target_infos
.into_iter()
.filter(|t| {
(t.target_type == "page" || t.target_type == "webview") && !t.url.is_empty()
})
.collect();
if page_targets.is_empty() {
// Create a new tab
let result: CreateTargetResult = self
.client
.send_command_typed(
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
},
None,
)
.await?;
let attach_result: AttachToTargetResult = self
.client
.send_command_typed(
"Target.attachToTarget",
&AttachToTargetParams {
target_id: result.target_id.clone(),
flatten: true,
},
None,
)
.await?;
self.pages.push(PageInfo {
target_id: result.target_id,
session_id: attach_result.session_id.clone(),
url: "about:blank".to_string(),
title: String::new(),
target_type: "page".to_string(),
});
self.active_page_index = 0;
self.enable_domains(&attach_result.session_id).await?;
} else {
for target in &page_targets {
let attach_result: AttachToTargetResult = self
.client
.send_command_typed(
"Target.attachToTarget",
&AttachToTargetParams {
target_id: target.target_id.clone(),
flatten: true,
},
None,
)
.await?;
self.pages.push(PageInfo {
target_id: target.target_id.clone(),
session_id: attach_result.session_id.clone(),
url: target.url.clone(),
title: target.title.clone(),
target_type: target.target_type.clone(),
});
}
self.active_page_index = 0;
let session_id = self.pages[0].session_id.clone();
self.enable_domains(&session_id).await?;
}
Ok(())
}
pub async fn enable_domains_pub(&self, session_id: &str) -> Result<(), String> {
self.enable_domains(session_id).await
}
async fn enable_domains(&self, session_id: &str) -> Result<(), String> {
self.client
.send_command_no_params("Page.enable", Some(session_id))
.await?;
self.client
.send_command_no_params("Runtime.enable", Some(session_id))
.await?;
self.client
.send_command_no_params("Network.enable", Some(session_id))
.await?;
Ok(())
}
pub fn active_session_id(&self) -> Result<&str, String> {
self.pages
.get(self.active_page_index)
.map(|p| p.session_id.as_str())
.ok_or_else(|| "No active page".to_string())
}
pub async fn navigate(&mut self, url: &str, wait_until: WaitUntil) -> Result<Value, String> {
let session_id = self.active_session_id()?.to_string();
let nav_result: PageNavigateResult = self
.client
.send_command_typed(
"Page.navigate",
&PageNavigateParams {
url: url.to_string(),
referrer: None,
},
Some(&session_id),
)
.await?;
if let Some(ref error_text) = nav_result.error_text {
return Err(format!("Navigation failed: {}", error_text));
}
self.wait_for_lifecycle(wait_until, &session_id).await?;
let page_url = self.get_url().await.unwrap_or_else(|_| url.to_string());
let title = self.get_title().await.unwrap_or_default();
if let Some(page) = self.pages.get_mut(self.active_page_index) {
page.url = page_url.clone();
page.title = title.clone();
}
Ok(json!({ "url": page_url, "title": title }))
}
async fn wait_for_lifecycle(
&self,
wait_until: WaitUntil,
session_id: &str,
) -> Result<(), String> {
let event_name = match wait_until {
WaitUntil::Load => "Page.loadEventFired",
WaitUntil::DomContentLoaded => "Page.domContentEventFired",
WaitUntil::NetworkIdle => return self.wait_for_network_idle(session_id).await,
};
let mut rx = self.client.subscribe();
let timeout = tokio::time::Duration::from_millis(self.default_timeout_ms);
tokio::time::timeout(timeout, async {
while let Ok(event) = rx.recv().await {
if event.method == event_name && event.session_id.as_deref() == Some(session_id) {
return Ok(());
}
}
Err("Event stream closed".to_string())
})
.await
.map_err(|_| format!("Timeout waiting for {}", event_name))?
}
async fn wait_for_network_idle(&self, session_id: &str) -> Result<(), String> {
let mut rx = self.client.subscribe();
let pending = Arc::new(Mutex::new(HashSet::<String>::new()));
let timeout = tokio::time::Duration::from_millis(self.default_timeout_ms);
tokio::time::timeout(timeout, async {
let mut idle_start: Option<tokio::time::Instant> = None;
loop {
let recv_result =
tokio::time::timeout(tokio::time::Duration::from_millis(600), rx.recv()).await;
match recv_result {
Ok(Ok(event)) if event.session_id.as_deref() == Some(session_id) => {
let mut p = pending.lock().await;
match event.method.as_str() {
"Network.requestWillBeSent" => {
if let Some(id) =
event.params.get("requestId").and_then(|v| v.as_str())
{
p.insert(id.to_string());
idle_start = None;
}
}
"Network.loadingFinished" | "Network.loadingFailed" => {
if let Some(id) =
event.params.get("requestId").and_then(|v| v.as_str())
{
p.remove(id);
if p.is_empty() {
idle_start = Some(tokio::time::Instant::now());
}
}
}
"Page.loadEventFired" => {
if p.is_empty() {
idle_start = Some(tokio::time::Instant::now());
}
}
_ => {}
}
}
Ok(Ok(_)) => {}
Ok(Err(_)) => break,
Err(_) => {
// Timeout on recv -- check if idle long enough
let p = pending.lock().await;
if p.is_empty() {
return Ok(());
}
}
}
if let Some(start) = idle_start {
if start.elapsed() >= tokio::time::Duration::from_millis(500) {
return Ok(());
}
}
}
Ok(())
})
.await
.map_err(|_| "Timeout waiting for networkidle".to_string())?
}
pub async fn get_url(&self) -> Result<String, String> {
let result = self.evaluate_simple("location.href").await?;
Ok(result.as_str().unwrap_or("").to_string())
}
pub async fn get_title(&self) -> Result<String, String> {
let result = self.evaluate_simple("document.title").await?;
Ok(result.as_str().unwrap_or("").to_string())
}
pub async fn get_content(&self) -> Result<String, String> {
let result = self
.evaluate_simple("document.documentElement.outerHTML")
.await?;
Ok(result.as_str().unwrap_or("").to_string())
}
pub async fn evaluate(&self, script: &str, _args: Option<Value>) -> Result<Value, String> {
let session_id = self.active_session_id()?.to_string();
let result: EvaluateResult = self
.client
.send_command_typed(
"Runtime.evaluate",
&EvaluateParams {
expression: script.to_string(),
return_by_value: Some(true),
await_promise: Some(true),
},
Some(&session_id),
)
.await?;
if let Some(ref details) = result.exception_details {
let msg = details
.exception
.as_ref()
.and_then(|e| e.description.as_deref())
.unwrap_or(&details.text);
return Err(format!("Evaluation error: {}", msg));
}
Ok(result.result.value.unwrap_or(Value::Null))
}
async fn evaluate_simple(&self, expression: &str) -> Result<Value, String> {
self.evaluate(expression, None).await
}
pub async fn wait_for_lifecycle_external(
&self,
wait_until: WaitUntil,
session_id: &str,
) -> Result<(), String> {
self.wait_for_lifecycle(wait_until, session_id).await
}
pub async fn close(&mut self) -> Result<(), String> {
let _ = self
.client
.send_command_no_params("Browser.close", None)
.await;
if let Some(mut process) = self.browser_process.take() {
let timeout = std::time::Duration::from_secs(5);
let _ = tokio::task::spawn_blocking(move || {
process.wait_or_kill(timeout);
})
.await;
}
Ok(())
}
pub fn has_pages(&self) -> bool {
!self.pages.is_empty()
}
/// Checks if the CDP connection is alive by sending a simple command.
/// Returns false if the command times out or fails.
pub async fn is_connection_alive(&self) -> bool {
let timeout = tokio::time::Duration::from_secs(3);
let result = tokio::time::timeout(
timeout,
self.client
.send_command_no_params("Browser.getVersion", None),
)
.await;
match result {
Ok(Ok(_)) => true,
Ok(Err(_)) | Err(_) => false,
}
}
/// Returns true if this manager was connected via CDP (as opposed to local launch).
pub fn is_cdp_connection(&self) -> bool {
self.browser_process.is_none()
}
/// Ensures the browser has at least one page. If `pages` is empty, creates a new
/// about:blank page and attaches to it.
pub async fn ensure_page(&mut self) -> Result<(), String> {
if !self.pages.is_empty() {
return Ok(());
}
let result: CreateTargetResult = self
.client
.send_command_typed(
"Target.createTarget",
&CreateTargetParams {
url: "about:blank".to_string(),
},
None,
)
.await?;
let attach_result: AttachToTargetResult = self
.client
.send_command_typed(
"Target.attachToTarget",
&AttachToTargetParams {
target_id: result.target_id.clone(),
flatten: true,
},
None,
)
.await?;
self.pages.push(PageInfo {
target_id: result.target_id,
session_id: attach_result.session_id.clone(),
url: "about:blank".to_string(),
title: String::new(),
target_type: "page".to_string(),
});
self.active_page_index = 0;
self.enable_domains(&attach_result.session_id).await?;
Ok(())
}
// -----------------------------------------------------------------------
// Tab management
// -----------------------------------------------------------------------
/// Checks if `active_page_index` is still valid and adjusts it if not
/// (e.g., after a tab was closed).
pub fn update_active_page_if_needed(&mut self) {
if self.pages.is_empty() {
self.active_page_index = 0;
return;
}
if self.active_page_index >= self.pages.len() {
self.active_page_index = self.pages.len() - 1;
}
}
pub fn tab_list(&self) -> Vec<Value> {
self.pages
.iter()
.enumerate()
.map(|(i, p)| {
json!({
"index": i,
"title": p.title,
"url": p.url,
"type": p.target_type,
"active": i == self.active_page_index,
})
})
.collect()
}
pub async fn tab_new(&mut self, url: Option<&str>) -> Result<Value, String> {
let target_url = url.unwrap_or("about:blank");
let result: CreateTargetResult = self
.client
.send_command_typed(
"Target.createTarget",
&CreateTargetParams {
url: target_url.to_string(),
},
None,
)
.await?;
let attach: AttachToTargetResult = self
.client
.send_command_typed(
"Target.attachToTarget",
&AttachToTargetParams {
target_id: result.target_id.clone(),
flatten: true,
},
None,
)
.await?;
self.enable_domains(&attach.session_id).await?;
let index = self.pages.len();
self.pages.push(PageInfo {
target_id: result.target_id,
session_id: attach.session_id,
url: target_url.to_string(),
title: String::new(),
target_type: "page".to_string(),
});
self.active_page_index = index;
Ok(json!({ "index": index, "url": target_url }))
}
pub async fn tab_switch(&mut self, index: usize) -> Result<Value, String> {
if index >= self.pages.len() {
return Err(format!(
"Tab index {} out of range (0-{})",
index,
self.pages.len().saturating_sub(1)
));
}
self.active_page_index = index;
let session_id = self.pages[index].session_id.clone();
self.enable_domains(&session_id).await?;
// Bring tab to front
let _ = self
.client
.send_command("Page.bringToFront", None, Some(&session_id))
.await;
let url = self.get_url().await.unwrap_or_default();
let title = self.get_title().await.unwrap_or_default();
if let Some(page) = self.pages.get_mut(index) {
page.url = url.clone();
page.title = title.clone();
}
Ok(json!({ "index": index, "url": url, "title": title }))
}
pub async fn tab_close(&mut self, index: Option<usize>) -> Result<Value, String> {
let target_index = index.unwrap_or(self.active_page_index);
if target_index >= self.pages.len() {
return Err(format!("Tab index {} out of range", target_index));
}
if self.pages.len() <= 1 {
return Err("Cannot close the last tab".to_string());
}
let page = self.pages.remove(target_index);
let _ = self
.client
.send_command_typed::<_, Value>(
"Target.closeTarget",
&CloseTargetParams {
target_id: page.target_id,
},
None,
)
.await;
if self.active_page_index >= self.pages.len() {
self.active_page_index = self.pages.len() - 1;
}
let session_id = self.pages[self.active_page_index].session_id.clone();
self.enable_domains(&session_id).await?;
Ok(json!({ "closed": target_index, "activeIndex": self.active_page_index }))
}
// -----------------------------------------------------------------------
// Emulation
// -----------------------------------------------------------------------
pub async fn set_viewport(
&self,
width: i32,
height: i32,
device_scale_factor: f64,
mobile: bool,
) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"Emulation.setDeviceMetricsOverride",
Some(json!({
"width": width,
"height": height,
"deviceScaleFactor": device_scale_factor,
"mobile": mobile,
})),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_user_agent(&self, user_agent: &str) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"Emulation.setUserAgentOverride",
Some(json!({ "userAgent": user_agent })),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn enable_webauthn(&self) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command_no_params("WebAuthn.enable", Some(session_id))
.await?;
Ok(())
}
pub async fn add_virtual_authenticator(&self) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"WebAuthn.addVirtualAuthenticator",
Some(json!({
"options": {
"protocol": "ctap2",
"transport": "internal",
"hasResidentKey": true,
"hasUserVerification": true,
"isUserVerified": true,
}
})),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_emulated_media(
&self,
media: Option<&str>,
features: Option<Vec<(String, String)>>,
) -> Result<(), String> {
let session_id = self.active_session_id()?;
let mut params = json!({});
if let Some(m) = media {
params["media"] = Value::String(m.to_string());
}
if let Some(feats) = features {
let features_arr: Vec<Value> = feats
.iter()
.map(|(name, value)| json!({ "name": name, "value": value }))
.collect();
params["features"] = Value::Array(features_arr);
}
self.client
.send_command("Emulation.setEmulatedMedia", Some(params), Some(session_id))
.await?;
Ok(())
}
pub async fn bring_to_front(&self) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command("Page.bringToFront", None, Some(session_id))
.await?;
Ok(())
}
pub async fn set_timezone(&self, timezone_id: &str) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"Emulation.setTimezoneOverride",
Some(json!({ "timezoneId": timezone_id })),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_locale(&self, locale: &str) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"Emulation.setLocaleOverride",
Some(json!({ "locale": locale })),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn set_geolocation(
&self,
latitude: f64,
longitude: f64,
accuracy: Option<f64>,
) -> Result<(), String> {
let session_id = self.active_session_id()?;
self.client
.send_command(
"Emulation.setGeolocationOverride",
Some(json!({
"latitude": latitude,
"longitude": longitude,
"accuracy": accuracy.unwrap_or(1.0),
})),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn grant_permissions(&self, permissions: &[String]) -> Result<(), String> {
self.client
.send_command(
"Browser.grantPermissions",
Some(json!({ "permissions": permissions })),
None,
)
.await?;
Ok(())
}
pub async fn handle_dialog(
&self,
accept: bool,
prompt_text: Option<&str>,
) -> Result<(), String> {
let session_id = self.active_session_id()?;
let mut params = json!({ "accept": accept });
if let Some(text) = prompt_text {
params["promptText"] = Value::String(text.to_string());
}
self.client
.send_command(
"Page.handleJavaScriptDialog",
Some(params),
Some(session_id),
)
.await?;
Ok(())
}
pub async fn upload_files(&self, selector: &str, files: &[String]) -> Result<(), String> {
let session_id = self.active_session_id()?;
let node_result = self
.client
.send_command(
"DOM.querySelector",
Some(json!({
"nodeId": 1,
"selector": selector,