Skip to main content

BrowserSession

Struct BrowserSession 

Source
pub struct BrowserSession { /* private fields */ }
Expand description

A live browser session backed by a stealth Chrome instance.

BrowserSession is Send + 'static. The underlying ChaserPage (!Send) lives on a dedicated std::thread / tokio::task::LocalSet. All operations cross the thread boundary via an mpsc channel.

Drop = browser closes. Dropping BrowserSession closes the channel, which causes the worker loop to exit and the browser process to terminate.

Implementations§

Source§

impl BrowserSession

Source

pub async fn wait(&self, duration: Duration)

Wait for the given duration. Does not require a browser round-trip.

Source

pub async fn wait_for_network_idle( &self, timeout_ms: u64, idle_ms: u64, ) -> Result<String, NightFuryError>

Wait until the network has been idle for idle_ms milliseconds.

“Idle” means zero in-flight HTTP requests. Returns OperationFailed on timeout.

Source

pub async fn upload_files( &self, selector: &str, paths: &[&str], ) -> Result<String, NightFuryError>

Set the files on a <input type="file"> element. paths are local filesystem paths on the machine running the browser.

Source

pub async fn set_viewport( &self, width: u32, height: u32, ) -> Result<String, NightFuryError>

Resize the browser viewport.

Source

pub async fn set_offline(&self, offline: bool) -> Result<String, NightFuryError>

Toggle network offline mode. Pass true to go offline, false to restore.

Source

pub async fn set_extra_headers( &self, headers: Value, ) -> Result<String, NightFuryError>

Inject extra HTTP headers for all subsequent requests on this tab. headers must be a JSON object where both keys and values are strings.

Source

pub async fn save_session(&self) -> Result<SessionData, NightFuryError>

Capture all cookies, localStorage, and sessionStorage as a portable snapshot.

Source

pub async fn restore_session( &self, data: SessionData, ) -> Result<String, NightFuryError>

Restore cookies, localStorage, and sessionStorage from a previously saved snapshot.

Source

pub async fn frame(&self, selector: &str) -> Result<Frame, NightFuryError>

Return a Frame handle scoped to the same-origin iframe matching selector. Verifies the iframe exists and is same-origin up front.

Prefer this over raw switch_to_frame when doing multiple operations against the same iframe — the handle restores main-frame context automatically after every call. See the frame module docs for concurrency and cancellation caveats.

Side effect: the up-front verification probe resets the session to main-frame context on success, so calling this while already in a frame context will silently exit that outer frame.

Source

pub async fn switch_to_frame( &self, selector: &str, ) -> Result<String, NightFuryError>

Switch the active document context to the same-origin iframe matching selector. Subsequent snapshot and eval commands will operate inside that frame.

Source

pub async fn switch_to_main_frame(&self) -> Result<String, NightFuryError>

Return to the main page context (undo a previous switch_to_frame).

Source

pub async fn set_dialog_handler( &self, accept: bool, prompt_text: Option<String>, ) -> Result<String, NightFuryError>

Set the auto-handle policy for JS dialogs (alert/confirm/prompt/beforeunload).

accept = true accepts the dialog; false dismisses it. prompt_text is only used when accepting a prompt dialog.

The default is accept = true, prompt_text = None.

Source

pub async fn get_last_dialog( &self, ) -> Result<Option<DialogInfo>, NightFuryError>

Return info about the last JS dialog that was shown, or None if no dialog has appeared since the session started (or since the last call that reset it).

Source

pub async fn set_console_capture( &self, enabled: bool, ) -> Result<String, NightFuryError>

Enable or disable console message capture.

When disabled (the default), console messages are discarded and the buffer is cleared. Enable before the action that produces console output.

Source

pub async fn get_console_logs( &self, ) -> Result<Vec<ConsoleMessage>, NightFuryError>

Return all captured console messages and clear the buffer.

Source

pub async fn authenticate( &self, username: &str, password: &str, ) -> Result<String, NightFuryError>

Set credentials for HTTP Basic/Digest authentication.

When the browser encounters an auth challenge (e.g. a 401 from a server or a 407 from a proxy), it automatically responds with these credentials. Call this before navigating to the protected resource.

