pub struct SessionHandle {
    pub client: Arc<dyn HttpClient + Send + Sync>,
    /* private fields */
}
Expand description

The SessionHandle contains a shared reference to the HTTP client to allow sending commands to the underlying WebDriver.

Fields§

§client: Arc<dyn HttpClient + Send + Sync>

The HTTP client for performing webdriver requests.

Implementations§

source§

impl SessionHandle

source

pub async fn get_alert_text(&self) -> WebDriverResult<String>

Get the active alert text.

§Example:
let text = driver.get_alert_text().await?;
source

pub async fn dismiss_alert(&self) -> WebDriverResult<()>

Dismiss the active alert.

§Example:
driver.dismiss_alert().await?;
source

pub async fn accept_alert(&self) -> WebDriverResult<()>

Accept the active alert.

§Example:
driver.accept_alert().await?;
source

pub async fn send_alert_text( &self, keys: impl Into<TypingData> ) -> WebDriverResult<()>

Send the specified keys to the active alert.

§Example:

You can specify anything that implements Into<TypingData>. This includes &str and String.

driver.send_alert_text("selenium").await?;
driver.accept_alert().await?;

You can also send special key combinations like this:

driver.send_alert_text(Key::Control + "a").await?;
driver.send_alert_text("thirtyfour").await?;
source§

impl SessionHandle

source

pub fn new( client: Arc<dyn HttpClient + Send + Sync>, server_url: Url, session_id: SessionId ) -> WebDriverResult<Self>

Create new SessionHandle.

source

pub fn session_id(&self) -> &SessionId

The session id for this webdriver session.

source

pub fn config(&self) -> &WebDriverConfig

The configuration used by this instance.

NOTE: It’s sometimes useful to have separate instances pointing at the same underlying browser session but using different configurations. See WebDriver::clone_with_config() for more details.

source

pub async fn cmd( &self, command: impl FormatRequestData ) -> WebDriverResult<CmdResponse>

Send the specified command to the webdriver server.

source

pub async fn status(&self) -> WebDriverResult<WebDriverStatus>

Get the WebDriver status.

§Example
let caps = DesiredCapabilities::chrome();
let mut driver = WebDriver::new("http://localhost:4444", caps).await?;
let status = driver.status().await?;
source

pub async fn close_window(&self) -> WebDriverResult<()>

Close the current window or tab. This will close the session if no other windows exist.

§Example:
// Open a new tab.
driver.new_tab().await?;

// Get window handles and switch to the new tab.
let handles = driver.windows().await?;
driver.switch_to_window(handles[1].clone()).await?;

// We are now controlling the new tab.
driver.goto("https://www.rust-lang.org").await?;

// Close the tab. This will return to the original tab.
driver.close_window().await?;
source

pub async fn close(&self) -> WebDriverResult<()>

👎Deprecated since 0.30.0: This method has been renamed to close_window()

Close the current window or tab. This will close the session if no other windows exist.

source

pub async fn goto(&self, url: impl Into<String>) -> WebDriverResult<()>

Navigate to the specified URL.

§Example:
driver.goto("https://www.rust-lang.org").await?;
source

pub async fn get(&self, url: impl Into<String>) -> WebDriverResult<()>

Navigate to the specified URL. Alias of goto().

source

pub async fn current_url(&self) -> WebDriverResult<Url>

Get the current URL.

source

pub async fn source(&self) -> WebDriverResult<String>

Get the page source as a String.

source

pub async fn page_source(&self) -> WebDriverResult<String>

👎Deprecated since 0.30.0: This method has been renamed to source()

Get the page source as a String.

source

pub async fn title(&self) -> WebDriverResult<String>

Get the page title as a String.

source

pub async fn find(self: &Arc<Self>, by: By) -> WebDriverResult<WebElement>

Search for an element on the current page using the specified selector.

NOTE: For more powerful element queries including polling and filters, see the WebDriver::query method instead.

§Example:
let elem_button = driver.find(By::Id("my-element-id")).await?;
let elem_text = driver.find(By::Name("my-text-input")).await?;
source

pub async fn find_element( self: &Arc<Self>, by: By ) -> WebDriverResult<WebElement>

