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
impl Tab
pub fn new(target_info: TargetInfo, transport: Arc<Transport>) -> Result<Self>
pub fn update_target_info(&self, target_info: TargetInfo)
pub fn get_target_id(&self) -> &TargetID
Sourcepub fn get_target_info(&self) -> Result<TargetInfo>
pub fn get_target_info(&self) -> Result<TargetInfo>
Fetches the most recent info about this target
pub fn get_browser_context_id(&self) -> Result<Option<String>>
pub fn get_url(&self) -> String
Sourcepub fn set_user_agent(
&self,
user_agent: &str,
accept_language: Option<&str>,
platform: Option<&str>,
) -> Result<()>
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.
pub fn expose_function(&self, name: &str, func: Arc<SafeBinding>) -> Result<()>
pub fn remove_function(&self, name: &str) -> Result<()>
pub fn call_method<C>(&self, method: C) -> Result<C::ReturnObject>
pub fn bring_to_front(&self) -> Result<BringToFrontReturnObject>
Sourcepub fn set_default_timeout(&self, timeout: Duration) -> &Self
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));
Sourcepub fn set_slow_motion_multiplier(&self, multiplier: f64) -> &Self
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.
pub fn wait_for_element(&self, selector: &str) -> Result<Element<'_>>
pub fn wait_for_xpath(&self, selector: &str) -> Result<Element<'_>>
pub fn wait_for_element_with_custom_timeout( &self, selector: &str, timeout: Duration, ) -> Result<Element<'_>>
pub fn wait_for_xpath_with_custom_timeout( &self, selector: &str, timeout: Duration, ) -> Result<Element<'_>>
pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>>
pub fn wait_for_elements_by_xpath( &self, selector: &str, ) -> Result<Vec<Element<'_>>>
Sourcepub fn find_element(&self, selector: &str) -> Result<Element<'_>>
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");
pub fn find_element_by_xpath(&self, query: &str) -> Result<Element<'_>>
pub fn run_query_selector_on_node( &self, node_id: NodeId, selector: &str, ) -> Result<Element<'_>>
pub fn run_query_selector_all_on_node( &self, node_id: NodeId, selector: &str, ) -> Result<Vec<Element<'_>>>
pub fn get_document(&self) -> Result<Node>
Sourcepub fn get_content(&self) -> Result<String>
pub fn get_content(&self) -> Result<String>
Get the full HTML contents of the page.
pub fn find_elements(&self, selector: &str) -> Result<Vec<Element<'_>>>
pub fn find_elements_by_xpath(&self, query: &str) -> Result<Vec<Element<'_>>>
pub fn describe_node(&self, node_id: NodeId) -> Result<Node>
pub fn type_str(&self, string_to_type: &str) -> Result<&Self>
Sourcepub fn send_character(&self, char_to_send: &str) -> Result<&Self>
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.
Sourcepub fn press_key_with_modifiers(
&self,
key: &str,
modifiers: Option<&[ModifierKey]>,
) -> Result<&Self>
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.
Sourcepub fn press_key(&self, key: &str) -> Result<&Self>
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.
Sourcepub fn move_mouse_to_point(&self, point: Point) -> Result<&Self>
pub fn move_mouse_to_point(&self, point: Point) -> Result<&Self>
Moves the mouse to this point (dispatches a mouseMoved event)
pub fn click_point(&self, point: Point) -> Result<&Self>
Sourcepub fn capture_screenshot(
&self,
format: CaptureScreenshotFormatOption,
quality: Option<u32>,
clip: Option<Viewport>,
from_surface: bool,
) -> Result<Vec<u8>>
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 certain elements
on the page; there is also Element::capture_screenshot()
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)?;
pub fn print_to_pdf( &self, options: Option<PrintToPdfOptions>, ) -> Result<Vec<u8>>
Sourcepub fn reload(
&self,
ignore_cache: bool,
script_to_evaluate_on_load: Option<&str>,
) -> Result<&Self>
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.
Sourcepub fn set_transparent_background_color(&self) -> Result<&Self>
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()?;
Sourcepub fn set_background_color(&self, color: RGBA) -> Result<&Self>
pub fn set_background_color(&self, color: RGBA) -> Result<&Self>
Set the default background color of the dom.
Pass a RGBA to override the background 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.,})?;
Sourcepub fn enable_profiler(&self) -> Result<&Self>
pub fn enable_profiler(&self) -> Result<&Self>
Enables the profiler
Sourcepub fn disable_profiler(&self) -> Result<&Self>
pub fn disable_profiler(&self) -> Result<&Self>
Disables the profiler
Sourcepub fn start_js_coverage(&self) -> Result<&Self>
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).
Sourcepub fn stop_js_coverage(&self) -> Result<&Self>
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
.
Sourcepub fn take_precise_js_coverage(&self) -> Result<Vec<ScriptCoverage>>
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
Sourcepub fn enable_fetch(
&self,
patterns: Option<&[RequestPattern]>,
handle_auth_requests: Option<bool>,
) -> Result<&Self>
pub fn enable_fetch( &self, patterns: Option<&[RequestPattern]>, handle_auth_requests: Option<bool>, ) -> Result<&Self>
Enables fetch domain.
Sourcepub fn disable_fetch(&self) -> Result<&Self>
pub fn disable_fetch(&self) -> Result<&Self>
Disables fetch domain
Sourcepub fn enable_request_interception(
&self,
interceptor: Arc<dyn RequestInterceptor + Send + Sync>,
) -> Result<()>
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
.
pub fn authenticate( &self, username: Option<String>, password: Option<String>, ) -> Result<&Self>
Sourcepub fn register_response_handling<S: ToString>(
&self,
handler_name: S,
handler: ResponseHandler,
) -> Result<Option<ResponseHandler>>
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 separately (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 ResponseHandler for existing handler with same name if existed.
pub fn register_loading_failed_handling<S: ToString>( &self, handler_name: S, handler: LoadingFailedHandler, ) -> Result<Option<LoadingFailedHandler>>
Sourcepub fn deregister_response_handling(
&self,
handler_name: &str,
) -> Result<Option<ResponseHandler>>
pub fn deregister_response_handling( &self, handler_name: &str, ) -> Result<Option<ResponseHandler>>
Deregister a response handler based on its name.
Return a option for ResponseHandler for removed handler if existed.
Sourcepub fn deregister_response_handling_all(&self) -> Result<()>
pub fn deregister_response_handling_all(&self) -> Result<()>
Deregister all registered handlers.
Sourcepub fn enable_runtime(&self) -> Result<&Self>
pub fn enable_runtime(&self) -> Result<&Self>
Enables runtime domain.
Sourcepub fn disable_runtime(&self) -> Result<&Self>
pub fn disable_runtime(&self) -> Result<&Self>
Disables runtime domain
Sourcepub fn enable_debugger(&self) -> Result<()>
pub fn enable_debugger(&self) -> Result<()>
Enables Debugger
Sourcepub fn disable_debugger(&self) -> Result<()>
pub fn disable_debugger(&self) -> Result<()>
Disables Debugger
Sourcepub fn get_script_source(&self, script_id: &str) -> Result<String>
pub fn get_script_source(&self, script_id: &str) -> Result<String>
Returns source for the script with given id.
Debugger must be enabled.
Sourcepub fn enable_log(&self) -> Result<&Self>
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
Sourcepub fn disable_log(&self) -> Result<&Self>
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
Sourcepub fn start_violations_report(
&self,
config: Vec<ViolationSetting>,
) -> Result<&Self>
pub fn start_violations_report( &self, config: Vec<ViolationSetting>, ) -> Result<&Self>
Starts violation reporting
See https://chromedevtools.github.io/devtools-protocol/tot/Log#method-startViolationsReport
Sourcepub fn stop_violations_report(&self) -> Result<&Self>
pub fn stop_violations_report(&self) -> Result<&Self>
Stop violation reporting
See https://chromedevtools.github.io/devtools-protocol/tot/Log#method-stopViolationsReport
Sourcepub fn evaluate(
&self,
expression: &str,
await_promise: bool,
) -> Result<RemoteObject>
pub fn evaluate( &self, expression: &str, await_promise: bool, ) -> Result<RemoteObject>
Evaluates expression on global object.
Sourcepub fn add_event_listener(
&self,
listener: Arc<dyn EventListener<Event> + Send + Sync>,
) -> Result<Weak<dyn EventListener<Event> + Send + Sync>>
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
}
_ => {}
}
}))?;
pub fn remove_event_listener( &self, listener: &Weak<dyn EventListener<Event> + Send + Sync>, ) -> Result<()>
Sourcepub fn close_target(&self) -> Result<bool>
pub fn close_target(&self) -> Result<bool>
Closes the target Page
Sourcepub fn close_with_unload(&self) -> Result<bool>
pub fn close_with_unload(&self) -> Result<bool>
Tries to close page, running its beforeunload hooks, if any
Sourcepub fn close(&self, fire_unload: bool) -> Result<bool>
pub fn close(&self, fire_unload: bool) -> Result<bool>
Calls one of the close_* methods depending on fire_unload option
Sourcepub fn get_bounds(&self) -> Result<CurrentBounds, Error>
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.
Sourcepub fn set_bounds(&self, bounds: Bounds) -> Result<&Self, Error>
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.
Returns all cookies that match the tab’s current URL.
Set cookies with tab’s current URL
Delete cookies with tab’s current URL
Sourcepub fn get_title(&self) -> Result<String>
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");
Sourcepub fn set_file_chooser_dialog_interception(&self, enabled: bool) -> Result<()>
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.
Sourcepub fn handle_file_chooser(
&self,
files: Vec<String>,
node_id: u32,
) -> Result<()>
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.
pub fn set_extra_http_headers(&self, headers: HashMap<&str, &str>) -> Result<()>
pub fn set_storage<T>(&self, item_name: &str, item: T) -> Result<()>where
T: Serialize,
pub fn get_storage<T>(&self, item_name: &str) -> Result<T>where
T: DeserializeOwned,
pub fn remove_storage(&self, item_name: &str) -> Result<()>
pub fn stop_loading(&self) -> Result<bool>
pub fn enable_stealth_mode(&self) -> Result<()>
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<()>
pub fn stop_screencast(&self) -> Result<()>
pub fn ack_screencast(&self, session_id: u32) -> Result<()>
Sourcepub fn get_dialog(&self) -> Dialog
pub fn get_dialog(&self) -> Dialog
Get the handle of the dialog opened in this tab.
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> 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> 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