Source

pub async fn add_init_script( &self, source: &str, ) -> Result<String, NightFuryError>

Inject JavaScript that runs before any page script on every new document load.

Returns a script identifier that can be passed to remove_init_script to stop injecting the script on future navigations.

Uses CDP Page.addScriptToEvaluateOnNewDocument.

§Example
let script_id = session.add_init_script("window.__test = true;").await?;
session.navigate("https://example.com").await?;
// window.__test is now true in the page context
session.remove_init_script(&script_id).await?;
Source

pub async fn remove_init_script( &self, identifier: &str, ) -> Result<String, NightFuryError>

Remove a previously injected init script by its identifier.

Uses CDP Page.removeScriptToEvaluateOnNewDocument.

Source

pub async fn get_response_body( &self, request_id: &str, ) -> Result<(String, bool), NightFuryError>

Fetch the response body for a previously observed network request by CDP request id.

Typical flow:

  1. Call BrowserSession::subscribe_events.
  2. Wait for a PageEvent::LoadingFinished matching the request you care about (the body is only ready after this event).
  3. Call this method with that event’s request_id.

Returns (body, base64_encoded). When base64_encoded is true, the body string is base64; decode it for binary responses.

Wraps CDP Network.getResponseBody. Requires the Network domain to be enabled (which subscribe_events does automatically).

Source

pub async fn cdp_command( &self, method: &str, params: Value, ) -> Result<Value, NightFuryError>

Execute a raw CDP command by method name and JSON parameters.

This is an escape hatch for CDP features that night-fury does not yet wrap. The response is the raw JSON returned by the browser.

§Example
let result = session.cdp_command(
    "Page.captureScreenshot",
    serde_json::json!({ "format": "webp", "quality": 80 }),
).await?;
Source§

impl BrowserSession

Source

pub async fn snapshot(&self) -> Result<Snapshot, NightFuryError>

Return a structured snapshot of the current page.

The returned Snapshot contains elements indexed 0-based. Pass Selector::Ref(idx) to click() or type_text() using these indices.

Source

pub async fn screenshot(&self) -> Result<Vec<u8>, NightFuryError>

Capture a PNG screenshot. Returns raw PNG bytes.

Source

pub async fn screenshot_element( &self, selector: &str, ) -> Result<Vec<u8>, NightFuryError>

Capture a PNG screenshot of a specific element identified by CSS selector.

Uses getBoundingClientRect to determine element bounds, then captures a clipped screenshot of that region. Returns raw PNG bytes.

Source

pub async fn screenshot_element_by_ref( &self, ref_id: usize, ) -> Result<Vec<u8>, NightFuryError>

Capture a PNG screenshot of a specific element identified by snapshot @ref index.

Uses DOM.getBoxModel to determine element bounds, then captures a clipped screenshot of that region. Requires a prior snapshot() call to populate refs. Returns raw PNG bytes.

Source

pub async fn pdf(&self) -> Result<Vec<u8>, NightFuryError>

Export the current page as a PDF with default options. Returns raw PDF bytes.

Produces a US-Letter portrait PDF with Chrome’s default margins.

Source

pub async fn pdf_with_options( &self, options: PdfOptions, ) -> Result<Vec<u8>, NightFuryError>

Export the current page as a PDF with custom options. Returns raw PDF bytes.

Source

pub async fn performance_metrics( &self, ) -> Result<PerformanceMetrics, NightFuryError>

Retrieve runtime performance metrics from Chrome’s Performance domain.

Returns timing data (FCP, DOMContentLoaded, etc.), DOM node counts, JS heap sizes, and layout statistics. Fields are None until Chrome has fired the corresponding event.

Source

pub async fn layout_metrics(&self) -> Result<LayoutMetrics, NightFuryError>

Retrieve page layout metrics (viewport dimensions and content size).

Useful for determining whether the page has scrollable content and how large the full document is relative to the visible viewport.

Source

pub async fn eval(&self, js: &str) -> Result<Value, NightFuryError>

Evaluate JavaScript in the page context. Returns null if the script returns nothing.

Source

pub async fn http_ping(&self, url: &str) -> Result<u16, NightFuryError>

