Skip to main content

ChromeBrowser

Struct ChromeBrowser 

Source
pub struct ChromeBrowser { /* private fields */ }

Implementations§

Source§

impl ChromeBrowser

Source

pub async fn new(config: ChromeConfig) -> ChromeBrowser

Creates a new Chrome browser instance with the specified configuration.

This method initializes chromedriver, establishes a WebDriver BiDi session, and optionally launches or connects to a Chrome browser instance.

§Arguments
  • config - Chrome configuration including driver path, browser options, and capabilities
§Examples
use rustenium::browsers::{ChromeBrowser, ChromeConfig};

let config = ChromeConfig {
    driver_executable_path: "chromedriver".to_string(),
    ..Default::default()
};

let mut browser = ChromeBrowser::new(config).await;
Source

pub async fn open_url( &mut self, url: &str, wait: Option<ReadinessState>, context_id: Option<BrowsingContext>, ) -> Result<NavigateResult, OpenUrlError>

Navigates to the specified URL.

§Arguments
  • url - The URL to navigate to
  • wait - Optional readiness state to wait for (e.g., ReadinessState::Complete)
  • context_id - Optional browsing context ID (uses active context if None)
§Examples
// Navigate to a URL
browser.open_url("https://example.com", None, None).await?;

// Wait for page to fully load
use rustenium_bidi_commands::browsing_context::types::ReadinessState;
browser.open_url(
    "https://example.com",
    Some(ReadinessState::Complete),
    None
).await?;
Source

pub async fn create_context_bidi( &mut self, context_type: Option<CreateType>, reference_context: Option<&Context>, background: bool, ) -> Result<Context, CommandResultError>

Create a new browsing context (tab or window)

Source

pub async fn find_nodes( &mut self, locator: Locator, context_id: Option<BrowsingContext>, max_node_count: Option<u64>, serialization_options: Option<SerializationOptions>, start_nodes: Option<Vec<SharedReference>>, ) -> Result<Vec<ChromeNode<WebsocketConnectionTransport>>, FindNodesError>

Finds all elements matching the given locator.

§Arguments
  • locator - Element locator (CSS selector, XPath, etc.)
  • context_id - Optional browsing context (uses active context if None)
  • max_node_count - Optional maximum number of nodes to return
  • serialization_options - Optional serialization options for node data
  • start_nodes - Optional starting nodes for the search
§Examples
// Find all buttons using CSS selector
let buttons = browser.find_nodes(css!("button"), None, None, None, None).await?;

// Find up to 5 links
let links = browser.find_nodes(css!("a"), None, Some(5), None, None).await?;

// Find using XPath
let elements = browser.find_nodes(xpath!("//div[@class='content']"), None, None, None, None).await?;
Source

pub async fn find_node( &mut self, locator: Locator, context_id: Option<BrowsingContext>, max_node_count: Option<u64>, serialization_options: Option<SerializationOptions>, start_nodes: Option<Vec<SharedReference>>, ) -> Result<Option<ChromeNode<WebsocketConnectionTransport>>, FindNodesError>

Finds the first element matching the given locator.

Returns None if no matching element is found.

§Examples
// Find the submit button
if let Some(button) = browser.find_node(css!("#submit"), None, None, None, None).await? {
    let text = button.get_inner_text().await;
    println!("Button text: {}", text);
}
Source

pub async fn wait_for_nodes( &mut self, locator: Locator, context_id: Option<BrowsingContext>, timeout_ms: Option<u64>, poll_interval_ms: Option<u64>, ) -> Result<Vec<ChromeNode<WebsocketConnectionTransport>>, FindNodesError>

Waits for elements matching the locator to appear, with a configurable timeout.

Polls for elements at regular intervals until they appear or the timeout is reached.

§Arguments
  • locator - Element locator
  • context_id - Optional browsing context
  • timeout_ms - Timeout in milliseconds (default: 4000ms)
  • poll_interval_ms - Polling interval in milliseconds (default: timeout/6)
§Examples
// Wait up to 5 seconds for dynamic content to load
let elements = browser.wait_for_nodes(
    css!(".dynamic-content"),
    None,
    Some(5000),
    None,
).await?;

if !elements.is_empty() {
    println!("Found {} elements", elements.len());
}
Source

pub async fn wait_for_node( &mut self, locator: Locator, context_id: Option<BrowsingContext>, timeout_ms: Option<u64>, poll_interval_ms: Option<u64>, ) -> Result<Option<ChromeNode<WebsocketConnectionTransport>>, FindNodesError>

Waits for a single element matching the locator to appear.

Returns None if no matching element appears within the timeout.

