Struct headless_chrome::browser::tab::Tab

source ·
pub struct Tab { /* private fields */ }
Expand description

A handle to a single page. Exposes methods for simulating user actions (clicking, typing), and also for getting information about the DOM and other parts of the page.

Implementations§

source§

impl Tab

source

pub fn new(target_info: TargetInfo, transport: Arc<Transport>) -> Result<Self>

source

pub fn update_target_info(&self, target_info: TargetInfo)

source

pub fn get_target_id(&self) -> &TargetID

source

pub fn get_target_info(&self) -> Result<TargetInfo>

Fetches the most recent info about this target

source

pub fn get_browser_context_id(&self) -> Result<Option<String>>

source

pub fn get_url(&self) -> String

source

pub fn set_user_agent( &self, user_agent: &str, accept_language: Option<&str>, platform: Option<&str> ) -> Result<()>

Allows overriding user agent with the given string.

source

pub fn expose_function(&self, name: &str, func: Arc<SafeBinding>) -> Result<()>

source

pub fn remove_function(&self, name: &str) -> Result<()>

source

pub fn call_method<C>(&self, method: C) -> Result<C::ReturnObject>
where C: Method + Serialize + Debug,

source

pub fn wait_until_navigated(&self) -> Result<&Self>

source

pub fn bring_to_front(&self) -> Result<BringToFrontReturnObject>

source

pub fn navigate_to(&self, url: &str) -> Result<&Self>

source

pub fn set_default_timeout(&self, timeout: Duration) -> &Self

Set default timeout for the tab

This will be applied to all wait_for_element and wait_for_elements calls for this tab

let tab = browser.new_tab()?;
tab.set_default_timeout(std::time::Duration::from_secs(5));
source

pub fn set_slow_motion_multiplier(&self, multiplier: f64) -> &Self

Analogous to Puppeteer’s ‘slowMo’ option, but with some differences:

  • It doesn’t add a delay after literally every message sent via the protocol, but instead just for:
    • clicking a specific point on the page (default: 100ms before moving the mouse, 250ms before pressing and releasting mouse button)
    • pressing a key (default: 25 ms)
    • reloading the page (default: 100ms)
    • closing a tab (default: 100ms)
  • Instead of an absolute number of milliseconds, it’s a multiplier, so that we can delay longer on certain actions like clicking or moving the mouse, and shorter on others like on pressing a key (or the individual ‘mouseDown’ and ‘mouseUp’ actions that go across the wire. If the delay was always the same, filling out a form (e.g.) would take ages).

By default the multiplier is set to zero, which effectively disables the slow motion.

The defaults for the various actions (i.e. how long we sleep for when multiplier is 1.0) are supposed to be just slow enough to help a human see what’s going on as a test runs.

source

pub fn wait_for_element(&self, selector: &str) -> Result<Element<'_>>

source

pub fn wait_for_xpath(&self, selector: &str) -> Result<Element<'_>>

source

pub fn wait_for_element_with_custom_timeout( &self, selector: &str, timeout: Duration ) -> Result<Element<'_>>

source

pub fn wait_for_xpath_with_custom_timeout( &self, selector: &str, timeout: Duration ) -> Result<Element<'_>>

source

pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>>

source

pub fn wait_for_elements_by_xpath( &self, selector: &str ) -> Result<Vec<Element<'_>>>

source

pub fn find_element(&self, selector: &str) -> Result<Element<'_>>

Returns the first element in the document which matches the given selector.

Equivalent to the following JS:

document.querySelector(selector)
use headless_chrome::Browser;

let browser = Browser::default()?;
let initial_tab = browser.new_tab()?;

let file_server = server::Server::with_dumb_html(include_str!("../../../tests/simple.html"));
let element = initial_tab.navigate_to(&file_server.url())?
    .wait_until_navigated()?
    .find_element("div#foobar")?;
let attrs = element.get_attributes()?.unwrap();
assert_eq!(attrs["id"], "foobar");
source

pub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>>

source

pub fn run_query_selector_on_node( &self, node_id: NodeId, selector: &str ) -> Result<Element<'_>>

