1use hashbrown::HashMap;
2use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
3use std::future::Future;
4use std::time::Duration;
5use std::{
6 io,
7 path::{Path, PathBuf},
8};
9
10use futures::channel::mpsc::{channel, unbounded, Sender};
11use futures::channel::oneshot::channel as oneshot_channel;
12use futures::select;
13use futures::SinkExt;
14
15use crate::async_process::{self, Child, ExitStatus, Stdio};
16use crate::cmd::{to_command_response, CommandMessage};
17use crate::conn::Connection;
18use crate::detection::{self, DetectionOptions};
19use crate::error::{BrowserStderr, CdpError, Result};
20use crate::handler::browser::BrowserContext;
21use crate::handler::viewport::Viewport;
22use crate::handler::{Handler, HandlerConfig, HandlerMessage, REQUEST_TIMEOUT};
23use crate::listeners::{EventListenerRequest, EventStream};
24use crate::page::Page;
25use crate::utils;
26use chromiumoxide_cdp::cdp::browser_protocol::browser::{
27 BrowserContextId, CloseReturns, GetVersionParams, GetVersionReturns,
28};
29use chromiumoxide_cdp::cdp::browser_protocol::network::{Cookie, CookieParam};
30use chromiumoxide_cdp::cdp::browser_protocol::storage::{
31 ClearCookiesParams, GetCookiesParams, SetCookiesParams,
32};
33use chromiumoxide_cdp::cdp::browser_protocol::target::{
34 CreateBrowserContextParams, CreateTargetParams, DisposeBrowserContextParams,
35 GetBrowserContextsParams, GetBrowserContextsReturns, TargetId, TargetInfo,
36};
37use chromiumoxide_cdp::cdp::{CdpEventMessage, IntoEventKind};
38use chromiumoxide_types::*;
39use spider_network_blocker::intercept_manager::NetworkInterceptManager;
40
41pub const LAUNCH_TIMEOUT: u64 = 20_000;
43
44lazy_static::lazy_static! {
45 static ref REQUEST_CLIENT: reqwest::Client = reqwest::Client::builder()
47 .timeout(Duration::from_secs(60))
48 .default_headers({
49 let mut m = HeaderMap::new();
50
51 m.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
52
53 m
54 })
55 .tcp_keepalive(Some(Duration::from_secs(5)))
56 .pool_idle_timeout(Some(Duration::from_secs(60)))
57 .pool_max_idle_per_host(10)
58 .build()
59 .expect("client to build");
60}
61
62#[derive(Debug)]
64pub struct Browser {
65 pub(crate) sender: Sender<HandlerMessage>,
68 config: Option<BrowserConfig>,
70 child: Option<Child>,
72 debug_ws_url: String,
74 pub browser_context: BrowserContext,
76}
77
78#[derive(serde::Deserialize, Debug, Default)]
80pub struct BrowserConnection {
81 #[serde(rename = "Browser")]
82 pub browser: String,
84 #[serde(rename = "Protocol-Version")]
85 pub protocol_version: String,
87 #[serde(rename = "User-Agent")]
88 pub user_agent: String,
90 #[serde(rename = "V8-Version")]
91 pub v8_version: String,
93 #[serde(rename = "WebKit-Version")]
94 pub webkit_version: String,
96 #[serde(rename = "webSocketDebuggerUrl")]
97 pub web_socket_debugger_url: String,
99}
100
101impl Browser {
102 pub async fn connect(url: impl Into<String>) -> Result<(Self, Handler)> {
106 Self::connect_with_config(url, HandlerConfig::default()).await
107 }
108
109 pub async fn connect_with_config(
113 url: impl Into<String>,
114 config: HandlerConfig,
115 ) -> Result<(Self, Handler)> {
116 let mut debug_ws_url = url.into();
117
118 if debug_ws_url.starts_with("http") {
119 match REQUEST_CLIENT
120 .get(
121 if debug_ws_url.ends_with("/json/version")
122 || debug_ws_url.ends_with("/json/version/")
123 {
124 debug_ws_url.to_owned()
125 } else {
126 format!(
127 "{}{}json/version",
128 &debug_ws_url,
129 if debug_ws_url.ends_with('/') { "" } else { "/" }
130 )
131 },
132 )
133 .send()
134 .await
135 {
136 Ok(req) => {
137 if let Ok(b) = req.bytes().await {
138 if let Ok(connection) =
139 crate::serde_json::from_slice::<Box<BrowserConnection>>(&b)
140 {
141 if !connection.web_socket_debugger_url.is_empty() {
142 debug_ws_url = connection.web_socket_debugger_url;
143 }
144 }
145 }
146 }
147 Err(_) => return Err(CdpError::NoResponse),
148 }
149 }
150
151 let conn = Connection::<CdpEventMessage>::connect(&debug_ws_url).await?;
152
153 let (tx, rx) = channel(1000);
154
155 let handler_config = BrowserConfig {
156 ignore_https_errors: config.ignore_https_errors,
157 viewport: config.viewport.clone(),
158 request_timeout: config.request_timeout,
159 request_intercept: config.request_intercept,
160 cache_enabled: config.cache_enabled,
161 ignore_visuals: config.ignore_visuals,
162 ignore_stylesheets: config.ignore_stylesheets,
163 ignore_javascript: config.ignore_javascript,
164 ignore_analytics: config.ignore_analytics,
165 ignore_ads: config.ignore_ads,
166 extra_headers: config.extra_headers.clone(),
167 only_html: config.only_html,
168 service_worker_enabled: config.service_worker_enabled,
169 intercept_manager: config.intercept_manager,
170 max_bytes_allowed: config.max_bytes_allowed,
171 ..Default::default()
172 };
173
174 let fut = Handler::new(conn, rx, config);
175 let browser_context = fut.default_browser_context().clone();
176
177 let browser = Self {
178 sender: tx,
179 config: Some(handler_config),
180 child: None,
181 debug_ws_url,
182 browser_context,
183 };
184
185 Ok((browser, fut))
186 }
187
188 pub async fn launch(mut config: BrowserConfig) -> Result<(Self, Handler)> {
197 config.executable = utils::canonicalize_except_snap(config.executable).await?;
199
200 let mut child = config.launch()?;
202
203 async fn with_child(
208 config: &BrowserConfig,
209 child: &mut Child,
210 ) -> Result<(String, Connection<CdpEventMessage>)> {
211 let dur = config.launch_timeout;
212 let timeout_fut = Box::pin(tokio::time::sleep(dur));
213
214 let debug_ws_url = ws_url_from_output(child, timeout_fut).await?;
216 let conn = Connection::<CdpEventMessage>::connect(&debug_ws_url).await?;
217 Ok((debug_ws_url, conn))
218 }
219
220 let (debug_ws_url, conn) = match with_child(&config, &mut child).await {
221 Ok(conn) => conn,
222 Err(e) => {
223 if let Ok(Some(_)) = child.try_wait() {
225 } else {
227 child.kill().await.expect("`Browser::launch` failed but could not clean-up the child process (`kill`)");
229 child.wait().await.expect("`Browser::launch` failed but could not clean-up the child process (`wait`)");
230 }
231 return Err(e);
232 }
233 };
234
235 let (tx, rx) = channel(1000);
239
240 let handler_config = HandlerConfig {
241 ignore_https_errors: config.ignore_https_errors,
242 viewport: config.viewport.clone(),
243 context_ids: Vec::new(),
244 request_timeout: config.request_timeout,
245 request_intercept: config.request_intercept,
246 cache_enabled: config.cache_enabled,
247 ignore_visuals: config.ignore_visuals,
248 ignore_stylesheets: config.ignore_stylesheets,
249 ignore_javascript: config.ignore_javascript,
250 ignore_analytics: config.ignore_analytics,
251 ignore_ads: config.ignore_ads,
252 extra_headers: config.extra_headers.clone(),
253 only_html: config.only_html,
254 service_worker_enabled: config.service_worker_enabled,
255 created_first_target: false,
256 intercept_manager: config.intercept_manager,
257 max_bytes_allowed: config.max_bytes_allowed,
258 };
259
260 let fut = Handler::new(conn, rx, handler_config);
261 let browser_context = fut.default_browser_context().clone();
262
263 let browser = Self {
264 sender: tx,
265 config: Some(config),
266 child: Some(child),
267 debug_ws_url,
268 browser_context,
269 };
270
271 Ok((browser, fut))
272 }
273
274 pub async fn fetch_targets(&mut self) -> Result<Vec<TargetInfo>> {
284 let (tx, rx) = oneshot_channel();
285
286 self.sender
287 .clone()
288 .send(HandlerMessage::FetchTargets(tx))
289 .await?;
290
291 rx.await?
292 }
293
294 pub async fn close(&self) -> Result<CloseReturns> {
301 let (tx, rx) = oneshot_channel();
302
303 self.sender
304 .clone()
305 .send(HandlerMessage::CloseBrowser(tx))
306 .await?;
307
308 rx.await?
309 }
310
311 pub async fn wait(&mut self) -> io::Result<Option<ExitStatus>> {
320 if let Some(child) = self.child.as_mut() {
321 Ok(Some(child.wait().await?))
322 } else {
323 Ok(None)
324 }
325 }
326
327 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
336 if let Some(child) = self.child.as_mut() {
337 child.try_wait()
338 } else {
339 Ok(None)
340 }
341 }
342
343 pub fn get_mut_child(&mut self) -> Option<&mut Child> {
354 self.child.as_mut()
355 }
356
357 pub fn has_child(&self) -> bool {
359 self.child.is_some()
360 }
361
362 pub async fn kill(&mut self) -> Option<io::Result<()>> {
373 match self.child.as_mut() {
374 Some(child) => Some(child.kill().await),
375 None => None,
376 }
377 }
378
379 pub async fn start_incognito_context(&mut self) -> Result<&mut Self> {
385 if !self.is_incognito_configured() {
386 let browser_context_id = self
387 .create_browser_context(CreateBrowserContextParams::default())
388 .await?;
389 self.browser_context = BrowserContext::from(browser_context_id);
390 self.sender
391 .clone()
392 .send(HandlerMessage::InsertContext(self.browser_context.clone()))
393 .await?;
394 }
395
396 Ok(self)
397 }
398
399 pub async fn quit_incognito_context_base(
405 &self,
406 browser_context_id: BrowserContextId,
407 ) -> Result<&Self> {
408 self.dispose_browser_context(browser_context_id.clone())
409 .await?;
410 self.sender
411 .clone()
412 .send(HandlerMessage::DisposeContext(BrowserContext::from(
413 browser_context_id,
414 )))
415 .await?;
416 Ok(self)
417 }
418
419 pub async fn quit_incognito_context(&mut self) -> Result<&mut Self> {
425 if let Some(id) = self.browser_context.take() {
426 let _ = self.quit_incognito_context_base(id).await;
427 }
428 Ok(self)
429 }
430
431 fn is_incognito_configured(&self) -> bool {
433 self.config
434 .as_ref()
435 .map(|c| c.incognito)
436 .unwrap_or_default()
437 }
438
439 pub fn websocket_address(&self) -> &String {
441 &self.debug_ws_url
442 }
443
444 pub fn is_incognito(&self) -> bool {
446 self.is_incognito_configured() || self.browser_context.is_incognito()
447 }
448
449 pub fn config(&self) -> Option<&BrowserConfig> {
451 self.config.as_ref()
452 }
453
454 pub async fn new_page(&self, params: impl Into<CreateTargetParams>) -> Result<Page> {
456 let (tx, rx) = oneshot_channel();
457 let mut params = params.into();
458
459 if let Some(id) = self.browser_context.id() {
460 if params.browser_context_id.is_none() {
461 params.browser_context_id = Some(id.clone());
462 }
463 }
464
465 let _ = self
466 .sender
467 .clone()
468 .send(HandlerMessage::CreatePage(params, tx))
469 .await;
470
471 rx.await?
472 }
473
474 pub async fn version(&self) -> Result<GetVersionReturns> {
476 Ok(self.execute(GetVersionParams::default()).await?.result)
477 }
478
479 pub async fn user_agent(&self) -> Result<String> {
481 Ok(self.version().await?.user_agent)
482 }
483
484 pub async fn execute<T: Command>(&self, cmd: T) -> Result<CommandResponse<T::Response>> {
486 let (tx, rx) = oneshot_channel();
487 let method = cmd.identifier();
488 let msg = CommandMessage::new(cmd, tx)?;
489
490 self.sender
491 .clone()
492 .send(HandlerMessage::Command(msg))
493 .await?;
494 let resp = rx.await??;
495 to_command_response::<T>(resp, method)
496 }
497
498 pub async fn pages(&self) -> Result<Vec<Page>> {
500 let (tx, rx) = oneshot_channel();
501 self.sender
502 .clone()
503 .send(HandlerMessage::GetPages(tx))
504 .await?;
505 Ok(rx.await?)
506 }
507
508 pub async fn get_page(&self, target_id: TargetId) -> Result<Page> {
510 let (tx, rx) = oneshot_channel();
511 self.sender
512 .clone()
513 .send(HandlerMessage::GetPage(target_id, tx))
514 .await?;
515 rx.await?.ok_or(CdpError::NotFound)
516 }
517
518 pub async fn event_listener<T: IntoEventKind>(&self) -> Result<EventStream<T>> {
520 let (tx, rx) = unbounded();
521 self.sender
522 .clone()
523 .send(HandlerMessage::AddEventListener(
524 EventListenerRequest::new::<T>(tx),
525 ))
526 .await?;
527
528 Ok(EventStream::new(rx))
529 }
530
531 pub async fn create_browser_context(
533 &mut self,
534 params: CreateBrowserContextParams,
535 ) -> Result<BrowserContextId> {
536 let response = self.execute(params).await?;
537 Ok(response.result.browser_context_id)
538 }
539
540 pub async fn get_browser_contexts(
542 &mut self,
543 params: GetBrowserContextsParams,
544 ) -> Result<GetBrowserContextsReturns> {
545 let response = self.execute(params).await?;
546 Ok(response.result)
547 }
548
549 pub async fn send_new_context(
551 &mut self,
552 browser_context_id: BrowserContextId,
553 ) -> Result<&Self> {
554 self.browser_context = BrowserContext::from(browser_context_id);
555 self.sender
556 .clone()
557 .send(HandlerMessage::InsertContext(self.browser_context.clone()))
558 .await?;
559 Ok(self)
560 }
561
562 pub async fn dispose_browser_context(
564 &self,
565 browser_context_id: impl Into<BrowserContextId>,
566 ) -> Result<&Self> {
567 self.execute(DisposeBrowserContextParams::new(browser_context_id))
568 .await?;
569
570 Ok(self)
571 }
572
573 pub async fn clear_cookies(&self) -> Result<&Self> {
575 self.execute(ClearCookiesParams::default()).await?;
576 Ok(self)
577 }
578
579 pub async fn get_cookies(&self) -> Result<Vec<Cookie>> {
581 let mut cmd = GetCookiesParams::default();
582
583 cmd.browser_context_id = self.browser_context.id.clone();
584
585 Ok(self.execute(cmd).await?.result.cookies)
586 }
587
588 pub async fn set_cookies(&self, mut cookies: Vec<CookieParam>) -> Result<&Self> {
590 for cookie in &mut cookies {
591 if let Some(url) = cookie.url.as_ref() {
592 crate::page::validate_cookie_url(url)?;
593 }
594 }
595
596 let mut cookies_param = SetCookiesParams::new(cookies);
597
598 cookies_param.browser_context_id = self.browser_context.id.clone();
599
600 self.execute(cookies_param).await?;
601 Ok(self)
602 }
603}
604
605impl Drop for Browser {
606 fn drop(&mut self) {
607 if let Some(child) = self.child.as_mut() {
608 if let Ok(Some(_)) = child.try_wait() {
609 } else {
611 tracing::warn!("Browser was not closed manually, it will be killed automatically in the background");
619 }
620 }
621 }
622}
623
624async fn ws_url_from_output(
634 child_process: &mut Child,
635 timeout_fut: impl Future<Output = ()> + Unpin,
636) -> Result<String> {
637 use futures::{AsyncBufReadExt, FutureExt};
638 let mut timeout_fut = timeout_fut.fuse();
639 let stderr = child_process.stderr.take().expect("no stderror");
640 let mut stderr_bytes = Vec::<u8>::new();
641 let mut exit_status_fut = Box::pin(child_process.wait()).fuse();
642 let mut buf = futures::io::BufReader::new(stderr);
643 loop {
644 select! {
645 _ = timeout_fut => return Err(CdpError::LaunchTimeout(BrowserStderr::new(stderr_bytes))),
646 exit_status = exit_status_fut => {
647 return Err(match exit_status {
648 Err(e) => CdpError::LaunchIo(e, BrowserStderr::new(stderr_bytes)),
649 Ok(exit_status) => CdpError::LaunchExit(exit_status, BrowserStderr::new(stderr_bytes)),
650 })
651 },
652 read_res = buf.read_until(b'\n', &mut stderr_bytes).fuse() => {
653 match read_res {
654 Err(e) => return Err(CdpError::LaunchIo(e, BrowserStderr::new(stderr_bytes))),
655 Ok(byte_count) => {
656 if byte_count == 0 {
657 let e = io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected end of stream");
658 return Err(CdpError::LaunchIo(e, BrowserStderr::new(stderr_bytes)));
659 }
660 let start_offset = stderr_bytes.len() - byte_count;
661 let new_bytes = &stderr_bytes[start_offset..];
662 match std::str::from_utf8(new_bytes) {
663 Err(_) => {
664 let e = io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8");
665 return Err(CdpError::LaunchIo(e, BrowserStderr::new(stderr_bytes)));
666 }
667 Ok(line) => {
668 if let Some((_, ws)) = line.rsplit_once("listening on ") {
669 if ws.starts_with("ws") && ws.contains("devtools/browser") {
670 return Ok(ws.trim().to_string());
671 }
672 }
673 }
674 }
675 }
676 }
677 }
678 }
679 }
680}
681
682#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
683pub enum HeadlessMode {
684 False,
686 #[default]
688 True,
689 New,
691}
692
693#[derive(Debug, Clone, Default)]
694pub struct BrowserConfig {
695 headless: HeadlessMode,
698 sandbox: bool,
700 window_size: Option<(u32, u32)>,
702 port: u16,
704 executable: std::path::PathBuf,
709
710 extensions: Vec<String>,
718
719 pub process_envs: Option<HashMap<String, String>>,
722
723 pub user_data_dir: Option<PathBuf>,
725
726 incognito: bool,
728
729 launch_timeout: Duration,
731
732 ignore_https_errors: bool,
734 pub viewport: Option<Viewport>,
735 request_timeout: Duration,
737
738 args: Vec<String>,
740
741 disable_default_args: bool,
743
744 pub request_intercept: bool,
746
747 pub cache_enabled: bool,
749 pub service_worker_enabled: bool,
752 pub ignore_visuals: bool,
755 pub ignore_stylesheets: bool,
758 pub ignore_javascript: bool,
761 pub ignore_analytics: bool,
763 pub ignore_ads: bool,
765 pub extra_headers: Option<std::collections::HashMap<String, String>>,
767 pub only_html: bool,
769 pub intercept_manager: NetworkInterceptManager,
771 pub max_bytes_allowed: Option<u64>,
773}
774
775#[derive(Debug, Clone)]
776pub struct BrowserConfigBuilder {
777 headless: HeadlessMode,
779 sandbox: bool,
781 window_size: Option<(u32, u32)>,
783 port: u16,
785 executable: Option<PathBuf>,
788 executation_detection: DetectionOptions,
790 extensions: Vec<String>,
792 process_envs: Option<HashMap<String, String>>,
794 user_data_dir: Option<PathBuf>,
796 incognito: bool,
798 launch_timeout: Duration,
800 ignore_https_errors: bool,
802 viewport: Option<Viewport>,
804 request_timeout: Duration,
806 args: Vec<String>,
808 disable_default_args: bool,
810 request_intercept: bool,
812 cache_enabled: bool,
814 service_worker_enabled: bool,
816 ignore_visuals: bool,
818 ignore_ads: bool,
820 ignore_javascript: bool,
822 ignore_stylesheets: bool,
824 ignore_analytics: bool,
826 only_html: bool,
828 extra_headers: Option<std::collections::HashMap<String, String>>,
830 intercept_manager: NetworkInterceptManager,
832 max_bytes_allowed: Option<u64>,
834}
835
836impl BrowserConfig {
837 pub fn builder() -> BrowserConfigBuilder {
839 BrowserConfigBuilder::default()
840 }
841
842 pub fn with_executable(path: impl AsRef<Path>) -> Self {
844 Self::builder()
845 .chrome_executable(path)
846 .build()
847 .expect("path to executable exist")
848 }
849}
850
851impl Default for BrowserConfigBuilder {
852 fn default() -> Self {
853 Self {
854 headless: HeadlessMode::True,
855 sandbox: true,
856 window_size: None,
857 port: 0,
858 executable: None,
859 executation_detection: DetectionOptions::default(),
860 extensions: Vec::new(),
861 process_envs: None,
862 user_data_dir: None,
863 incognito: false,
864 launch_timeout: Duration::from_millis(LAUNCH_TIMEOUT),
865 ignore_https_errors: true,
866 viewport: Some(Default::default()),
867 request_timeout: Duration::from_millis(REQUEST_TIMEOUT),
868 args: Vec::new(),
869 disable_default_args: false,
870 request_intercept: false,
871 cache_enabled: true,
872 ignore_visuals: false,
873 ignore_ads: false,
874 ignore_javascript: false,
875 ignore_analytics: false,
876 ignore_stylesheets: false,
877 only_html: false,
878 extra_headers: Default::default(),
879 service_worker_enabled: true,
880 intercept_manager: NetworkInterceptManager::Unknown,
881 max_bytes_allowed: None,
882 }
883 }
884}
885
886impl BrowserConfigBuilder {
887 pub fn window_size(mut self, width: u32, height: u32) -> Self {
889 self.window_size = Some((width, height));
890 self
891 }
892 pub fn no_sandbox(mut self) -> Self {
894 self.sandbox = false;
895 self
896 }
897 pub fn with_head(mut self) -> Self {
899 self.headless = HeadlessMode::False;
900 self
901 }
902 pub fn new_headless_mode(mut self) -> Self {
904 self.headless = HeadlessMode::New;
905 self
906 }
907 pub fn headless_mode(mut self, mode: HeadlessMode) -> Self {
909 self.headless = mode;
910 self
911 }
912 pub fn incognito(mut self) -> Self {
914 self.incognito = true;
915 self
916 }
917
918 pub fn respect_https_errors(mut self) -> Self {
919 self.ignore_https_errors = false;
920 self
921 }
922
923 pub fn port(mut self, port: u16) -> Self {
924 self.port = port;
925 self
926 }
927
928 pub fn with_max_bytes_allowed(mut self, max_bytes_allowed: Option<u64>) -> Self {
929 self.max_bytes_allowed = max_bytes_allowed;
930 self
931 }
932
933 pub fn launch_timeout(mut self, timeout: Duration) -> Self {
934 self.launch_timeout = timeout;
935 self
936 }
937
938 pub fn request_timeout(mut self, timeout: Duration) -> Self {
939 self.request_timeout = timeout;
940 self
941 }
942
943 pub fn viewport(mut self, viewport: impl Into<Option<Viewport>>) -> Self {
949 self.viewport = viewport.into();
950 self
951 }
952
953 pub fn user_data_dir(mut self, data_dir: impl AsRef<Path>) -> Self {
954 self.user_data_dir = Some(data_dir.as_ref().to_path_buf());
955 self
956 }
957
958 pub fn chrome_executable(mut self, path: impl AsRef<Path>) -> Self {
959 self.executable = Some(path.as_ref().to_path_buf());
960 self
961 }
962
963 pub fn chrome_detection(mut self, options: DetectionOptions) -> Self {
964 self.executation_detection = options;
965 self
966 }
967
968 pub fn extension(mut self, extension: impl Into<String>) -> Self {
969 self.extensions.push(extension.into());
970 self
971 }
972
973 pub fn extensions<I, S>(mut self, extensions: I) -> Self
974 where
975 I: IntoIterator<Item = S>,
976 S: Into<String>,
977 {
978 for ext in extensions {
979 self.extensions.push(ext.into());
980 }
981 self
982 }
983
984 pub fn env(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
985 self.process_envs
986 .get_or_insert(HashMap::new())
987 .insert(key.into(), val.into());
988 self
989 }
990
991 pub fn envs<I, K, V>(mut self, envs: I) -> Self
992 where
993 I: IntoIterator<Item = (K, V)>,
994 K: Into<String>,
995 V: Into<String>,
996 {
997 self.process_envs
998 .get_or_insert(HashMap::new())
999 .extend(envs.into_iter().map(|(k, v)| (k.into(), v.into())));
1000 self
1001 }
1002
1003 pub fn arg(mut self, arg: impl Into<String>) -> Self {
1004 self.args.push(arg.into());
1005 self
1006 }
1007
1008 pub fn args<I, S>(mut self, args: I) -> Self
1009 where
1010 I: IntoIterator<Item = S>,
1011 S: Into<String>,
1012 {
1013 for arg in args {
1014 self.args.push(arg.into());
1015 }
1016 self
1017 }
1018
1019 pub fn disable_default_args(mut self) -> Self {
1020 self.disable_default_args = true;
1021 self
1022 }
1023
1024 pub fn enable_request_intercept(mut self) -> Self {
1025 self.request_intercept = true;
1026 self
1027 }
1028
1029 pub fn disable_request_intercept(mut self) -> Self {
1030 self.request_intercept = false;
1031 self
1032 }
1033
1034 pub fn enable_cache(mut self) -> Self {
1035 self.cache_enabled = true;
1036 self
1037 }
1038
1039 pub fn disable_cache(mut self) -> Self {
1040 self.cache_enabled = false;
1041 self
1042 }
1043
1044 pub fn set_service_worker_enabled(mut self, bypass: bool) -> Self {
1045 self.service_worker_enabled = bypass;
1046 self
1047 }
1048
1049 pub fn set_extra_headers(
1050 mut self,
1051 headers: Option<std::collections::HashMap<String, String>>,
1052 ) -> Self {
1053 self.extra_headers = headers;
1054 self
1055 }
1056
1057 pub fn build(self) -> std::result::Result<BrowserConfig, String> {
1058 let executable = if let Some(e) = self.executable {
1059 e
1060 } else {
1061 detection::default_executable(self.executation_detection)?
1062 };
1063
1064 Ok(BrowserConfig {
1065 headless: self.headless,
1066 sandbox: self.sandbox,
1067 window_size: self.window_size,
1068 port: self.port,
1069 executable,
1070 extensions: self.extensions,
1071 process_envs: self.process_envs,
1072 user_data_dir: self.user_data_dir,
1073 incognito: self.incognito,
1074 launch_timeout: self.launch_timeout,
1075 ignore_https_errors: self.ignore_https_errors,
1076 viewport: self.viewport,
1077 request_timeout: self.request_timeout,
1078 args: self.args,
1079 disable_default_args: self.disable_default_args,
1080 request_intercept: self.request_intercept,
1081 cache_enabled: self.cache_enabled,
1082 ignore_visuals: self.ignore_visuals,
1083 ignore_ads: self.ignore_ads,
1084 ignore_javascript: self.ignore_javascript,
1085 ignore_analytics: self.ignore_analytics,
1086 ignore_stylesheets: self.ignore_stylesheets,
1087 extra_headers: self.extra_headers,
1088 only_html: self.only_html,
1089 intercept_manager: self.intercept_manager,
1090 service_worker_enabled: self.service_worker_enabled,
1091 max_bytes_allowed: self.max_bytes_allowed,
1092 })
1093 }
1094}
1095
1096impl BrowserConfig {
1097 pub fn launch(&self) -> io::Result<Child> {
1098 let mut cmd = async_process::Command::new(&self.executable);
1099
1100 if self.disable_default_args {
1101 cmd.args(&self.args);
1102 } else {
1103 cmd.args(DEFAULT_ARGS).args(&self.args);
1104 }
1105
1106 if !self
1107 .args
1108 .iter()
1109 .any(|arg| arg.contains("--remote-debugging-port="))
1110 {
1111 cmd.arg(format!("--remote-debugging-port={}", self.port));
1112 }
1113
1114 cmd.args(
1115 self.extensions
1116 .iter()
1117 .map(|e| format!("--load-extension={e}")),
1118 );
1119
1120 if let Some(ref user_data) = self.user_data_dir {
1121 cmd.arg(format!("--user-data-dir={}", user_data.display()));
1122 } else {
1123 cmd.arg(format!(
1127 "--user-data-dir={}",
1128 std::env::temp_dir().join("chromiumoxide-runner").display()
1129 ));
1130 }
1131
1132 if let Some((width, height)) = self.window_size {
1133 cmd.arg(format!("--window-size={width},{height}"));
1134 }
1135
1136 if !self.sandbox {
1137 cmd.args(["--no-sandbox", "--disable-setuid-sandbox"]);
1138 }
1139
1140 match self.headless {
1141 HeadlessMode::False => (),
1142 HeadlessMode::True => {
1143 cmd.args(["--headless", "--hide-scrollbars", "--mute-audio"]);
1144 }
1145 HeadlessMode::New => {
1146 cmd.args(["--headless=new", "--hide-scrollbars", "--mute-audio"]);
1147 }
1148 }
1149
1150 if self.incognito {
1151 cmd.arg("--incognito");
1152 }
1153
1154 if let Some(ref envs) = self.process_envs {
1155 cmd.envs(envs);
1156 }
1157 cmd.stderr(Stdio::piped()).spawn()
1158 }
1159}
1160
1161#[deprecated(note = "Use detection::default_executable instead")]
1170pub fn default_executable() -> Result<std::path::PathBuf, String> {
1171 let options = DetectionOptions {
1172 msedge: false,
1173 unstable: false,
1174 };
1175 detection::default_executable(options)
1176}
1177
1178static DEFAULT_ARGS: [&str; 26] = [
1181 "--disable-background-networking",
1182 "--enable-features=NetworkService,NetworkServiceInProcess",
1183 "--disable-background-timer-throttling",
1184 "--disable-backgrounding-occluded-windows",
1185 "--disable-breakpad",
1186 "--disable-client-side-phishing-detection",
1187 "--disable-component-extensions-with-background-pages",
1188 "--disable-default-apps",
1189 "--disable-dev-shm-usage",
1190 "--disable-extensions",
1191 "--disable-features=TranslateUI",
1192 "--disable-hang-monitor",
1193 "--disable-ipc-flooding-protection",
1194 "--disable-popup-blocking",
1195 "--disable-prompt-on-repost",
1196 "--disable-renderer-backgrounding",
1197 "--disable-sync",
1198 "--force-color-profile=srgb",
1199 "--metrics-recording-only",
1200 "--no-first-run",
1201 "--enable-automation",
1202 "--password-store=basic",
1203 "--use-mock-keychain",
1204 "--enable-blink-features=IdleDetection",
1205 "--lang=en_US",
1206 "--disable-blink-features=AutomationControlled",
1207];