Issue a fetch(url, {credentials: "include"}) from within the page context and return the HTTP status code.

This is a lightweight session-validity probe — typical use is “hit an authenticated endpoint and check for 200 vs 401”. Because the request runs inside the browser, it uses existing cookies automatically.

Returns 0 if the fetch throws (network error, CORS block, etc.).

§Example
let status = session.http_ping("https://x.com/i/api/graphql/ping").await?;
if status == 200 { println!("session valid"); }
Source

pub async fn start_coverage(&self) -> Result<(), NightFuryError>

Start collecting CSS and JavaScript code coverage.

Enables the CDP Profiler domain with precise coverage (call counts + block-level detail) and the CSS domain’s rule usage tracking. Call stop_coverage() after interacting with the page to retrieve the collected data.

Source

pub async fn stop_coverage(&self) -> Result<CoverageReport, NightFuryError>

Stop collecting coverage and return the results.

Returns a CoverageReport containing JS and CSS coverage data gathered since the last start_coverage() call. The Profiler and CSS tracking are disabled after this call.

Source§

impl BrowserSession

Source

pub async fn new_context(&self) -> Result<BrowserContext, NightFuryError>

Create a new isolated browser context with its own cookies, localStorage, and cache. Returns a BrowserContext handle that can open tabs and be disposed when no longer needed.

Source§

impl BrowserSession

Source

pub async fn set_download_path(&self, path: &str) -> Result<(), NightFuryError>

Set the directory where Chrome saves downloaded files.

This must be called before initiating a download. The path must be an absolute directory path that the Chrome process can write to.

session.set_download_path("/tmp/downloads").await?;
Source

pub async fn wait_for_download( &self, timeout: Duration, ) -> Result<DownloadInfo, NightFuryError>

Wait for a file download to complete within the given timeout.

Returns a DownloadInfo with the file path, filename, size, and URL once the download finishes. Returns an error if the download is canceled or the timeout is exceeded.

Prerequisite: call set_download_path before triggering the download so Chrome knows where to save the file and to enable download progress events.

session.set_download_path("/tmp/downloads").await?;
// ... trigger the download (e.g. click a download link) ...
let download = session.wait_for_download(Duration::from_secs(30)).await?;
println!("saved to {}", download.path);
Source

pub async fn cancel_download(&self, guid: &str) -> Result<(), NightFuryError>

Cancel an in-progress download by its guid.

Obtain the guid from a PageEvent::DownloadBegin delivered via subscribe_events. A cancel that races with completion is a no-op on some Chrome builds.

guid is browser-global (not tab-scoped) — it remains valid even if you switch tabs between receiving DownloadBegin and calling cancel.

Source§

impl BrowserSession

Source

pub async fn set_geolocation( &self, latitude: f64, longitude: f64, ) -> Result<String, NightFuryError>

Override the browser’s reported geolocation.

Source

pub async fn emulate_media_feature( &self, name: &str, value: &str, ) -> Result<String, NightFuryError>

Override a CSS media feature for media queries.

Common features: prefers-color-scheme (dark / light), prefers-reduced-motion (reduce / no-preference).

Source

pub async fn emulate_media_type( &self, media: &str, ) -> Result<String, NightFuryError>

Override the CSS media type (e.g. screen, print). Pass an empty string to disable the override.

Source

pub async fn emulate_timezone( &self, timezone_id: &str, ) -> Result<String, NightFuryError>

Override the browser’s timezone. Pass a valid IANA timezone ID (e.g. Asia/Tokyo, America/New_York). Pass an empty string to restore the default.

Source

pub async fn emulate_locale( &self, locale: &str, ) -> Result<String, NightFuryError>

Override the browser’s locale (e.g. ja-JP, en-US). Pass an empty string to restore the default.

Source§

impl BrowserSession

Source

pub async fn subscribe_events( &self, buffer: usize, ) -> Result<Receiver<PageEvent>, NightFuryError>

Subscribe to real-time page events (console messages, JS errors, network requests) via a broadcast::Receiver<PageEvent>.

buffer controls the broadcast channel capacity. A value of 64-256 is reasonable for most use cases. Events that arrive when the receiver is lagging behind are dropped (broadcast channel semantics).