source

pub fn run_query_selector_all_on_node( &self, node_id: NodeId, selector: &str ) -> Result<Vec<Element<'_>>>

source

pub fn get_document(&self) -> Result<Node>

source

pub fn get_content(&self) -> Result<String>

Get the full HTML contents of the page.

source

pub fn find_elements(&self, selector: &str) -> Result<Vec<Element<'_>>>

source

pub fn find_elements_by_xpath(&self, query: &str) -> Result<Vec<Element<'_>>>

source

pub fn describe_node(&self, node_id: NodeId) -> Result<Node>

source

pub fn type_str(&self, string_to_type: &str) -> Result<&Self>

source

pub fn send_character(&self, char_to_send: &str) -> Result<&Self>

Does the same as type_str but it only dispatches a keypress and input event. It does not send a keydown or keyup event.

What this means is that it is much faster. It is especially useful when you have a lot of text as input.

source

pub fn press_key_with_modifiers( &self, key: &str, modifiers: Option<&[ModifierKey]> ) -> Result<&Self>

Press a key on the keyboard, optionally with some modifier keys. See this file for a full definition of which strings correspond with which keys.

source

pub fn press_key(&self, key: &str) -> Result<&Self>

Press a key on the keyboard. See this file for a full definition of which strings correspond with which keys.

source

pub fn move_mouse_to_point(&self, point: Point) -> Result<&Self>

Moves the mouse to this point (dispatches a mouseMoved event)

source

pub fn click_point(&self, point: Point) -> Result<&Self>

source

pub fn capture_screenshot( &self, format: CaptureScreenshotFormatOption, quality: Option<u32>, clip: Option<Viewport>, from_surface: bool ) -> Result<Vec<u8>>

Capture a screenshot of the current page.

If clip is given, the screenshot is taken of the specified region only. Element::get_box_model() can be used to get regions of certains elements on the page; there is also Element::capture_screenhot() as a shorthand.

If from_surface is true, the screenshot is taken from the surface rather than the view.

use headless_chrome::{protocol::page::ScreenshotFormat, Browser, LaunchOptions};
let browser = Browser::new(LaunchOptions::default_builder().build().unwrap())?;
let tab = browser.new_tab()?;
let viewport = tab.navigate_to("https://en.wikipedia.org/wiki/WebKit")?
    .wait_for_element("#mw-content-text > div > table.infobox.vevent")?
    .get_box_model()?
    .margin_viewport();
 let png_data = tab.capture_screenshot(ScreenshotFormat::PNG, Some(viewport), true)?;
source

pub fn print_to_pdf( &self, options: Option<PrintToPdfOptions> ) -> Result<Vec<u8>>

source

pub fn reload( &self, ignore_cache: bool, script_to_evaluate_on_load: Option<&str> ) -> Result<&Self>

Reloads given page optionally ignoring the cache

If ignore_cache is true, the browser cache is ignored (as if the user pressed Shift+F5). If script_to_evaluate is given, the script will be injected into all frames of the inspected page after reload. Argument will be ignored if reloading dataURL origin.

source

pub fn set_transparent_background_color(&self) -> Result<&Self>

Set the background color of the dom to transparent.

Useful when you want capture a .png

use headless_chrome::{protocol::page::ScreenshotFormat, Browser, LaunchOptions};
let browser = Browser::new(LaunchOptions::default_builder().build().unwrap())?;
let tab = browser.new_tab()?;
tab.set_transparent_background_color()?;
source

pub fn set_background_color(&self, color: RGBA) -> Result<&Self>

Set the default background color of the dom.

Pass a RGBA to override the backrgound color of the dom.

use headless_chrome::{protocol::page::ScreenshotFormat, Browser, LaunchOptions};
let browser = Browser::new(LaunchOptions::default_builder().build().unwrap())?;
let tab = browser.new_tab()?;
tab.set_background_color( color: RGBA { r: 255, g: 0, b: 0, a: 1.,})?;
source

pub fn enable_profiler(&self) -> Result<&Self>