👎Deprecated since 0.30.0: This method has been renamed to find()

Search for an element on the current page using the specified selector.

source

pub async fn find_all( self: &Arc<Self>, by: By ) -> WebDriverResult<Vec<WebElement>>

Search for all elements on the current page that match the specified selector.

NOTE: For more powerful element queries including polling and filters, see the WebDriver::query method instead.

§Example:
let elems = driver.find_all(By::ClassName("section")).await?;
for elem in elems {
    assert!(elem.attr("class").await?.expect("Missing class on element").contains("section"));
}
source

pub async fn find_elements( self: &Arc<Self>, by: By ) -> WebDriverResult<Vec<WebElement>>

👎Deprecated since 0.30.0: This method has been renamed to find_all()

Search for all elements on the current page that match the specified selector.

source

pub async fn execute( self: &Arc<Self>, script: impl Into<String>, args: Vec<Value> ) -> WebDriverResult<ScriptRet>

Execute the specified Javascript synchronously and return the result.

§Example:
let ret = driver.execute(r#"
    let elem = document.getElementById("button1");
    elem.click();
    return elem;
    "#, Vec::new()
).await?;
let elem_out: WebElement = ret.element()?;

To supply an element as an input argument to a script, use WebElement::to_json as follows:

§Example:
let elem = driver.find(By::Id("button1")).await?;
let ret = driver.execute(r#"
    arguments[0].innerHTML = arguments[1];
    return arguments[0];
    "#, vec![elem.to_json()?, serde_json::to_value("TESTING")?]
).await?;
let elem_out = ret.element()?;
assert_eq!(elem_out.element_id(), elem.element_id());
assert_eq!(elem_out.text().await?, "TESTING");
source

pub async fn execute_script( self: &Arc<Self>, script: impl Into<String>, args: Vec<Value> ) -> WebDriverResult<ScriptRet>

👎Deprecated since 0.30.0: This method has been renamed to execute()

Execute the specified Javascript synchronously and return the result.

source

pub async fn execute_async( self: &Arc<Self>, script: impl Into<String>, args: Vec<Value> ) -> WebDriverResult<ScriptRet>

Execute the specified Javascrypt asynchronously and return the result.

§Example:
let ret = driver.execute_async(r#"
    // Selenium automatically provides an extra argument which is a
    // function that receives the return value(s).
    let done = arguments[0];
    window.setTimeout(() => {
        let elem = document.getElementById("button1");
        elem.click();
        done(elem);
    }, 1000);
    "#, Vec::new()
).await?;
let elem_out: WebElement = ret.element()?;

To supply an element as an input argument to a script, use WebElement::to_json as follows:

§Example:
let elem = driver.find(By::Id("button1")).await?;
let args = vec![elem.to_json()?, serde_json::to_value("TESTING")?];
let ret = driver.execute_async(r#"
    // Selenium automatically provides an extra argument which is a
    // function that receives the return value(s).
    let done = arguments[2];
    window.setTimeout(() => {
        arguments[0].innerHTML = arguments[1];
        done(arguments[0]);
    }, 1000);
    "#, args
).await?;
let elem_out = ret.element()?;
assert_eq!(elem_out.element_id(), elem.element_id());
assert_eq!(elem_out.text().await?, "TESTING");
source

pub async fn execute_script_async( self: &Arc<Self>, script: impl Into<String>, args: Vec<Value> ) -> WebDriverResult<ScriptRet>

👎Deprecated since 0.30.0: This method has been renamed to execute_async()

Execute the specified Javascrypt asynchronously and return the result.

source

pub async fn window(&self) -> WebDriverResult<WindowHandle>

Get the current window handle.

§Example:
// Get the current window handle.
let handle = driver.window().await?;

// Open a new tab.
driver.new_tab().await?;

// Get window handles and switch to the new tab.
let handles = driver.windows().await?;
driver.switch_to_window(handles[1].clone()).await?;

// We are now controlling the new tab.
driver.goto("https://www.rust-lang.org/").await?;
assert_ne!(driver.window().await?, handle);

// Switch back to original tab.
driver.switch_to_window(handle.clone()).await?;
assert_eq!(driver.window().await?, handle);
source