Calling this method multiple times returns additional receivers attached to the same underlying broadcast channel – CDP listeners are only registered once.

§Example
let mut rx = session.subscribe_events(128).await?;
tokio::spawn(async move {
    while let Ok(event) = rx.recv().await {
        println!("{event:?}");
    }
});
Source

pub async fn subscribe_raw_cdp_event<T>( &self, buffer: usize, ) -> Result<Receiver<T>, NightFuryError>
where T: CustomEvent + Clone + Send + Sync + Unpin + 'static,

Subscribe to an arbitrary CDP event by type.

T must be a type implementing chromiumoxide_cdp::cdp::CustomEvent and chromiumoxide_types::MethodType (so the CDP method name is known at compile time). Use the [define_cdp_event!] macro for a terse definition.

Returns a broadcast::Receiver<T> that yields each matching event. The CDP domain corresponding to the event must be enabled before events will be dispatched — if you’re listening to a Network.* event, call cdp_command("Network.enable", json!({})) (or subscribe_events, which enables Network/Runtime/Log) first.

§Limitation: built-in events only route through the typed path

This method is an escape hatch for CDP events not already modeled by chromiumoxide_cdp. Built-in events (anything in chromiumoxide_cdp::cdp::CdpEvent — which covers ~1000 events including all Network.*, Page.*, Target.*, Storage.*, etc.) are dispatched by concrete Rust type, not by method id string. A custom type whose method_id() matches a built-in event will never receive events: the downcast inside EventStream fails and events are silently dropped. For built-in events, use BrowserSession::subscribe_events (for the typed PageEvent variants) or file a request to add a first-class wrapper. Use this method only for experimental or Chrome-Canary-only events that chromiumoxide_cdp does not yet cover.

§Example
use night_fury_core::{define_cdp_event, BrowserSession, NightFuryError};
use serde::Deserialize;

define_cdp_event!(WebSocketCreated, "Network.webSocketCreated", {
    request_id: String,
    url: String,
});

async fn demo(session: BrowserSession) -> Result<(), NightFuryError> {
    session.cdp_command("Network.enable", serde_json::json!({})).await?;
    let mut rx = session.subscribe_raw_cdp_event::<WebSocketCreated>(64).await?;
    while let Ok(evt) = rx.recv().await {
        println!("ws created: {}", evt.url);
    }
    Ok(())
}
Source§

impl BrowserSession

Source

pub async fn scroll(&self, pixels: i32) -> Result<String, NightFuryError>

Scroll the page. Positive pixels = scroll down; negative = scroll up.

Source

pub async fn scroll_to_element( &self, selector: &str, ) -> Result<String, NightFuryError>

Scroll an element into the viewport.

Source

pub async fn scroll_element( &self, selector: &str, pixels: i32, ) -> Result<String, NightFuryError>

Scroll inside a container element. Positive pixels = scroll down.

Source§

impl BrowserSession

Source

pub async fn click_human( &self, selector: Selector, ) -> Result<String, NightFuryError>

Click an element with explicit human-like Bezier mouse movement, jitter, and random delays. Functionally identical to click (which already uses click_human internally) but provided as a named method for clarity.

Source

pub async fn type_human( &self, selector: Selector, text: &str, typos: bool, ) -> Result<String, NightFuryError>

Type text with human-like variable inter-keystroke delays and optional typos with self-correction. When typos is true, the underlying driver occasionally types wrong characters and corrects them with backspace.

Source

pub async fn scroll_human(&self, pixels: i32) -> Result<String, NightFuryError>

Scroll with human-like ease-in/ease-out and variable steps. Positive pixels = scroll down; negative = scroll up.

Source§

impl BrowserSession

Source

pub async fn click_with_timeout( &self, selector: Selector, timeout: Duration, ) -> Result<String, NightFuryError>

Click an element, retrying on ElementNotFound until timeout expires.

Polls every 100 ms. Useful when elements appear asynchronously after navigation or JS rendering.

Source

pub async fn click(&self, selector: Selector) -> Result<String, NightFuryError>

Click an element identified by selector.

Source

pub async fn dbl_click_with_timeout( &self, selector: Selector, timeout: Duration, ) -> Result<String, NightFuryError>