Enables the profiler

source

pub fn disable_profiler(&self) -> Result<&Self>

Disables the profiler

source

pub fn start_js_coverage(&self) -> Result<&Self>

Starts tracking which lines of JS have been executed

Will return error unless enable_profiler has been called.

Equivalent to hitting the record button in the “coverage” tab in Chrome DevTools. See the file tests/coverage.rs for an example.

By default we enable the ‘detailed’ flag on StartPreciseCoverage, which enables block-level granularity, and also enable ‘call_count’ (which when disabled always sets count to 1 or 0).

source

pub fn stop_js_coverage(&self) -> Result<&Self>

Stops tracking which lines of JS have been executed If you’re finished with the profiler, don’t forget to call disable_profiler.

source

pub fn take_precise_js_coverage(&self) -> Result<Vec<ScriptCoverage>>

Collect coverage data for the current isolate, and resets execution counters.

Precise code coverage needs to have started (see start_js_coverage).

Will only send information about code that’s been executed since this method was last called, or (if this is the first time) since calling start_js_coverage. Another way of thinking about it is: every time you call this, the call counts for FunctionRanges are reset after returning.

The format of the data is a little unintuitive, see here for details: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage

source

pub fn enable_fetch( &self, patterns: Option<&[RequestPattern]>, handle_auth_requests: Option<bool> ) -> Result<&Self>

Enables fetch domain.

source

pub fn disable_fetch(&self) -> Result<&Self>

Disables fetch domain

source

pub fn enable_request_interception( &self, interceptor: Arc<dyn RequestInterceptor + Send + Sync> ) -> Result<()>

Allows you to inspect outgoing network requests from the tab, and optionally return your own responses to them

The interceptor argument is a closure which takes this tab’s Transport and its SessionID so that you can call methods from within the closure using transport.call_method_on_target.

The closure needs to return a variant of RequestPausedDecision.

source

pub fn authenticate( &self, username: Option<String>, password: Option<String> ) -> Result<&Self>

source

pub fn register_response_handling<S: ToString>( &self, handler_name: S, handler: ResponseHandler ) -> Result<Option<ResponseHandler>>

Lets you register a listener for responses, and gives you a way to get the response body too.

Please note that the ‘response’ does not include the body of the response – Chrome tells us about them seperately (because you might quickly get the status code and headers from a server well before you receive the entire response body which could, after all, be gigabytes long).

Currently we leave it up to the caller to decide when to call fetch_body (the second argument to the response handler), although ideally it wouldn’t be possible until Chrome has sent the Network.loadingFinished event.

Return a option for ResponseHander for existing handler with same name if existed.

source

pub fn register_loading_failed_handling<S: ToString>( &self, handler_name: S, handler: LoadingFailedHandler ) -> Result<Option<LoadingFailedHandler>>

source

pub fn deregister_response_handling( &self, handler_name: &str ) -> Result<Option<ResponseHandler>>

Deregister a reponse handler based on its name.

Return a option for ResponseHandler for removed handler if existed.

source

pub fn deregister_response_handling_all(&self) -> Result<()>

Deregister all registered handlers.

source

pub fn enable_runtime(&self) -> Result<&Self>

Enables runtime domain.

source

pub fn disable_runtime(&self) -> Result<&Self>

Disables runtime domain

source

pub fn enable_debugger(&self) -> Result<()>

Enables Debugger

source

pub fn disable_debugger(&self) -> Result<()>

Disables Debugger

source

pub fn get_script_source(&self, script_id: &str) -> Result<String>

Returns source for the script with given id.

Debugger must be enabled.

source

pub fn enable_log(&self) -> Result<&Self>

Enables log domain.

Sends the entries collected so far to the client by means of the entryAdded notification.

See https://chromedevtools.github.io/devtools-protocol/tot/Log#method-enable

source

pub fn disable_log(&self) -> Result<&Self>

Disables log domain

Prevents further log entries from being reported to the client

See https://chromedevtools.github.io/devtools-protocol/tot/Log#method-disable

source