pub async fn current_window_handle(&self) -> WebDriverResult<WindowHandle>

👎Deprecated since 0.30.0: This method has been renamed to window()

Get the current window handle.

source

pub async fn windows(&self) -> WebDriverResult<Vec<WindowHandle>>

Get all window handles for the current session.

§Example:
assert_eq!(driver.windows().await?.len(), 1);
// Open a new tab.
driver.new_tab().await?;

// Get window handles and switch to the new tab.
let handles = driver.windows().await?;
assert_eq!(handles.len(), 2);
driver.switch_to_window(handles[1].clone()).await?;
source

pub async fn window_handles(&self) -> WebDriverResult<Vec<WindowHandle>>

👎Deprecated since 0.30.0: This method has been renamed to windows()

Get all window handles for the current session.

source

pub async fn maximize_window(&self) -> WebDriverResult<()>

Maximize the current window.

§Example:
driver.maximize_window().await?;
source

pub async fn minimize_window(&self) -> WebDriverResult<()>

Minimize the current window.

§Example:
driver.minimize_window().await?;
source

pub async fn fullscreen_window(&self) -> WebDriverResult<()>

Make the current window fullscreen.

§Example:
driver.fullscreen_window().await?;
source

pub async fn get_window_rect(&self) -> WebDriverResult<Rect>

Get the current window rectangle, in pixels.

The returned Rect struct has members x, y, width, height, all i32.

§Example:
use thirtyfour::Rect;
driver.set_window_rect(0, 0, 600, 400).await?;
let rect = driver.get_window_rect().await?;
assert_eq!(rect, Rect::new(0, 0, 600, 400));
source

pub async fn set_window_rect( &self, x: u32, y: u32, width: u32, height: u32 ) -> WebDriverResult<()>

Set the current window rectangle, in pixels.

driver.set_window_rect(0, 0, 500, 400).await?;
source

pub async fn back(&self) -> WebDriverResult<()>

Go back. This is equivalent to clicking the browser’s back button.

§Example:
driver.back().await?;
source

pub async fn forward(&self) -> WebDriverResult<()>

Go forward. This is equivalent to clicking the browser’s forward button.

§Example:
let caps = DesiredCapabilities::chrome();
driver.forward().await?;
source

pub async fn refresh(&self) -> WebDriverResult<()>

Refresh the current page.

§Example:
driver.refresh().await?;
source

pub async fn get_timeouts(&self) -> WebDriverResult<TimeoutConfiguration>

Get all timeouts for the current session.

§Example:
use thirtyfour::TimeoutConfiguration;
use std::time::Duration;
let timeouts = driver.get_timeouts().await?;
println!("Page load timeout = {:?}", timeouts.page_load());
source

pub async fn update_timeouts( &self, timeouts: TimeoutConfiguration ) -> WebDriverResult<()>

Set all timeouts for the current session.

NOTE: Setting the implicit wait timeout to a non-zero value will interfere with the use of WebDriver::query and WebElement::wait_until. It is therefore recommended to use these methods (which provide polling and explicit waits) instead rather than increasing the implicit wait timeout.

§Example:
use thirtyfour::TimeoutConfiguration;
use std::time::Duration;
// Setting timeouts to None means those timeout values will not be updated.
let timeouts = TimeoutConfiguration::new(None, Some(Duration::new(11, 0)), None);
driver.update_timeouts(timeouts).await?;
source

pub async fn set_timeouts( &self, timeouts: TimeoutConfiguration ) -> WebDriverResult<()>

👎Deprecated since 0.30.0: This method has been renamed to update_timeouts()

Set all timeouts for the current session.

source

pub async fn set_implicit_wait_timeout( &self, time_to_wait: Duration ) -> WebDriverResult<()>

Set the implicit wait timeout.

This is how long the WebDriver will wait when querying elements. By default this is set to 0 seconds.

NOTE: Setting the implicit wait timeout to a non-zero value will interfere with the use of WebDriver::query and WebElement::wait_until. It is therefore recommended to use these methods (which provide polling and explicit waits) instead rather than increasing the implicit wait timeout.