§Examples
// Wait for login button to appear
if let Some(button) = browser.wait_for_node(
    css!("#login-btn"),
    None,
    Some(3000), // 3 second timeout
    None,
).await? {
    println!("Login button appeared!");
}
Source

pub async fn send_bidi_command( &mut self, command: CommandData, ) -> Result<ResultData, SessionSendError>

Sends a raw WebDriver BiDi command.

This is a low-level method for sending custom BiDi commands not covered by the high-level API.

§Examples
// Send a custom BiDi command
let command = CommandData::/*...*/;
let result = browser.send_bidi_command(command).await?;
Source

pub async fn on_request_bidi<F, Fut>( &mut self, handler: F, url_patterns: Option<Vec<UrlPattern>>, contexts: Option<Vec<String>>, ) -> Result<(), InterceptNetworkError>
where F: Fn(NetworkRequest<WebsocketConnectionTransport>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler to be called for each network request

§Example
browser.on_request_bidi(|request| async move {
    if request.params.base_parameters.request.url.contains("ads") {
        let _ = request.abort().await;
    } else {
        let _ = request.continue_().await;
    }
}, None, None).await?;
Source

pub async fn subscribe_events<F, R>( &mut self, events: HashSet<&str>, handler: F, browsing_contexts: Option<Vec<String>>, user_contexts: Option<Vec<&str>>, ) -> Result<Option<SubscribeResult>, CommandResultError>
where F: FnMut(Event) -> R + Send + Sync + 'static, R: Future<Output = ()> + Send + 'static,

Subscribes to browser events and registers a handler to process them.

§Arguments
  • events - Set of event names to subscribe to (e.g., “browsingContext.load”, “network.responseCompleted”)
  • handler - Async function called for each matching event
  • browsing_contexts - Optional list of browsing context IDs to filter events
  • user_contexts - Optional list of user context IDs
§Examples
// Subscribe to page load events
browser.subscribe_events(
    HashSet::from(["browsingContext.load"]),
    |event| async move {
        println!("Page loaded: {:?}", event);
    },
    None,
    None,
).await?;

// Subscribe to multiple network events
browser.subscribe_events(
    HashSet::from(["network.responseStarted", "network.responseCompleted"]),
    |event| async move {
        println!("Network event: {:?}", event);
    },
    None,
    None,
).await?;
Source

pub async fn add_event_handler<F, R>( &mut self, events: HashSet<&str>, handler: F, handler_id: Option<String>, ) -> String
where F: FnMut(Event) -> R + Send + Sync + 'static, R: Future<Output = ()> + Send + 'static,

Add an event handler without sending a subscription command Returns the handler ID (either provided or generated)

Source

pub async fn evaluate_script_bidi( &mut self, expression: String, await_promise: bool, target: Option<Target>, result_ownership: Option<ResultOwnership>, serialization_options: Option<SerializationOptions>, user_activation: Option<bool>, ) -> Result<EvaluateResultSuccess, EvaluateResultError>

Evaluate a JavaScript expression in the browser context using BiDi

§Example
let result = browser.evaluate_script_bidi(
    "document.title".to_string(),
    false,
    None,
    None,
    None,
    None,
).await?;
Source

pub fn get_config(&self) -> &ChromeConfig

Get a reference to the Chrome configuration

Source

pub fn get_browser_process(&self) -> &Option<Process>

Get a reference to the Chrome browser process

Source

pub fn mouse(&self) -> &BidiMouse<WebsocketConnectionTransport>

Returns a reference to the direct BiDi mouse for precise, instant movements.

§Examples
let mouse = browser.mouse();
mouse.move_to(Point { x: 100.0, y: 200.0 }, &context, None).await?;
mouse.click(None, &context, None).await?;
Source

pub fn human_mouse( &self, ) -> &HumanMouse<BidiMouse<WebsocketConnectionTransport>>

Returns a reference to the human mouse for realistic, human-like movements with Bezier curves and jitter.

§Examples
let human_mouse = browser.human_mouse();
// Moves with natural curve and realistic delays
human_mouse.move_to(Point { x: 300.0, y: 400.0 }, &context, None).await?;
human_mouse.click(None, &context, None).await?;
Source

pub fn keyboard(&self) -> &Keyboard<WebsocketConnectionTransport>

Returns a reference to the keyboard for text input and key presses.

§Examples
let keyboard = browser.keyboard();
keyboard.type_text("Hello, World!", &context).await?;
keyboard.press("Enter", &context).await?;
Source

pub async fn move_mouse_to_node_bidi( &mut self, node: &mut ChromeNode, context: Option<&BrowsingContext>, scroll_into_view: bool, ) -> Result<(), MouseInputError>

Moves the mouse to the center of an element.

§Arguments
  • node - The element to move the mouse to
  • context - Optional browsing context
  • scroll_into_view - Whether to scroll the element into view first
§Examples
let mut button = browser.find_node(css!("#submit"), None, None, None, None).await?.unwrap();
browser.move_mouse_to_node_bidi(&mut button, None, true).await?;
Source

pub async fn click_on_node_bidi( &mut self, node: &mut ChromeNode, context: Option<&BrowsingContext>, options: Option<MouseClickOptions>, ) -> Result<(), MouseInputError>

Clicks on an element (automatically scrolls into view and moves mouse to center).

§Examples
let mut button = browser.find_node(css!("#submit"), None, None, None, None).await?.unwrap();

// Single click
browser.click_on_node_bidi(&mut button, None, None).await?;

// Double click
browser.click_on_node_bidi(
    &mut button,
    None,
    Some(MouseClickOptions {
        count: Some(2),
        ..Default::default()
    })
).await?;
Source

pub async fn add_preload_script_bidi( &mut self, function_declaration: String, arguments: Option<Vec<ChannelValue>>, contexts: Option<Vec<String>>, user_contexts: Option<Vec<String>>, sandbox: Option<String>, ) -> Result<String, EvaluateResultError>

Add a preload script that will be executed in new contexts

Source

pub async fn remove_preload_script_bidi( &mut self, script: String, ) -> Result<(), EvaluateResultError>

Remove a preload script by its ID

Source

pub async fn screenshot( &mut self, context_id: Option<BrowsingContext>, origin: Option<OriginUnion>, format: Option<ImageFormat>, clip: Option<ClipRectangle>, save_path: Option<&str>, ) -> Result<String, ScreenshotError>

Capture a screenshot of the current browsing context If save_path is provided:

  • If it’s a directory, saves with auto-generated filename (screenshot_TIMESTAMP.png)
  • If it’s a file path, saves to that exact location Returns the final path where the file was saved Otherwise, returns the base64-encoded image data
§Example
// Get base64 data
let base64_data = browser.screenshot(None, None, None, None, None).await?;

// Save to specific file
let path = browser.screenshot(None, None, None, None, Some("screenshot.png")).await?;

// Save to directory with auto-generated filename
let path = browser.screenshot(None, None, None, None, Some("./screenshots/")).await?;
Source

pub async fn emulate_timezone( &mut self, timezone: Option<String>, contexts: Option<Vec<BrowsingContext>>, user_contexts: Option<Vec<String>>, ) -> Result<(), EmulationError>

Emulate a timezone for the browsing contexts

§Arguments
  • timezone - Optional timezone ID (e.g., “America/New_York”, “Europe/London”). Pass None to clear the override.
  • contexts - Optional list of browsing context IDs to apply the override to. If None, applies to the active context.
  • user_contexts - Optional list of user context IDs
§Example
// Set timezone to New York
browser.emulate_timezone(Some("America/New_York".to_string()), None, None).await?;

// Clear timezone override
browser.emulate_timezone(None, None, None).await?;
Source

pub async fn authenticate( &mut self, username: impl Into<String> + Send + 'static, password: impl Into<String> + Send + 'static, url_patterns: Option<Vec<UrlPattern>>, contexts: Option<Vec<String>>, ) -> Result<(), InterceptNetworkError>

Set HTTP authentication credentials (similar to Puppeteer’s authenticate)

§Arguments
  • username - The username for HTTP authentication
  • password - The password for HTTP authentication
  • url_patterns - Optional URL patterns to apply authentication to
  • contexts - Optional list of browsing contexts
§Example
// Authenticate for all requests
browser.authenticate("user", "pass", None, None).await?;

// Authenticate for specific URLs
use rustenium_bidi_commands::network::types::UrlPattern;
let patterns = vec![UrlPattern {
    pattern: Some("https://example.com/*".to_string()),
    ..Default::default()
}];
browser.authenticate("user", "pass", Some(patterns), None).await?;
Source

pub fn get_active_context_id( &self, ) -> Result<BrowsingContext, ContextIndexError>

Source

pub async fn end_bidi_session(&mut self) -> Result<(), SessionSendError>

End the BiDi session and clean up resources

§Example
let mut browser = ChromeBrowser::new(config).await;
// ... use browser ...
browser.end_bidi_session().await.unwrap();

Trait Implementations§

Source§

impl BidiDrive<WebsocketConnectionTransport> for ChromeBrowser

Source§

fn start( driver_config: &impl DriverConfiguration, connection_transport_config: &ConnectionTransportConfig, session_connection_type: SessionConnectionType, capabilities: Option<CapabilitiesRequest>, ) -> impl Future<Output = (Arc<TokioMutex<Session<WebsocketConnectionTransport>>>, Process)>

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> 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, 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