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
impl BrowserSession
Sourcepub async fn wait(&self, duration: Duration)
pub async fn wait(&self, duration: Duration)
Wait for the given duration. Does not require a browser round-trip.
Sourcepub async fn wait_for_network_idle(
&self,
timeout_ms: u64,
idle_ms: u64,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn upload_files(
&self,
selector: &str,
paths: &[&str],
) -> Result<String, NightFuryError>
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.
Sourcepub async fn set_viewport(
&self,
width: u32,
height: u32,
) -> Result<String, NightFuryError>
pub async fn set_viewport( &self, width: u32, height: u32, ) -> Result<String, NightFuryError>
Resize the browser viewport.
Sourcepub async fn set_offline(&self, offline: bool) -> Result<String, NightFuryError>
pub async fn set_offline(&self, offline: bool) -> Result<String, NightFuryError>
Toggle network offline mode. Pass true to go offline, false to restore.
Sourcepub async fn set_extra_headers(
&self,
headers: Value,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn save_session(&self) -> Result<SessionData, NightFuryError>
pub async fn save_session(&self) -> Result<SessionData, NightFuryError>
Capture all cookies, localStorage, and sessionStorage as a portable snapshot.
Sourcepub async fn restore_session(
&self,
data: SessionData,
) -> Result<String, NightFuryError>
pub async fn restore_session( &self, data: SessionData, ) -> Result<String, NightFuryError>
Restore cookies, localStorage, and sessionStorage from a previously saved snapshot.
Sourcepub async fn frame(&self, selector: &str) -> Result<Frame, NightFuryError>
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.
Sourcepub async fn switch_to_frame(
&self,
selector: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn switch_to_main_frame(&self) -> Result<String, NightFuryError>
pub async fn switch_to_main_frame(&self) -> Result<String, NightFuryError>
Return to the main page context (undo a previous switch_to_frame).
Sourcepub async fn set_dialog_handler(
&self,
accept: bool,
prompt_text: Option<String>,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_last_dialog(
&self,
) -> Result<Option<DialogInfo>, NightFuryError>
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).
Sourcepub async fn set_console_capture(
&self,
enabled: bool,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_console_logs(
&self,
) -> Result<Vec<ConsoleMessage>, NightFuryError>
pub async fn get_console_logs( &self, ) -> Result<Vec<ConsoleMessage>, NightFuryError>
Return all captured console messages and clear the buffer.
Sourcepub async fn authenticate(
&self,
username: &str,
password: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn add_init_script(
&self,
source: &str,
) -> Result<String, NightFuryError>
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?;Sourcepub async fn remove_init_script(
&self,
identifier: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_response_body(
&self,
request_id: &str,
) -> Result<(String, bool), NightFuryError>
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:
- Call
BrowserSession::subscribe_events. - Wait for a
PageEvent::LoadingFinishedmatching the request you care about (the body is only ready after this event). - 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).
Sourcepub async fn cdp_command(
&self,
method: &str,
params: Value,
) -> Result<Value, NightFuryError>
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
impl BrowserSession
Sourcepub async fn snapshot(&self) -> Result<Snapshot, NightFuryError>
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.
Sourcepub async fn screenshot(&self) -> Result<Vec<u8>, NightFuryError>
pub async fn screenshot(&self) -> Result<Vec<u8>, NightFuryError>
Capture a PNG screenshot. Returns raw PNG bytes.
Sourcepub async fn screenshot_element(
&self,
selector: &str,
) -> Result<Vec<u8>, NightFuryError>
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.
Sourcepub async fn screenshot_element_by_ref(
&self,
ref_id: usize,
) -> Result<Vec<u8>, NightFuryError>
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.
Sourcepub async fn pdf(&self) -> Result<Vec<u8>, NightFuryError>
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.
Sourcepub async fn pdf_with_options(
&self,
options: PdfOptions,
) -> Result<Vec<u8>, NightFuryError>
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.
Sourcepub async fn performance_metrics(
&self,
) -> Result<PerformanceMetrics, NightFuryError>
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.
Sourcepub async fn layout_metrics(&self) -> Result<LayoutMetrics, NightFuryError>
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.
Sourcepub async fn eval(&self, js: &str) -> Result<Value, NightFuryError>
pub async fn eval(&self, js: &str) -> Result<Value, NightFuryError>
Evaluate JavaScript in the page context. Returns null if the script
returns nothing.
Sourcepub async fn http_ping(&self, url: &str) -> Result<u16, NightFuryError>
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"); }Sourcepub async fn start_coverage(&self) -> Result<(), NightFuryError>
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.
Sourcepub async fn stop_coverage(&self) -> Result<CoverageReport, NightFuryError>
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
impl BrowserSession
Sourcepub async fn new_context(&self) -> Result<BrowserContext, NightFuryError>
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
impl BrowserSession
Sourcepub async fn set_download_path(&self, path: &str) -> Result<(), NightFuryError>
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?;Sourcepub async fn wait_for_download(
&self,
timeout: Duration,
) -> Result<DownloadInfo, NightFuryError>
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);Sourcepub async fn cancel_download(&self, guid: &str) -> Result<(), NightFuryError>
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
impl BrowserSession
Sourcepub async fn set_geolocation(
&self,
latitude: f64,
longitude: f64,
) -> Result<String, NightFuryError>
pub async fn set_geolocation( &self, latitude: f64, longitude: f64, ) -> Result<String, NightFuryError>
Override the browser’s reported geolocation.
Sourcepub async fn emulate_media_feature(
&self,
name: &str,
value: &str,
) -> Result<String, NightFuryError>
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).
Sourcepub async fn emulate_media_type(
&self,
media: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn emulate_timezone(
&self,
timezone_id: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn emulate_locale(
&self,
locale: &str,
) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn subscribe_events(
&self,
buffer: usize,
) -> Result<Receiver<PageEvent>, NightFuryError>
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:?}");
}
});Sourcepub async fn subscribe_raw_cdp_event<T>(
&self,
buffer: usize,
) -> Result<Receiver<T>, NightFuryError>
pub async fn subscribe_raw_cdp_event<T>( &self, buffer: usize, ) -> Result<Receiver<T>, NightFuryError>
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
impl BrowserSession
Sourcepub async fn scroll(&self, pixels: i32) -> Result<String, NightFuryError>
pub async fn scroll(&self, pixels: i32) -> Result<String, NightFuryError>
Scroll the page. Positive pixels = scroll down; negative = scroll up.
Sourcepub async fn scroll_to_element(
&self,
selector: &str,
) -> Result<String, NightFuryError>
pub async fn scroll_to_element( &self, selector: &str, ) -> Result<String, NightFuryError>
Scroll an element into the viewport.
Sourcepub async fn scroll_element(
&self,
selector: &str,
pixels: i32,
) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn click_human(
&self,
selector: Selector,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn type_human(
&self,
selector: Selector,
text: &str,
typos: bool,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn scroll_human(&self, pixels: i32) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn click_with_timeout(
&self,
selector: Selector,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn click(&self, selector: Selector) -> Result<String, NightFuryError>
pub async fn click(&self, selector: Selector) -> Result<String, NightFuryError>
Click an element identified by selector.
Sourcepub async fn dbl_click_with_timeout(
&self,
selector: Selector,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn dbl_click(
&self,
selector: Selector,
) -> Result<String, NightFuryError>
pub async fn dbl_click( &self, selector: Selector, ) -> Result<String, NightFuryError>
Double-click an element. Accepts the same selector types as click.
Sourcepub async fn dbl_click_by_ref(
&self,
idx: usize,
) -> Result<String, NightFuryError>
pub async fn dbl_click_by_ref( &self, idx: usize, ) -> Result<String, NightFuryError>
Double-click an element by @ref index from the last snapshot.
Sourcepub async fn type_text_with_timeout(
&self,
selector: Selector,
text: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn type_text(
&self,
selector: Selector,
text: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn key_press(&self, key: &str) -> Result<String, NightFuryError>
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.
Sourcepub async fn hover_with_timeout(
&self,
selector: Selector,
timeout: Duration,
) -> Result<String, NightFuryError>
pub async fn hover_with_timeout( &self, selector: Selector, timeout: Duration, ) -> Result<String, NightFuryError>
Hover over an element, retrying on ElementNotFound until timeout expires.
Sourcepub async fn hover(&self, selector: Selector) -> Result<String, NightFuryError>
pub async fn hover(&self, selector: Selector) -> Result<String, NightFuryError>
Hover over an element (triggers mousemove and CSS :hover states).
Sourcepub async fn select_with_timeout(
&self,
selector: Selector,
value: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn select(
&self,
selector: Selector,
value: &str,
) -> Result<String, NightFuryError>
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).
Sourcepub async fn check_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
pub async fn check_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>
Check a checkbox, retrying on ElementNotFound until timeout expires.
Sourcepub async fn check(&self, selector: &str) -> Result<String, NightFuryError>
pub async fn check(&self, selector: &str) -> Result<String, NightFuryError>
Ensure a checkbox or radio button is checked. No-op if already checked.
Sourcepub async fn uncheck_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
pub async fn uncheck_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>
Uncheck a checkbox, retrying on ElementNotFound until timeout expires.
Sourcepub async fn uncheck(&self, selector: &str) -> Result<String, NightFuryError>
pub async fn uncheck(&self, selector: &str) -> Result<String, NightFuryError>
Ensure a checkbox is unchecked. No-op if already unchecked.
Sourcepub async fn drag_to_with_timeout(
&self,
source: Selector,
target: Selector,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn drag_to(
&self,
source: Selector,
target: Selector,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn drag_to_by_ref(
&self,
source_idx: usize,
target_idx: usize,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn mouse_move(&self, x: f64, y: f64) -> Result<String, NightFuryError>
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.
Sourcepub async fn mouse_wheel(
&self,
delta_x: f64,
delta_y: f64,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn mouse_down(
&self,
button: MouseButton,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn mouse_up(
&self,
button: MouseButton,
) -> Result<String, NightFuryError>
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
impl BrowserSession
Navigate to a URL. Call snapshot() afterwards to observe the page.
Sourcepub async fn back(&self) -> Result<String, NightFuryError>
pub async fn back(&self) -> Result<String, NightFuryError>
Navigate to the previous page in browser history.
Sourcepub async fn forward(&self) -> Result<String, NightFuryError>
pub async fn forward(&self) -> Result<String, NightFuryError>
Navigate to the next page in browser history.
Sourcepub async fn reload(&self) -> Result<String, NightFuryError>
pub async fn reload(&self) -> Result<String, NightFuryError>
Reload the current page.
Sourcepub async fn get_url(&self) -> Result<String, NightFuryError>
pub async fn get_url(&self) -> Result<String, NightFuryError>
Return the current page URL without a full snapshot.
Sourcepub async fn get_title(&self) -> Result<String, NightFuryError>
pub async fn get_title(&self) -> Result<String, NightFuryError>
Return the current page title without a full snapshot.
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
impl BrowserSession
Sourcepub async fn get_text_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
pub async fn get_text_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>
Return the innerText, retrying on ElementNotFound until timeout expires.
Sourcepub async fn get_text(&self, selector: &str) -> Result<String, NightFuryError>
pub async fn get_text(&self, selector: &str) -> Result<String, NightFuryError>
Return the innerText of an element identified by CSS selector.
Sourcepub async fn get_value_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_value(&self, selector: &str) -> Result<String, NightFuryError>
pub async fn get_value(&self, selector: &str) -> Result<String, NightFuryError>
Return the .value property of an input/textarea/select element.
Sourcepub async fn get_attribute_with_timeout(
&self,
selector: &str,
attribute: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_attribute(
&self,
selector: &str,
attribute: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_html_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<String, NightFuryError>
pub async fn get_html_with_timeout( &self, selector: &str, timeout: Duration, ) -> Result<String, NightFuryError>
Return the innerHTML, retrying on ElementNotFound until timeout expires.
Sourcepub async fn get_html(&self, selector: &str) -> Result<String, NightFuryError>
pub async fn get_html(&self, selector: &str) -> Result<String, NightFuryError>
Return the innerHTML of an element.
Sourcepub async fn get_count(&self, selector: &str) -> Result<usize, NightFuryError>
pub async fn get_count(&self, selector: &str) -> Result<usize, NightFuryError>
Return the number of DOM elements matching a CSS selector.
Sourcepub async fn get_box_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<Value, NightFuryError>
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.
Sourcepub async fn get_box(&self, selector: &str) -> Result<Value, NightFuryError>
pub async fn get_box(&self, selector: &str) -> Result<Value, NightFuryError>
Return the bounding box {x, y, width, height} of an element.
Sourcepub async fn is_checked_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<bool, NightFuryError>
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.
Sourcepub async fn is_checked(&self, selector: &str) -> Result<bool, NightFuryError>
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.
Sourcepub async fn is_visible_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<bool, NightFuryError>
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.
Sourcepub async fn is_visible(&self, selector: &str) -> Result<bool, NightFuryError>
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.
Sourcepub async fn is_enabled_with_timeout(
&self,
selector: &str,
timeout: Duration,
) -> Result<bool, NightFuryError>
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.
Sourcepub async fn is_enabled(&self, selector: &str) -> Result<bool, NightFuryError>
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.
Sourcepub async fn wait_for_selector(
&self,
selector: &str,
timeout_ms: u64,
) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn add_route(
&self,
pattern: &str,
action: RouteAction,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn remove_route(
&self,
pattern: &str,
) -> Result<String, NightFuryError>
pub async fn remove_route( &self, pattern: &str, ) -> Result<String, NightFuryError>
Remove a previously added route rule by its pattern.
Sourcepub async fn capture_responses(
&self,
pattern: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_captured_responses(
&self,
) -> Result<Vec<CapturedResponse>, NightFuryError>
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.
Sourcepub async fn clear_routes(&self) -> Result<String, NightFuryError>
pub async fn clear_routes(&self) -> Result<String, NightFuryError>
Remove all route rules (disables Fetch interception entirely).
Source§impl BrowserSession
impl BrowserSession
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.
Return all cookies currently visible to the browser as JSON objects.
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());Return cookies whose domain field matches the given glob pattern.
Pattern semantics:
*.twitter.com— any host ending in.twitter.com(including.twitter.comitself)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).
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.
Sourcepub async fn storage_get(
&self,
storage: StorageKind,
key: Option<&str>,
) -> Result<Value, NightFuryError>
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.
Sourcepub async fn storage_set(
&self,
storage: StorageKind,
key: &str,
value: &str,
) -> Result<String, NightFuryError>
pub async fn storage_set( &self, storage: StorageKind, key: &str, value: &str, ) -> Result<String, NightFuryError>
Write a key/value pair to localStorage or sessionStorage.
Sourcepub async fn storage_clear(
&self,
storage: StorageKind,
) -> Result<String, NightFuryError>
pub async fn storage_clear( &self, storage: StorageKind, ) -> Result<String, NightFuryError>
Clear all entries in localStorage or sessionStorage.
Sourcepub async fn clipboard_write(
&self,
text: &str,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn clipboard_read(&self) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn new_tab(&self, url: Option<&str>) -> Result<usize, NightFuryError>
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.
Sourcepub async fn switch_tab(&self, idx: usize) -> Result<String, NightFuryError>
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.
Sourcepub async fn list_tabs(&self) -> Result<Vec<TabInfo>, NightFuryError>
pub async fn list_tabs(&self) -> Result<Vec<TabInfo>, NightFuryError>
Return metadata for every open tab.
Sourcepub async fn close_tab(
&self,
idx: Option<usize>,
) -> Result<String, NightFuryError>
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.
Sourcepub async fn bring_to_front(&self) -> Result<(), NightFuryError>
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
impl BrowserSession
Sourcepub async fn tap(&self, x: f64, y: f64) -> Result<String, NightFuryError>
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.
Sourcepub async fn swipe(
&self,
start_x: f64,
start_y: f64,
end_x: f64,
end_y: f64,
) -> Result<String, NightFuryError>
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
impl BrowserSession
Sourcepub async fn enable_ws_capture(&self) -> Result<String, NightFuryError>
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.
Sourcepub async fn get_ws_messages(&self) -> Result<Vec<WsMessage>, NightFuryError>
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
impl BrowserSession
Sourcepub fn builder() -> SessionBuilder
pub fn builder() -> SessionBuilder
Create a SessionBuilder to configure and launch a new browser.
Sourcepub fn from_sender(tx: Sender<BrowserCmd>) -> BrowserSession
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>.
Sourcepub fn set_auto_wait(&mut self, timeout: Option<Duration>)
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).
Sourcepub fn with_auto_wait(self, timeout: Duration) -> BrowserSession
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.
Sourcepub fn actions(&self) -> ActionChain<'_>
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
impl Clone for BrowserSession
Source§fn clone(&self) -> BrowserSession
fn clone(&self) -> BrowserSession
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more