pub struct ChromeBrowser { /* private fields */ }Implementations§
Source§impl ChromeBrowser
impl ChromeBrowser
Sourcepub async fn new(config: ChromeConfig) -> ChromeBrowser
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;Sourcepub async fn open_url(
&mut self,
url: &str,
wait: Option<ReadinessState>,
context_id: Option<BrowsingContext>,
) -> Result<NavigateResult, OpenUrlError>
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 towait- 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?;Sourcepub async fn create_context_bidi(
&mut self,
context_type: Option<CreateType>,
reference_context: Option<&Context>,
background: bool,
) -> Result<Context, CommandResultError>
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)
Sourcepub 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>
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 returnserialization_options- Optional serialization options for node datastart_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?;Sourcepub 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>
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);
}Sourcepub 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>
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 locatorcontext_id- Optional browsing contexttimeout_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());
}Sourcepub 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>
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!");
}Sourcepub async fn send_bidi_command(
&mut self,
command: CommandData,
) -> Result<ResultData, SessionSendError>
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?;Sourcepub 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,
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,
Sourcepub 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>
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>
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 eventbrowsing_contexts- Optional list of browsing context IDs to filter eventsuser_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?;Sourcepub async fn add_event_handler<F, R>(
&mut self,
events: HashSet<&str>,
handler: F,
handler_id: Option<String>,
) -> String
pub async fn add_event_handler<F, R>( &mut self, events: HashSet<&str>, handler: F, handler_id: Option<String>, ) -> String
Add an event handler without sending a subscription command Returns the handler ID (either provided or generated)
Sourcepub 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>
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>
Sourcepub fn get_config(&self) -> &ChromeConfig
pub fn get_config(&self) -> &ChromeConfig
Get a reference to the Chrome configuration
Sourcepub fn get_browser_process(&self) -> &Option<Process>
pub fn get_browser_process(&self) -> &Option<Process>
Get a reference to the Chrome browser process
Sourcepub fn mouse(&self) -> &BidiMouse<WebsocketConnectionTransport>
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?;Sourcepub fn human_mouse(
&self,
) -> &HumanMouse<BidiMouse<WebsocketConnectionTransport>>
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?;Sourcepub fn keyboard(&self) -> &Keyboard<WebsocketConnectionTransport>
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?;Sourcepub async fn move_mouse_to_node_bidi(
&mut self,
node: &mut ChromeNode,
context: Option<&BrowsingContext>,
scroll_into_view: bool,
) -> Result<(), MouseInputError>
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 tocontext- Optional browsing contextscroll_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?;Sourcepub async fn click_on_node_bidi(
&mut self,
node: &mut ChromeNode,
context: Option<&BrowsingContext>,
options: Option<MouseClickOptions>,
) -> Result<(), MouseInputError>
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?;Sourcepub 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>
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
Sourcepub async fn remove_preload_script_bidi(
&mut self,
script: String,
) -> Result<(), EvaluateResultError>
pub async fn remove_preload_script_bidi( &mut self, script: String, ) -> Result<(), EvaluateResultError>
Remove a preload script by its ID
Sourcepub 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>
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?;Sourcepub async fn emulate_timezone(
&mut self,
timezone: Option<String>,
contexts: Option<Vec<BrowsingContext>>,
user_contexts: Option<Vec<String>>,
) -> Result<(), EmulationError>
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?;Sourcepub 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>
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 authenticationpassword- The password for HTTP authenticationurl_patterns- Optional URL patterns to apply authentication tocontexts- 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?;pub fn get_active_context_id( &self, ) -> Result<BrowsingContext, ContextIndexError>
Sourcepub async fn end_bidi_session(&mut self) -> Result<(), SessionSendError>
pub async fn end_bidi_session(&mut self) -> Result<(), SessionSendError>
Trait Implementations§
Source§impl BidiDrive<WebsocketConnectionTransport> for ChromeBrowser
impl BidiDrive<WebsocketConnectionTransport> for ChromeBrowser
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§
impl Freeze for ChromeBrowser
impl !RefUnwindSafe for ChromeBrowser
impl Send for ChromeBrowser
impl Sync for ChromeBrowser
impl Unpin for ChromeBrowser
impl !UnwindSafe for ChromeBrowser
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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