chromiumoxide/
browser.rs

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
41/// Default `Browser::launch` timeout in MS
42pub const LAUNCH_TIMEOUT: u64 = 20_000;
43
44lazy_static::lazy_static! {
45    /// The request client to get the web socket url.
46    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/// A [`Browser`] is created when chromiumoxide connects to a Chromium instance.
63#[derive(Debug)]
64pub struct Browser {
65    /// The `Sender` to send messages to the connection handler that drives the
66    /// websocket
67    pub(crate) sender: Sender<HandlerMessage>,
68    /// How the spawned chromium instance was configured, if any
69    config: Option<BrowserConfig>,
70    /// The spawned chromium instance
71    child: Option<Child>,
72    /// The debug web socket url of the chromium instance
73    debug_ws_url: String,
74    /// The context of the browser
75    pub browser_context: BrowserContext,
76}
77
78/// Browser connection information.
79#[derive(serde::Deserialize, Debug, Default)]
80pub struct BrowserConnection {
81    #[serde(rename = "Browser")]
82    /// The browser name
83    pub browser: String,
84    #[serde(rename = "Protocol-Version")]
85    /// Browser version
86    pub protocol_version: String,
87    #[serde(rename = "User-Agent")]
88    /// User Agent used by default.
89    pub user_agent: String,
90    #[serde(rename = "V8-Version")]
91    /// The v8 engine version
92    pub v8_version: String,
93    #[serde(rename = "WebKit-Version")]
94    /// Webkit version
95    pub webkit_version: String,
96    #[serde(rename = "webSocketDebuggerUrl")]
97    /// Remote debugging address
98    pub web_socket_debugger_url: String,
99}
100
101impl Browser {
102    /// Connect to an already running chromium instance via the given URL.
103    ///
104    /// If the URL is a http(s) URL, it will first attempt to retrieve the Websocket URL from the `json/version` endpoint.
105    pub async fn connect(url: impl Into<String>) -> Result<(Self, Handler)> {
106        Self::connect_with_config(url, HandlerConfig::default()).await
107    }
108
109    // Connect to an already running chromium instance with a given `HandlerConfig`.
110    ///
111    /// If the URL is a http URL, it will first attempt to retrieve the Websocket URL from the `json/version` endpoint.
112    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    /// Launches a new instance of `chromium` in the background and attaches to
189    /// its debug web socket.
190    ///
191    /// This fails when no chromium executable could be detected.
192    ///
193    /// This fails if no web socket url could be detected from the child
194    /// processes stderr for more than the configured `launch_timeout`
195    /// (20 seconds by default).
196    pub async fn launch(mut config: BrowserConfig) -> Result<(Self, Handler)> {
197        // Canonalize paths to reduce issues with sandboxing
198        config.executable = utils::canonicalize_except_snap(config.executable).await?;
199
200        // Launch a new chromium instance
201        let mut child = config.launch()?;
202
203        /// Faillible initialization to run once the child process is created.
204        ///
205        /// All faillible calls must be executed inside this function. This ensures that all
206        /// errors are caught and that the child process is properly cleaned-up.
207        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            // extract the ws:
215            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                // An initialization error occurred, clean up the process
224                if let Ok(Some(_)) = child.try_wait() {
225                    // already exited, do nothing, may happen if the browser crashed
226                } else {
227                    // the process is still alive, kill it and wait for exit (avoid zombie processes)
228                    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        // Only infaillible calls are allowed after this point to avoid clean-up issues with the
236        // child process.
237
238        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    /// Request to fetch all existing browser targets.
275    ///
276    /// By default, only targets launched after the browser connection are tracked
277    /// when connecting to a existing browser instance with the devtools websocket url
278    /// This function fetches existing targets on the browser and adds them as pages internally
279    ///
280    /// The pages are not guaranteed to be ready as soon as the function returns
281    /// You should wait a few millis if you need to use a page
282    /// Returns [TargetInfo]
283    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    /// Request for the browser to close completely.
295    ///
296    /// If the browser was spawned by [`Browser::launch`], it is recommended to wait for the
297    /// spawned instance exit, to avoid "zombie" processes ([`Browser::wait`],
298    /// [`Browser::wait_sync`], [`Browser::try_wait`]).
299    /// [`Browser::drop`] waits automatically if needed.
300    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    /// Asynchronously wait for the spawned chromium instance to exit completely.
312    ///
313    /// The instance is spawned by [`Browser::launch`]. `wait` is usually called after
314    /// [`Browser::close`]. You can call this explicitly to collect the process and avoid
315    /// "zombie" processes.
316    ///
317    /// This call has no effect if this [`Browser`] did not spawn any chromium instance (e.g.
318    /// connected to an existing browser through [`Browser::connect`])
319    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    /// If the spawned chromium instance has completely exited, wait for it.
328    ///
329    /// The instance is spawned by [`Browser::launch`]. `try_wait` is usually called after
330    /// [`Browser::close`]. You can call this explicitly to collect the process and avoid
331    /// "zombie" processes.
332    ///
333    /// This call has no effect if this [`Browser`] did not spawn any chromium instance (e.g.
334    /// connected to an existing browser through [`Browser::connect`])
335    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    /// Get the spawned chromium instance
344    ///
345    /// The instance is spawned by [`Browser::launch`]. The result is a [`async_process::Child`]
346    /// value. It acts as a compat wrapper for an `async-std` or `tokio` child process.
347    ///
348    /// You may use [`async_process::Child::as_mut_inner`] to retrieve the concrete implementation
349    /// for the selected runtime.
350    ///
351    /// This call has no effect if this [`Browser`] did not spawn any chromium instance (e.g.
352    /// connected to an existing browser through [`Browser::connect`])
353    pub fn get_mut_child(&mut self) -> Option<&mut Child> {
354        self.child.as_mut()
355    }
356
357    /// Has a browser instance launched on system.
358    pub fn has_child(&self) -> bool {
359        self.child.is_some()
360    }
361
362    /// Forcibly kill the spawned chromium instance
363    ///
364    /// The instance is spawned by [`Browser::launch`]. `kill` will automatically wait for the child
365    /// process to exit to avoid "zombie" processes.
366    ///
367    /// This method is provided to help if the browser does not close by itself. You should prefer
368    /// to use [`Browser::close`].
369    ///
370    /// This call has no effect if this [`Browser`] did not spawn any chromium instance (e.g.
371    /// connected to an existing browser through [`Browser::connect`])
372    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    /// If not launched as incognito this creates a new incognito browser
380    /// context. After that this browser exists within the incognito session.
381    /// New pages created while being in incognito mode will also run in the
382    /// incognito context. Incognito contexts won't share cookies/cache with
383    /// other browser contexts.
384    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    /// If a incognito session was created with
400    /// `Browser::start_incognito_context` this disposes this context.
401    ///
402    /// # Note This will also dispose all pages that were running within the
403    /// incognito context.
404    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    /// If a incognito session was created with
420    /// `Browser::start_incognito_context` this disposes this context.
421    ///
422    /// # Note This will also dispose all pages that were running within the
423    /// incognito context.
424    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    /// Whether incognito mode was configured from the start
432    fn is_incognito_configured(&self) -> bool {
433        self.config
434            .as_ref()
435            .map(|c| c.incognito)
436            .unwrap_or_default()
437    }
438
439    /// Returns the address of the websocket this browser is attached to
440    pub fn websocket_address(&self) -> &String {
441        &self.debug_ws_url
442    }
443
444    /// Whether the BrowserContext is incognito.
445    pub fn is_incognito(&self) -> bool {
446        self.is_incognito_configured() || self.browser_context.is_incognito()
447    }
448
449    /// The config of the spawned chromium instance if any.
450    pub fn config(&self) -> Option<&BrowserConfig> {
451        self.config.as_ref()
452    }
453
454    /// Create a new browser page
455    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    /// Version information about the browser
475    pub async fn version(&self) -> Result<GetVersionReturns> {
476        Ok(self.execute(GetVersionParams::default()).await?.result)
477    }
478
479    /// Returns the user agent of the browser
480    pub async fn user_agent(&self) -> Result<String> {
481        Ok(self.version().await?.user_agent)
482    }
483
484    /// Call a browser method.
485    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    /// Return all of the pages of the browser
499    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    /// Return page of given target_id
509    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    /// Set listener for browser event
519    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    /// Creates a new empty browser context.
532    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    /// Returns all browser contexts created with Target.createBrowserContext method.
541    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    /// Send a new empty browser context.
550    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    /// Deletes a browser context.
563    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    /// Clears cookies.
574    pub async fn clear_cookies(&self) -> Result<&Self> {
575        self.execute(ClearCookiesParams::default()).await?;
576        Ok(self)
577    }
578
579    /// Returns all browser cookies.
580    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    /// Sets given cookies.
589    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                // Already exited, do nothing. Usually occurs after using the method close or kill.
610            } else {
611                // We set the `kill_on_drop` property for the child process, so no need to explicitely
612                // kill it here. It can't really be done anyway since the method is async.
613                //
614                // On Unix, the process will be reaped in the background by the runtime automatically
615                // so it won't leave any resources locked. It is, however, a better practice for the user to
616                // do it himself since the runtime doesn't provide garantees as to when the reap occurs, so we
617                // warn him here.
618                tracing::warn!("Browser was not closed manually, it will be killed automatically in the background");
619            }
620        }
621    }
622}
623
624/// Resolve devtools WebSocket URL from the provided browser process
625///
626/// If an error occurs, it returns the browser's stderr output.
627///
628/// The URL resolution fails if:
629/// - [`CdpError::LaunchTimeout`]: `timeout_fut` completes, this corresponds to a timeout
630/// - [`CdpError::LaunchExit`]: the browser process exits (or is killed)
631/// - [`CdpError::LaunchIo`]: an input/output error occurs when await the process exit or reading
632///   the browser's stderr: end of stream, invalid UTF-8, other
633async 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    /// The "headful" mode.
685    False,
686    /// The old headless mode.
687    #[default]
688    True,
689    /// The new headless mode. See also: https://developer.chrome.com/docs/chromium/new-headless
690    New,
691}
692
693#[derive(Debug, Clone, Default)]
694pub struct BrowserConfig {
695    /// Determines whether to run headless version of the browser. Defaults to
696    /// true.
697    headless: HeadlessMode,
698    /// Determines whether to run the browser with a sandbox.
699    sandbox: bool,
700    /// Launch the browser with a specific window width and height.
701    window_size: Option<(u32, u32)>,
702    /// Launch the browser with a specific debugging port.
703    port: u16,
704    /// Path for Chrome or Chromium.
705    ///
706    /// If unspecified, the create will try to automatically detect a suitable
707    /// binary.
708    executable: std::path::PathBuf,
709
710    /// A list of Chrome extensions to load.
711    ///
712    /// An extension should be a path to a folder containing the extension code.
713    /// CRX files cannot be used directly and must be first extracted.
714    ///
715    /// Note that Chrome does not support loading extensions in headless-mode.
716    /// See https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c5
717    extensions: Vec<String>,
718
719    /// Environment variables to set for the Chromium process.
720    /// Passes value through to std::process::Command::envs.
721    pub process_envs: Option<HashMap<String, String>>,
722
723    /// Data dir for user data
724    pub user_data_dir: Option<PathBuf>,
725
726    /// Whether to launch the `Browser` in incognito mode.
727    incognito: bool,
728
729    /// Timeout duration for `Browser::launch`.
730    launch_timeout: Duration,
731
732    /// Ignore https errors, default is true.
733    ignore_https_errors: bool,
734    pub viewport: Option<Viewport>,
735    /// The duration after a request with no response should time out.
736    request_timeout: Duration,
737
738    /// Additional command line arguments to pass to the browser instance.
739    args: Vec<String>,
740
741    /// Whether to disable DEFAULT_ARGS or not, default is false.
742    disable_default_args: bool,
743
744    /// Whether to enable request interception.
745    pub request_intercept: bool,
746
747    /// Whether to enable cache.
748    pub cache_enabled: bool,
749    /// Whether to enable or disable Service Workers.
750    /// Disabling may reduce background network activity and caching effects.
751    pub service_worker_enabled: bool,
752    /// Whether to ignore image/visual requests during interception.
753    /// Can reduce bandwidth and speed up crawling when visuals are unnecessary.
754    pub ignore_visuals: bool,
755    /// Whether to ignore stylesheet (CSS) requests during interception.
756    /// Useful for content-only crawls.
757    pub ignore_stylesheets: bool,
758    /// Whether to ignore JavaScript requests during interception.
759    /// This still allows critical framework bundles to pass when applicable.
760    pub ignore_javascript: bool,
761    /// Whether to ignore analytics/telemetry requests during interception.
762    pub ignore_analytics: bool,
763    /// Whether to ignore ad network requests during interception.
764    pub ignore_ads: bool,
765    /// Extra headers.
766    pub extra_headers: Option<std::collections::HashMap<String, String>>,
767    /// Only html
768    pub only_html: bool,
769    /// The interception intercept manager.
770    pub intercept_manager: NetworkInterceptManager,
771    /// The max bytes to receive.
772    pub max_bytes_allowed: Option<u64>,
773}
774
775#[derive(Debug, Clone)]
776pub struct BrowserConfigBuilder {
777    /// Headless mode configuration for the browser.
778    headless: HeadlessMode,
779    /// Whether to run the browser with a sandbox.
780    sandbox: bool,
781    /// Optional initial browser window size `(width, height)`.
782    window_size: Option<(u32, u32)>,
783    /// DevTools debugging port to bind to.
784    port: u16,
785    /// Optional explicit path to the Chrome/Chromium executable.
786    /// If `None`, auto-detection may be attempted based on `executation_detection`.
787    executable: Option<PathBuf>,
788    /// Controls auto-detection behavior for finding a Chrome/Chromium binary.
789    executation_detection: DetectionOptions,
790    /// List of unpacked extensions (directories) to load at startup.
791    extensions: Vec<String>,
792    /// Environment variables to set on the spawned Chromium process.
793    process_envs: Option<HashMap<String, String>>,
794    /// User data directory to persist browser state, or `None` for ephemeral.
795    user_data_dir: Option<PathBuf>,
796    /// Whether to start the browser in incognito (off-the-record) mode.
797    incognito: bool,
798    /// Maximum time to wait for the browser to launch and become ready.
799    launch_timeout: Duration,
800    /// Whether to ignore HTTPS/TLS errors during navigation and requests.
801    ignore_https_errors: bool,
802    /// Default page viewport configuration applied on startup.
803    viewport: Option<Viewport>,
804    /// Timeout for individual network requests without response progress.
805    request_timeout: Duration,
806    /// Additional command-line flags passed directly to the browser process.
807    args: Vec<String>,
808    /// Disable the default argument set and use only the provided `args`.
809    disable_default_args: bool,
810    /// Enable Network.requestInterception for request filtering/handling.
811    request_intercept: bool,
812    /// Enable the browser cache for navigations and subresources.
813    cache_enabled: bool,
814    /// Enable/disable Service Workers.
815    service_worker_enabled: bool,
816    /// Drop image/visual requests when interception is enabled.
817    ignore_visuals: bool,
818    /// Drop ad network requests when interception is enabled.
819    ignore_ads: bool,
820    /// Drop JavaScript requests when interception is enabled.
821    ignore_javascript: bool,
822    /// Drop stylesheet (CSS) requests when interception is enabled.
823    ignore_stylesheets: bool,
824    /// Drop analytics/telemetry requests when interception is enabled.
825    ignore_analytics: bool,
826    /// If `true`, limit fetching to HTML documents.
827    only_html: bool,
828    /// Extra HTTP headers to include with every request.
829    extra_headers: Option<std::collections::HashMap<String, String>>,
830    /// Network interception manager used to configure filtering behavior.
831    intercept_manager: NetworkInterceptManager,
832    /// Optional upper bound on bytes that may be received (per session/run).
833    max_bytes_allowed: Option<u64>,
834}
835
836impl BrowserConfig {
837    /// Browser builder default config.
838    pub fn builder() -> BrowserConfigBuilder {
839        BrowserConfigBuilder::default()
840    }
841
842    /// Launch with the executable path.
843    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    /// Configure window size.
888    pub fn window_size(mut self, width: u32, height: u32) -> Self {
889        self.window_size = Some((width, height));
890        self
891    }
892    /// Configure sandboxing.
893    pub fn no_sandbox(mut self) -> Self {
894        self.sandbox = false;
895        self
896    }
897    /// Configure the launch to start non headless.
898    pub fn with_head(mut self) -> Self {
899        self.headless = HeadlessMode::False;
900        self
901    }
902    /// Configure the launch with the new headless mode.
903    pub fn new_headless_mode(mut self) -> Self {
904        self.headless = HeadlessMode::New;
905        self
906    }
907    /// Configure the launch with headless.
908    pub fn headless_mode(mut self, mode: HeadlessMode) -> Self {
909        self.headless = mode;
910        self
911    }
912    /// Configure the launch in incognito.
913    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    /// Configures the viewport of the browser, which defaults to `800x600`.
944    /// `None` disables viewport emulation (i.e., it uses the browsers default
945    /// configuration, which fills the available space. This is similar to what
946    /// Playwright does when you provide `null` as the value of its `viewport`
947    /// option).
948    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            // If the user did not specify a data directory, this would default to the systems default
1124            // data directory. In most cases, we would rather have a fresh instance of Chromium. Specify
1125            // a temp dir just for chromiumoxide instead.
1126            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/// Returns the path to Chrome's executable.
1162///
1163/// If the `CHROME` environment variable is set, `default_executable` will
1164/// use it as the default path. Otherwise, the filenames `google-chrome-stable`
1165/// `chromium`, `chromium-browser`, `chrome` and `chrome-browser` are
1166/// searched for in standard places. If that fails,
1167/// `/Applications/Google Chrome.app/...` (on MacOS) or the registry (on
1168/// Windows) is consulted. If all of the above fail, an error is returned.
1169#[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
1178/// These are passed to the Chrome binary by default.
1179/// Via https://github.com/puppeteer/puppeteer/blob/4846b8723cf20d3551c0d755df394cc5e0c82a94/src/node/Launcher.ts#L157
1180static 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];