pub fn start_violations_report( &self, config: Vec<ViolationSetting> ) -> Result<&Self>

source

pub fn stop_violations_report(&self) -> Result<&Self>

source

pub fn evaluate( &self, expression: &str, await_promise: bool ) -> Result<RemoteObject>

Evaluates expression on global object.

source

pub fn add_event_listener( &self, listener: Arc<dyn EventListener<Event> + Send + Sync> ) -> Result<Weak<dyn EventListener<Event> + Send + Sync>>

Adds event listener to Event

Make sure you are enabled domain you are listening events to.

§Usage example
tab.enable_log()?;
tab.add_event_listener(Arc::new(move |event: &Event| {
    match event {
        Event::LogEntryAdded(_) => {
            // process event here
        }
        _ => {}
      }
    }))?;
source

pub fn remove_event_listener( &self, listener: &Weak<dyn EventListener<Event> + Send + Sync> ) -> Result<()>

source

pub fn close_target(&self) -> Result<bool>

Closes the target Page

source

pub fn close_with_unload(&self) -> Result<bool>

Tries to close page, running its beforeunload hooks, if any

source

pub fn close(&self, fire_unload: bool) -> Result<bool>

Calls one of the close_* methods depending on fire_unload option

source

pub fn activate(&self) -> Result<&Self>

Activates (focuses) the target.

source

pub fn get_bounds(&self) -> Result<CurrentBounds, Error>

Get position and size of the browser window associated with this Tab.

Note that the returned bounds are always specified for normal (windowed) state; they do not change when minimizing, maximizing or setting to fullscreen.

source

pub fn set_bounds(&self, bounds: Bounds) -> Result<&Self, Error>

Set position and/or size of the browser window associated with this Tab.

When setting the window to normal (windowed) state, unspecified fields are left unchanged.

source

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

Returns all cookies that match the tab’s current URL.

source

pub fn set_cookies(&self, cs: Vec<CookieParam>) -> Result<()>

Set cookies with tab’s current URL

source

pub fn delete_cookies(&self, cs: Vec<DeleteCookies>) -> Result<()>

Delete cookies with tab’s current URL

source

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

Returns the title of the document.

tab.navigate_to("https://google.com")?;
tab.wait_until_navigated()?;
let title = tab.get_title()?;
assert_eq!(title, "Google");
source

pub fn set_file_chooser_dialog_interception(&self, enabled: bool) -> Result<()>

If enabled, instead of using the GUI to select files, the browser will wait for the Tab.handle_file_chooser method to be called. WARNING: Only works on Chromium / Chrome 77 and above.

source

pub fn handle_file_chooser( &self, files: Vec<String>, node_id: u32 ) -> Result<()>

Will have the same effect as choosing these files from the file chooser dialog that would’ve popped up had set_file_chooser_dialog_interception not been called. Calls to this method must be preceded by calls to that method.

Supports selecting files or closing the file chooser dialog.

NOTE: the filepaths listed in files must be absolute.

source

pub fn set_extra_http_headers(&self, headers: HashMap<&str, &str>) -> Result<()>

source

pub fn set_storage<T>(&self, item_name: &str, item: T) -> Result<()>
where T: Serialize,

source

pub fn get_storage<T>(&self, item_name: &str) -> Result<T>

source

pub fn remove_storage(&self, item_name: &str) -> Result<()>

source

pub fn stop_loading(&self) -> Result<bool>

source

pub fn enable_stealth_mode(&self) -> Result<()>

source

pub fn start_screencast( &self, format: Option<StartScreencastFormatOption>, quality: Option<u32>, max_width: Option<u32>, max_height: Option<u32>, every_nth_frame: Option<u32> ) -> Result<()>

source

pub fn stop_screencast(&self) -> Result<()>

source

pub fn ack_screencast(&self, session_id: u32) -> Result<()>

Auto Trait Implementations§

§

impl Freeze for Tab

§

impl !RefUnwindSafe for Tab

§

impl Send for Tab

§

impl Sync for Tab

§

impl Unpin for Tab

§

impl !UnwindSafe for Tab

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

§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V