§Example:
use thirtyfour::TimeoutConfiguration;
use std::time::Duration;
let delay = Duration::new(11, 0);
driver.set_implicit_wait_timeout(delay).await?;
source

pub async fn set_script_timeout( &self, time_to_wait: Duration ) -> WebDriverResult<()>

Set the script timeout.

This is how long the WebDriver will wait for a Javascript script to execute. By default this is set to 60 seconds.

§Example:
use thirtyfour::TimeoutConfiguration;
use std::time::Duration;
let delay = Duration::new(11, 0);
driver.set_script_timeout(delay).await?;
source

pub async fn set_page_load_timeout( &self, time_to_wait: Duration ) -> WebDriverResult<()>

Set the page load timeout.

This is how long the WebDriver will wait for the page to finish loading. By default this is set to 60 seconds.

§Example:
use thirtyfour::TimeoutConfiguration;
use std::time::Duration;
let delay = Duration::new(11, 0);
driver.set_page_load_timeout(delay).await?;
source

pub fn action_chain(self: &Arc<SessionHandle>) -> ActionChain

Create a new action chain for this session.

Action chains can be used to simulate more complex user input actions involving key combinations, mouse movements, mouse click, right-click, and more.

§Example:
let elem_text = driver.find(By::Name("input1")).await?;
let elem_button = driver.find(By::Id("button-set")).await?;

driver.action_chain()
    .send_keys_to_element(&elem_text, "thirtyfour")
    .move_to_element_center(&elem_button)
    .click()
    .perform()
    .await?;
source

pub async fn get_all_cookies(&self) -> WebDriverResult<Vec<Cookie>>

Get all cookies.

§Example:
let cookies = driver.get_all_cookies().await?;
for cookie in &cookies {
    println!("Got cookie: {}", cookie.value);
}
source

pub async fn get_cookies(&self) -> WebDriverResult<Vec<Cookie>>

👎Deprecated since 0.30.0: This method has been renamed to get_all_cookies()

Get all cookies.

Get the specified cookie.

§Example:
let cookie = driver.get_named_cookie("key").await?;
println!("Got cookie: {}", cookie.value);
👎Deprecated since 0.30.0: This method has been renamed to get_named_cookie()

Get the specified cookie.

Delete the specified cookie.

§Example:
driver.delete_cookie("key").await?;
source

pub async fn delete_all_cookies(&self) -> WebDriverResult<()>

Delete all cookies.

§Example:
driver.delete_all_cookies().await?;

Add the specified cookie.

§Example:
driver.goto("https://wikipedia.org").await?;
let mut cookie = Cookie::new("key", "value");
cookie.set_domain("wikipedia.org");
cookie.set_path("/");
cookie.set_same_site(SameSite::Lax);
driver.add_cookie(cookie.clone()).await?;
source

pub async fn screenshot_as_png_base64(&self) -> WebDriverResult<String>

Take a screenshot of the current window and return it as PNG, base64 encoded.

source

pub async fn screenshot_as_png(&self) -> WebDriverResult<Vec<u8>>

Take a screenshot of the current window and return it as PNG bytes.

source

pub async fn screenshot(&self, path: &Path) -> WebDriverResult<()>

Take a screenshot of the current window and write it to the specified filename.

source

pub fn switch_to(self: &Arc<SessionHandle>) -> SwitchTo

👎Deprecated since 0.30.0: SwitchTo has been deprecated. Use WebDriver::switch_to_*() methods instead

Return a SwitchTo struct for switching to another window or frame.

source

pub async fn set_window_name( self: &Arc<SessionHandle>, window_name: impl Into<String> ) -> WebDriverResult<()>

Set the current window name.

Useful for switching between windows/tabs using WebDriver::switch_to_named_window

§Example:
// Get the current window handle.
let handle = driver.window().await?;
driver.set_window_name("main").await?;

// Open a new tab.
let new_handle = driver.new_tab().await?;

// Get window handles and switch to the new tab.
driver.switch_to_window(new_handle).await?;

// We are now controlling the new tab.
driver.goto("https://www.rust-lang.org").await?;
assert_ne!(driver.window().await?, handle);

