Struct BrowserConfig

Source
pub struct BrowserConfig {
    pub process_envs: Option<HashMap<String, String>>,
    pub user_data_dir: Option<PathBuf>,
    pub request_intercept: bool,
    pub cache_enabled: bool,
    /* private fields */
}

Fields§

§process_envs: Option<HashMap<String, String>>

Environment variables to set for the Chromium process. Passes value through to std::process::Command::envs.

§user_data_dir: Option<PathBuf>

Data dir for user data

§request_intercept: bool

Whether to enable request interception

§cache_enabled: bool

Whether to enable cache

Implementations§

Source§

impl BrowserConfig

Source

pub fn builder() -> BrowserConfigBuilder

Examples found in repository?
src/browser.rs (line 14)
13    pub async fn new(headless: bool) -> BrowserResult<Self> {
14        let mut config = BrowserConfig::builder();
15
16        if !headless {
17            config = config.with_head();
18        }
19
20        let (browser, mut handler) = Browser::launch(config.build().unwrap())
21            .await
22            .map_err(|e| BrowserError::Launch(e.to_string()))?;
23
24        // In the task spawn section of all browser methods:
25        let handle = tokio::task::spawn(async move {
26            while let Some(event) = handler.next().await {
27                match event {
28                    Ok(_) => {}
29                    Err(e) => {
30                        let error_str = e.to_string();
31                        // Filter out common harmless errors
32                        if !error_str.contains("data did not match any variant")
33                            && !error_str.contains("ResetWithoutClosingHandshake")
34                            && !error_str.contains("Connection reset")
35                        {
36                            eprintln!("Browser event error: {:?}", e);
37                        }
38                    }
39                }
40            }
41        });
42
43        Ok(Self {
44            browser,
45            _handler: handle,
46        })
47    }
48    pub async fn new_stealth_browser(headless: bool) -> BrowserResult<Self> {
49        let args = vec![
50            "--disable-blink-features=AutomationControlled",
51            "--disable-infobars",
52            "--disable-extensions",
53            "--disable-plugins",
54            "--disable-web-security",
55            "--no-first-run",
56            "--disable-default-apps",
57            "--password-store=basic",
58            "--use-mock-keychain",
59            "--window-size=1366,768",
60            "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
61            "--lang=en-US",
62            "--accept-lang=en-US,en;q=0.9",
63            "--memory-pressure-off",
64            "--max_old_space_size=2048",
65            "--js-flags=--max-old-space-size=2048",
66            "--disable-background-timer-throttling",
67            "--disable-renderer-backgrounding",
68            "--disable-backgrounding-occluded-windows",
69            "--disable-dev-shm-usage",
70            "--no-sandbox",
71            "--disable-gpu",
72            "--disable-software-rasterizer",
73            "--disable-hang-monitor",
74            "--disable-prompt-on-repost",
75            "--disable-sync",
76            "--disable-translate",
77            "--disable-domain-reliability",
78            "--disable-component-extensions-with-background-pages",
79            "--disable-background-networking",
80            "--disable-client-side-phishing-detection",
81            "--disable-popup-blocking",
82            "--disable-notifications",
83            "--disable-desktop-notifications",
84            "--no-crash-upload",
85            "--no-default-browser-check",
86            "--no-pings",
87
88            "--disable-features=TranslateUI,VizDisplayCompositor",
89            "--disable-ipc-flooding-protection",
90            "--aggressive-cache-discard",
91            "--disable-backing-store-limit",
92
93            "--ignore-certificate-errors",
94            "--ignore-ssl-errors",
95            "--ignore-certificate-errors-spki-list",
96            "--disable-features=VizDisplayCompositor",
97        ];
98
99        let user_data_path = format!(
100            "/tmp/browser_profile_{}_{}",
101            std::process::id(),
102            std::time::SystemTime::now()
103                .duration_since(std::time::UNIX_EPOCH)
104                .unwrap()
105                .as_secs()
106        );
107
108        let mut config = BrowserConfig::builder()
109            .args(args)
110            .user_data_dir(&user_data_path)
111            .request_timeout(Duration::from_secs(30));
112
113        if !headless {
114            config = config.with_head();
115        }
116
117        let (browser, mut handler) = Browser::launch(config.build().unwrap())
118            .await
119            .map_err(|e| BrowserError::Launch(e.to_string()))?;
120        let handle = tokio::task::spawn(async move {
121            let mut consecutive_errors = 0;
122            const MAX_CONSECUTIVE_ERRORS: u32 = 5;
123
124            while let Some(event) = handler.next().await {
125                match event {
126                    Ok(_) => {
127                        consecutive_errors = 0;
128                    }
129                    Err(e) => {
130                        let error_str = e.to_string();
131                        if !error_str.contains("data did not match any variant")
132                            && !error_str.contains("ResetWithoutClosingHandshake")
133                            && !error_str.contains("Connection reset")
134                            && !error_str.contains("EOF")
135                        {
136                            consecutive_errors += 1;
137
138                            if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
139                                eprintln!(
140                                    "Browser unstable - {} consecutive errors",
141                                    consecutive_errors
142                                );
143                                break;
144                            }
145                        }
146                    }
147                }
148            }
149        });
150
151        Ok(Self {
152            browser,
153            _handler: handle,
154        })
155    }
Source

pub fn with_executable(path: impl AsRef<Path>) -> BrowserConfig

Source§

impl BrowserConfig

Source

pub fn launch(&self) -> Result<Child, Error>

Trait Implementations§

Source§

impl Clone for BrowserConfig

Source§

fn clone(&self) -> BrowserConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BrowserConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,