Double-click an element, retrying on ElementNotFound until timeout expires.

Source

pub async fn dbl_click( &self, selector: Selector, ) -> Result<String, NightFuryError>

Double-click an element. Accepts the same selector types as click.

Source

pub async fn dbl_click_by_ref( &self, idx: usize, ) -> Result<String, NightFuryError>

Double-click an element by @ref index from the last snapshot.

Source

pub async fn type_text_with_timeout( &self, selector: Selector, text: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Type text into an element, retrying on ElementNotFound until timeout expires.

Source

pub async fn type_text( &self, selector: Selector, text: &str, ) -> Result<String, NightFuryError>

Type text into an element identified by selector. Clears any existing value before typing.

Source

pub async fn key_press(&self, key: &str) -> Result<String, NightFuryError>

Send a keyboard key press (keyDown + keyUp).

Use standard key names: Enter, Tab, Escape, Backspace, Space, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Delete, etc.

Source

pub async fn hover_with_timeout( &self, selector: Selector, timeout: Duration, ) -> Result<String, NightFuryError>

Hover over an element, retrying on ElementNotFound until timeout expires.

Source

pub async fn hover(&self, selector: Selector) -> Result<String, NightFuryError>

Hover over an element (triggers mousemove and CSS :hover states).

Source

pub async fn select_with_timeout( &self, selector: Selector, value: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Select an option, retrying on ElementNotFound until timeout expires.

Source

pub async fn select( &self, selector: Selector, value: &str, ) -> Result<String, NightFuryError>

Select an option in a <select> element. Dispatches input and change events so JS frameworks react. value is the option’s .value attribute (not its visible text).

Source

pub async fn check_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Check a checkbox, retrying on ElementNotFound until timeout expires.

Source

pub async fn check(&self, selector: &str) -> Result<String, NightFuryError>

Ensure a checkbox or radio button is checked. No-op if already checked.

Source

pub async fn uncheck_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Uncheck a checkbox, retrying on ElementNotFound until timeout expires.

Source

pub async fn uncheck(&self, selector: &str) -> Result<String, NightFuryError>

Ensure a checkbox is unchecked. No-op if already unchecked.

Source

pub async fn drag_to_with_timeout( &self, source: Selector, target: Selector, timeout: Duration, ) -> Result<String, NightFuryError>

Drag between elements, retrying on ElementNotFound until timeout expires.

Source

pub async fn drag_to( &self, source: Selector, target: Selector, ) -> Result<String, NightFuryError>

Drag from one element to another. Accepts the same selector types as click.

Source

pub async fn drag_to_by_ref( &self, source_idx: usize, target_idx: usize, ) -> Result<String, NightFuryError>

Drag from one @ref element to another @ref element.

Source

pub async fn mouse_move(&self, x: f64, y: f64) -> Result<String, NightFuryError>

Move the mouse to absolute viewport coordinates (x, y).

Dispatches a CDP Input.dispatchMouseEvent with type mouseMoved. This fires DOM mousemove, mouseenter, and mouseover events and triggers CSS :hover states, but does not click or select any element.

Source

pub async fn mouse_wheel( &self, delta_x: f64, delta_y: f64, ) -> Result<String, NightFuryError>

Dispatch a mouse wheel (scroll) event.

delta_x and delta_y are pixel deltas. Positive delta_y scrolls down; negative scrolls up. Positive delta_x scrolls right; negative scrolls left.

Source

pub async fn mouse_down( &self, button: MouseButton, ) -> Result<String, NightFuryError>

Press a mouse button down at the current cursor position.

Pair with mouse_up to perform custom click sequences or hold-and-drag operations.

Source

pub async fn mouse_up( &self, button: MouseButton, ) -> Result<String, NightFuryError>

Release a mouse button at the current cursor position.

Pair with mouse_down to complete a click or finish a drag operation.

Source§

impl BrowserSession

Source

pub async fn navigate(&self, url: &str) -> Result<String, NightFuryError>

Navigate to a URL. Call snapshot() afterwards to observe the page.

Source

pub async fn back(&self) -> Result<String, NightFuryError>

Navigate to the previous page in browser history.

Source

pub async fn forward(&self) -> Result<String, NightFuryError>

Navigate to the next page in browser history.

Source

pub async fn reload(&self) -> Result<String, NightFuryError>

Reload the current page.

Source

pub async fn get_url(&self) -> Result<String, NightFuryError>

Return the current page URL without a full snapshot.

Source

pub async fn get_title(&self) -> Result<String, NightFuryError>

Return the current page title without a full snapshot.

Source

pub async fn wait_for_navigation( &self, timeout_ms: u64, ) -> Result<String, NightFuryError>

Wait for the page’s load event to fire.

Call this immediately after an action that triggers navigation (e.g. click on a link). Returns Navigation error on timeout.

Source§

impl BrowserSession

Source

pub async fn get_text_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Return the innerText, retrying on ElementNotFound until timeout expires.

Source

pub async fn get_text(&self, selector: &str) -> Result<String, NightFuryError>

Return the innerText of an element identified by CSS selector.

Source

pub async fn get_value_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Return the .value property, retrying on ElementNotFound until timeout expires.

Source

pub async fn get_value(&self, selector: &str) -> Result<String, NightFuryError>

Return the .value property of an input/textarea/select element.

Source

pub async fn get_attribute_with_timeout( &self, selector: &str, attribute: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Return an attribute value, retrying on ElementNotFound until timeout expires.

Source

pub async fn get_attribute( &self, selector: &str, attribute: &str, ) -> Result<String, NightFuryError>

Return the value of a DOM attribute from an element identified by CSS selector.

Source

pub async fn get_html_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>

Return the innerHTML, retrying on ElementNotFound until timeout expires.

Source

pub async fn get_html(&self, selector: &str) -> Result<String, NightFuryError>

Return the innerHTML of an element.

Source

pub async fn get_count(&self, selector: &str) -> Result<usize, NightFuryError>

Return the number of DOM elements matching a CSS selector.

Source

pub async fn get_box_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<Value, NightFuryError>

Return the bounding box, retrying on ElementNotFound until timeout expires.

Source

pub async fn get_box(&self, selector: &str) -> Result<Value, NightFuryError>

Return the bounding box {x, y, width, height} of an element.

Source

pub async fn is_checked_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<bool, NightFuryError>

Check if element is checked, retrying on ElementNotFound until timeout expires.

Source

pub async fn is_checked(&self, selector: &str) -> Result<bool, NightFuryError>

Return true if the checkbox/radio is checked, false if unchecked. Returns ElementNotFound if the selector matches nothing.

Source

pub async fn is_visible_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<bool, NightFuryError>

Check if element is visible, retrying on ElementNotFound until timeout expires.

Source

pub async fn is_visible(&self, selector: &str) -> Result<bool, NightFuryError>

Return true if the element is visible (non-zero size, not hidden). Returns ElementNotFound if the selector matches nothing.

Source

pub async fn is_enabled_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<bool, NightFuryError>

Check if element is enabled, retrying on ElementNotFound until timeout expires.

Source

pub async fn is_enabled(&self, selector: &str) -> Result<bool, NightFuryError>

Return true if the element is not disabled. Returns ElementNotFound if the selector matches nothing.

Source

pub async fn wait_for_selector( &self, selector: &str, timeout_ms: u64, ) -> Result<String, NightFuryError>

Wait until a CSS selector matches an element in the DOM.

Polls every 100 ms. Returns ElementNotFound on timeout.

Source§

impl BrowserSession

Source

pub async fn add_route( &self, pattern: &str, action: RouteAction, ) -> Result<String, NightFuryError>

Add a URL-pattern route rule. Wildcards: * = zero-or-more, ? = one char.

Source

pub async fn remove_route( &self, pattern: &str, ) -> Result<String, NightFuryError>

Remove a previously added route rule by its pattern.

Source

pub async fn capture_responses( &self, pattern: &str, ) -> Result<String, NightFuryError>

Start capturing response bodies for URLs matching the given pattern.

Uses CDP Fetch.enable with response-stage interception and Fetch.getResponseBody to collect response data. Captured responses are retrieved via get_captured_responses().

Wildcards: * = zero-or-more chars, ? = one char.

Source

pub async fn get_captured_responses( &self, ) -> Result<Vec<CapturedResponse>, NightFuryError>

Retrieve and drain all captured responses collected since the last call.

Returns a Vec<CapturedResponse> containing the URL, status code, headers, and body of each matching response. The internal buffer is cleared after each call.

Source

pub async fn clear_routes(&self) -> Result<String, NightFuryError>

Remove all route rules (disables Fetch interception entirely).

Source§

impl BrowserSession

Source

pub async fn set_cookies( &self, cookies: Vec<Value>, ) -> Result<String, NightFuryError>

Inject cookies into the browser context before or after navigation.

Accepts an array of cookie objects in the standard browser-export JSON format (Chrome DevTools, Cookie-Editor, EditThisCookie). Both httpOnly/secure and isHttpOnly/isSecure field names are accepted; expirationDate is treated as an alias for expires.

Navigate to the target domain before calling set_cookies so that the browser can associate cookies with the correct origin.

Source

pub async fn get_cookies(&self) -> Result<Vec<Value>, NightFuryError>

Return all cookies currently visible to the browser as JSON objects.

Source

pub async fn refresh_cookies( &self, url: &str, ) -> Result<Vec<Value>, NightFuryError>

Navigate to a URL that triggers a server-side Set-Cookie response (e.g. a /refresh, /keep-alive, or home-page endpoint), wait for the page to settle, then return the current cookies.

This is a convenience over Self::navigate + Self::get_cookies that names the intent — readers see refresh_cookies and understand this is the session-renewal pattern, not just any navigation.

Returns all cookies in the browser jar, not just ones set by the refresh URL. Use Self::get_cookies_for_domain to filter by site.

§Example
let fresh = session.refresh_cookies("https://x.com/home").await?;
println!("refreshed {} cookies", fresh.len());
Source

pub async fn get_cookies_for_domain( &self, pattern: &str, ) -> Result<Vec<Value>, NightFuryError>

Return cookies whose domain field matches the given glob pattern.

Pattern semantics:

  • *.twitter.com — any host ending in .twitter.com (including .twitter.com itself)
  • twitter.com — substring match; covers .twitter.com, api.twitter.com, etc.

The wildcard form is preferred for precision; the substring form is a pragmatic fallback for cookie domain values that carry leading dots.

§Example
let x_cookies = session.get_cookies_for_domain("*.x.com").await?;
let all_twitter = session.get_cookies_for_domain("twitter.com").await?;

Delete a specific cookie by name and domain.

Useful for session rotation without full browser restart, or for testing auth flows (logout simulation).

Source

pub async fn delete_all_cookies(&self) -> Result<String, NightFuryError>

Delete all cookies in the current browser context.

Equivalent to clearing cookies via Chrome DevTools. Useful for full session rotation or starting a clean browsing state.

Source

pub async fn storage_get( &self, storage: StorageKind, key: Option<&str>, ) -> Result<Value, NightFuryError>

Read from localStorage or sessionStorage. Pass key=None to return the entire storage as a JSON object.

Source

pub async fn storage_set( &self, storage: StorageKind, key: &str, value: &str, ) -> Result<String, NightFuryError>

Write a key/value pair to localStorage or sessionStorage.

Source

pub async fn storage_clear( &self, storage: StorageKind, ) -> Result<String, NightFuryError>

Clear all entries in localStorage or sessionStorage.

Source

pub async fn clipboard_write( &self, text: &str, ) -> Result<String, NightFuryError>

Write text to the clipboard via the browser’s clipboard API. Grants clipboardReadWrite permission automatically.

Source

pub async fn clipboard_read(&self) -> Result<String, NightFuryError>

Read text from the clipboard via the browser’s clipboard API. Grants clipboardReadWrite permission automatically.

Source§

impl BrowserSession

Source

pub async fn new_tab(&self, url: Option<&str>) -> Result<usize, NightFuryError>

Open a new tab. If url is provided the tab navigates to it immediately. Returns the zero-based index of the new tab; the new tab becomes the active tab.

Source

pub async fn switch_tab(&self, idx: usize) -> Result<String, NightFuryError>

Switch the active tab to idx. All subsequent commands operate on that tab. Returns InvalidArgument if idx is out of range.

Source

pub async fn list_tabs(&self) -> Result<Vec<TabInfo>, NightFuryError>

Return metadata for every open tab.

Source

pub async fn close_tab( &self, idx: Option<usize>, ) -> Result<String, NightFuryError>

Close a tab by index. Pass None to close the currently active tab. The last remaining tab cannot be closed. If the closed tab was active, the active tab becomes the next tab (or the last tab if the closed tab was at the end of the list). Returns InvalidArgument if idx is out of range.

Source

pub async fn bring_to_front(&self) -> Result<(), NightFuryError>

Activate the active tab’s renderer target via Page.bringToFront.

Useful when a popup or background tab needs focus for keyboard events or document.hasFocus()-gated logic.

Scope is the CDP target (tab), not the OS window: this does NOT raise the Chrome window above other applications. In headless mode it is effectively a no-op.

Source§

impl BrowserSession

Source

pub async fn tap(&self, x: f64, y: f64) -> Result<String, NightFuryError>

Simulate a touch tap at the given screen coordinates.

Dispatches touchStart followed by touchEnd via CDP Input.dispatchTouchEvent. The viewport should be configured with has_touch: true and emulating_mobile: true for correct behaviour.

Source

pub async fn swipe( &self, start_x: f64, start_y: f64, end_x: f64, end_y: f64, ) -> Result<String, NightFuryError>

Simulate a touch swipe gesture between two points.

Dispatches touchStart, a series of interpolated touchMove events, and a final touchEnd. Use this for scroll-like gestures on mobile-emulated pages.

// Swipe up (scroll down):
session.swipe(200.0, 500.0, 200.0, 100.0).await?;
// Swipe left:
session.swipe(300.0, 400.0, 50.0, 400.0).await?;
Source§

impl BrowserSession

Source

pub async fn enable_ws_capture(&self) -> Result<String, NightFuryError>

Enable WebSocket message capture.

Subscribes to CDP Network.webSocketCreated, Network.webSocketFrameSent, and Network.webSocketFrameReceived events. Captured messages are retrieved via get_ws_messages().

This method is idempotent: calling it multiple times is safe.

Source

pub async fn get_ws_messages(&self) -> Result<Vec<WsMessage>, NightFuryError>

Retrieve and drain all captured WebSocket messages since the last call.

Returns a Vec<WsMessage> containing the URL, direction, payload data, opcode, and timestamp of each captured frame. The internal buffer is cleared after each call.

Source§

impl BrowserSession

Source

pub fn builder() -> SessionBuilder

Create a SessionBuilder to configure and launch a new browser.

Source

pub fn from_sender(tx: Sender<BrowserCmd>) -> BrowserSession

Wrap an existing mpsc::Sender<BrowserCmd> into a BrowserSession.

Use this when you need to manage the browser thread yourself — for example, flock’s stealth_launch spawns its own thread to perform Cloudflare bypass logic, then wraps the resulting channel sender here.

The caller must ensure a run_worker(chaser, rx) loop is running on a LocalSet thread that consumes the matching mpsc::Receiver<BrowserCmd>.

Source

pub fn auto_wait(&self) -> Option<Duration>

Return the configured auto-wait duration, if any.

Source

pub fn set_auto_wait(&mut self, timeout: Option<Duration>)

Set the auto-wait duration for element operations.

When set, element operations (click, type_text, get_text, etc.) automatically retry on ElementNotFound errors, polling every 100 ms until the element appears or the timeout expires.

Pass None to disable auto-wait (the default).

Source

pub fn with_auto_wait(self, timeout: Duration) -> BrowserSession

Create a new session handle with the given auto-wait duration.

This is a convenience builder-style method that returns a new BrowserSession sharing the same underlying browser connection.

Source

pub fn actions(&self) -> ActionChain<'_>

Create an ActionChain builder to queue multiple browser actions.

Actions are executed sequentially when ActionChain::execute is called, stopping on the first error.

Trait Implementations§

Source§

impl Clone for BrowserSession

Source§

fn clone(&self) -> BrowserSession

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 BrowserSession

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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