// Switch back to original tab using window name.
driver.switch_to_named_window("main").await?;
assert_eq!(driver.window().await?, handle);
source

pub async fn in_new_tab<F, Fut, T>(&self, f: F) -> WebDriverResult<T>
where F: FnOnce() -> Fut + Send, Fut: Future<Output = WebDriverResult<T>> + Send, T: Send,

Execute the specified function in a new browser tab, closing the tab when complete.

The return value will be that of the supplied function, unless an error occurs while opening or closing the tab.

let window_title = driver.in_new_tab(|| async {
    driver.goto("https://www.google.com").await?;
    driver.title().await
}).await?;
assert_eq!(window_title, "Google");
source§

impl SessionHandle

source

pub async fn active_element( self: &Arc<SessionHandle> ) -> WebDriverResult<WebElement>

Return the element with focus, or the <body> element if nothing has focus.

§Example:
// If no element has focus, active_element() will return the body tag.
let active_elem = driver.active_element().await?;
assert_eq!(active_elem.tag_name().await?, "body");

// Now let's manually focus an element and try active_element() again.
let elem = driver.find(By::Id("my-element-id")).await?;
elem.focus().await?;

// And fetch the active element again.
let active_elem = driver.active_element().await?;
assert_eq!(active_elem.element_id(), elem.element_id());
source

pub async fn enter_default_frame(&self) -> WebDriverResult<()>

Switch to the default frame.

§Example:
// Enter the first iframe.
driver.enter_frame(0).await?;
// We are now inside the iframe.
driver.find(By::Id("button1")).await?;
driver.enter_default_frame().await?;
// We are now back in the original window.
source

pub async fn enter_frame(&self, frame_number: u16) -> WebDriverResult<()>

Switch to an iframe by index. The first iframe on the page has index 0.

§Example:
// Enter the first iframe.
driver.enter_frame(0).await?;
// We can now search for elements within the iframe.
let elem = driver.find(By::Id("button1")).await?;
elem.click().await?;
source

pub async fn enter_parent_frame(&self) -> WebDriverResult<()>

Switch to the parent frame.

§Example:
// Find the iframe element and enter the iframe.
let elem_iframe = driver.find(By::Id("iframeid1")).await?;
elem_iframe.enter_frame().await?;
// We can now search for elements within the iframe.
let elem = driver.find(By::Id("button1")).await?;
elem.click().await?;
// Now switch back to the parent frame.
driver.enter_parent_frame().await?;
// We are now back in the parent document.
source

pub async fn switch_to_window( &self, handle: WindowHandle ) -> WebDriverResult<()>

Switch to the specified window.

§Example:
// Open a new tab.
driver.new_tab().await?;

// Get window handles and switch to the new tab.
let handles = driver.windows().await?;
driver.switch_to_window(handles[1].clone()).await?;

// We are now controlling the new tab.
driver.goto("https://www.rust-lang.org").await?;
source

pub async fn switch_to_named_window( self: &Arc<SessionHandle>, name: &str ) -> WebDriverResult<()>

Switch to the window with the specified name. This uses the window.name property. You can set a window name via WebDriver::set_window_name("someName").await?.

§Example:
// Set main window name so we can switch back easily.
driver.set_window_name("mywindow").await?;

// Open a new tab.
driver.new_tab().await?;

// Get window handles and switch to the new tab.
let handles = driver.windows().await?;
driver.switch_to_window(handles[1].clone()).await?;

// We are now controlling the new tab.
assert_eq!(driver.title().await?, "");
driver.switch_to_named_window("mywindow").await?;

// We are now back in the original tab.
source

pub async fn new_window(&self) -> WebDriverResult<WindowHandle>

Switch to a new window.

§Example:
// Open a new window.
let handle = driver.new_window().await?;
source

pub async fn new_tab(&self) -> WebDriverResult<WindowHandle>

Switch to a new tab.

§Example:
// Open a new tab in the current window.
let handle = driver.new_tab().await?;

Trait Implementations§

source§

impl Clone for SessionHandle

source§

fn clone(&self) -> SessionHandle

Returns a copy 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 SessionHandle

source§

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

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> 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> ToOwned for T
where T: Clone,

§

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

§

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

§

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