pub struct Page { /* private fields */ }Expand description
A browser page (tab).
Implementations§
Source§impl Page
impl Page
Sourcepub async fn expose_function<F, Fut>(
&self,
name: &str,
callback: F,
) -> Result<(), PageError>
pub async fn expose_function<F, Fut>( &self, name: &str, callback: F, ) -> Result<(), PageError>
Expose a Rust function to JavaScript.
The function will be available as window.<name>() in JavaScript.
When called from JavaScript, the function arguments are serialized to JSON,
the Rust callback is executed, and the result is returned to JavaScript.
§Example
use viewpoint_core::Page;
// Expose a simple function
page.expose_function("add", |args| async move {
let x = args[0].as_i64().unwrap_or(0);
let y = args[1].as_i64().unwrap_or(0);
Ok(serde_json::json!(x + y))
}).await?;
// Call from JavaScript:
// const result = await window.add(1, 2); // returns 3
// Expose a function with string processing
page.expose_function("sha256", |args| async move {
let input = args[0].as_str().unwrap_or("");
// ... compute hash ...
let hash_string = "example_hash";
Ok(serde_json::json!(hash_string))
}).await?;§Notes
- The function is re-bound after each navigation
- Arguments and return values must be JSON-serializable
- Errors returned from the callback will reject the JavaScript promise
Source§impl Page
impl Page
Sourcepub fn set_content(&self, html: impl Into<String>) -> SetContentBuilder<'_>
pub fn set_content(&self, html: impl Into<String>) -> SetContentBuilder<'_>
Set the page HTML content.
Returns a builder for additional options.
§Example
use viewpoint_core::DocumentLoadState;
// Set simple content
page.set_content("<html><body>Hello</body></html>").set().await?;
// Set content and wait for network idle
page.set_content("<html><body><script src='app.js'></script></body></html>")
.wait_until(DocumentLoadState::NetworkIdle)
.set()
.await?;Sourcepub fn add_script_tag(&self) -> ScriptTagBuilder<'_>
pub fn add_script_tag(&self) -> ScriptTagBuilder<'_>
Create a builder for injecting script tags.
§Example
// Add script by URL
page.add_script_tag().url("https://example.com/script.js").inject().await?;
// Add inline script
page.add_script_tag().content("console.log('Hello')").inject().await?;
// Add ES6 module
use viewpoint_core::page::ScriptType;
page.add_script_tag()
.content("export const x = 1;")
.script_type(ScriptType::Module)
.inject()
.await?;Sourcepub fn add_style_tag(&self) -> StyleTagBuilder<'_>
pub fn add_style_tag(&self) -> StyleTagBuilder<'_>
Create a builder for injecting style tags.
§Example
// Add stylesheet by URL
page.add_style_tag().url("https://example.com/style.css").inject().await?;
// Add inline CSS
page.add_style_tag().content("body { background: red; }").inject().await?;Source§impl Page
impl Page
Sourcepub fn viewport_size(&self) -> Option<ViewportSize>
pub fn viewport_size(&self) -> Option<ViewportSize>
Get the current viewport size.
Returns the width and height in pixels.
Sourcepub async fn bring_to_front(&self) -> Result<(), PageError>
pub async fn bring_to_front(&self) -> Result<(), PageError>
Bring this page to the front (activate the tab).
§Errors
Returns an error if the page is closed or the CDP command fails.
Sourcepub fn emulate_media(&self) -> EmulateMediaBuilder<'_>
pub fn emulate_media(&self) -> EmulateMediaBuilder<'_>
Create a builder for emulating CSS media features.
Use this to test how your application responds to different media preferences like dark mode, print media, reduced motion, and forced colors.
§Example
use viewpoint_core::{Page, page::MediaType};
use viewpoint_core::{ColorScheme, ReducedMotion};
// Emulate dark mode
page.emulate_media()
.color_scheme(ColorScheme::Dark)
.apply()
.await?;
// Emulate print media
page.emulate_media()
.media(MediaType::Print)
.apply()
.await?;
// Combine multiple settings
page.emulate_media()
.color_scheme(ColorScheme::Dark)
.reduced_motion(ReducedMotion::Reduce)
.apply()
.await?;
// Clear all media emulation
page.emulate_media()
.clear()
.await?;Sourcepub async fn emulate_vision_deficiency(
&self,
deficiency: VisionDeficiency,
) -> Result<(), PageError>
pub async fn emulate_vision_deficiency( &self, deficiency: VisionDeficiency, ) -> Result<(), PageError>
Emulate a vision deficiency on the page.
This is useful for accessibility testing to ensure your application is usable by people with various types of color blindness.
§Example
use viewpoint_core::{Page, page::VisionDeficiency};
// Emulate deuteranopia (green-blind)
page.emulate_vision_deficiency(VisionDeficiency::Deuteranopia).await?;
// Clear vision deficiency emulation
page.emulate_vision_deficiency(VisionDeficiency::None).await?;§Errors
Returns an error if the page is closed or the CDP command fails.
Source§impl Page
impl Page
Sourcepub fn wait_for_function(
&self,
expression: impl Into<String>,
) -> WaitForFunctionBuilder<'_>
pub fn wait_for_function( &self, expression: impl Into<String>, ) -> WaitForFunctionBuilder<'_>
Wait for a JavaScript function to return a truthy value.
§Example
use std::time::Duration;
use viewpoint_core::page::Polling;
use viewpoint_js::js;
// Wait for an element to appear
let selector = ".loaded";
page.wait_for_function(js!{ () => document.querySelector(#{selector}) })
.wait()
.await?;
// Wait with custom timeout
page.wait_for_function(js!{ () => window.ready })
.timeout(Duration::from_secs(10))
.wait()
.await?;
// Wait with interval polling
page.wait_for_function(js!{ () => window.ready })
.polling(Polling::Interval(Duration::from_millis(100)))
.wait()
.await?;Sourcepub fn wait_for_function_with_arg<A>(
&self,
expression: impl Into<String>,
arg: A,
) -> WaitForFunctionBuilder<'_>where
A: Serialize,
pub fn wait_for_function_with_arg<A>(
&self,
expression: impl Into<String>,
arg: A,
) -> WaitForFunctionBuilder<'_>where
A: Serialize,
Wait for a JavaScript function with an argument to return a truthy value.
Source§impl Page
impl Page
Sourcepub async fn evaluate<T>(&self, expression: &str) -> Result<T, PageError>where
T: DeserializeOwned,
pub async fn evaluate<T>(&self, expression: &str) -> Result<T, PageError>where
T: DeserializeOwned,
Evaluate JavaScript in the page context.
The expression is evaluated and the result is deserialized to the specified type. Promises are automatically awaited.
§Type Parameters
T- The return type. Useserde_json::Valuefor dynamic results.
§Example
use viewpoint_js::js;
// Simple expression
let sum: i32 = page.evaluate(js!{ 1 + 2 }).await?;
assert_eq!(sum, 3);
// Function expression
let width: i32 = page.evaluate(js!{ () => window.innerWidth }).await?;
// With interpolation (note: returns String so use &)
let selector = ".my-class";
let el: serde_json::Value = page.evaluate(&js!{ document.querySelector(#{selector}) }).await?;
// Get document title
let title: String = page.evaluate(js!{ document.title }).await?;§Errors
Returns an error if:
- The page is closed
- The JavaScript throws an error
- The result cannot be deserialized
Sourcepub async fn evaluate_with_arg<T, A>(
&self,
expression: &str,
arg: A,
) -> Result<T, PageError>where
T: DeserializeOwned,
A: Serialize,
pub async fn evaluate_with_arg<T, A>(
&self,
expression: &str,
arg: A,
) -> Result<T, PageError>where
T: DeserializeOwned,
A: Serialize,
Evaluate JavaScript with an argument.
The argument is serialized to JSON and passed to the function.
§Example
// Pass a number
let doubled: i32 = page.evaluate_with_arg("x => x * 2", 21).await?;
assert_eq!(doubled, 42);
// Pass an object
let name: String = page.evaluate_with_arg("obj => obj.name", serde_json::json!({"name": "test"})).await?;Sourcepub async fn evaluate_handle(
&self,
expression: &str,
) -> Result<JsHandle, PageError>
pub async fn evaluate_handle( &self, expression: &str, ) -> Result<JsHandle, PageError>
Evaluate JavaScript and return a handle to the result.
Use this when you need to reference the result object later, or when the result cannot be serialized (like DOM elements).
§Example
// Get a handle to the body element
let body_handle = page.evaluate_handle("document.body").await?;
// Use the handle in another evaluation
let tag_name: String = page.evaluate_with_arg("el => el.tagName", body_handle.object_id()).await?;
// Clean up
body_handle.dispose().await?;Source§impl Page
impl Page
Sourcepub async fn on_dialog<F, Fut>(&self, handler: F)
pub async fn on_dialog<F, Fut>(&self, handler: F)
Set a handler for browser dialogs (alert, confirm, prompt, beforeunload).
The handler will be called whenever a dialog appears. If no handler is set, dialogs are automatically dismissed.
§Example
use viewpoint_core::Page;
use viewpoint_core::DialogType;
// Accept all dialogs
page.on_dialog(|dialog| async move {
println!("Dialog: {:?} - {}", dialog.type_(), dialog.message());
dialog.accept().await
}).await;
// Handle prompt with custom text
page.on_dialog(|dialog| async move {
if matches!(dialog.type_(), DialogType::Prompt) {
dialog.accept_with_text("my answer").await
} else {
dialog.accept().await
}
}).await;Sourcepub async fn off_dialog(&self)
pub async fn off_dialog(&self)
Remove the dialog handler.
After calling this, dialogs will be automatically dismissed.
Sourcepub async fn on_console<F, Fut>(&self, handler: F)
pub async fn on_console<F, Fut>(&self, handler: F)
Set a handler for console messages (console.log, console.error, etc.).
The handler will be called whenever JavaScript code logs to the console.
§Example
use viewpoint_core::Page;
use viewpoint_core::page::console::ConsoleMessageType;
page.on_console(|message| async move {
println!("[{:?}] {}", message.type_(), message.text());
}).await;
// Filter by message type
page.on_console(|message| async move {
if matches!(message.type_(), ConsoleMessageType::Error) {
eprintln!("Console error: {}", message.text());
}
}).await;Sourcepub async fn off_console(&self)
pub async fn off_console(&self)
Remove the console message handler.
Sourcepub async fn on_pageerror<F, Fut>(&self, handler: F)
pub async fn on_pageerror<F, Fut>(&self, handler: F)
Set a handler for page errors (uncaught exceptions).
The handler will be called whenever an uncaught JavaScript exception occurs.
§Example
use viewpoint_core::Page;
page.on_pageerror(|error| async move {
eprintln!("Page error: {}", error.message());
if let Some(stack) = error.stack() {
eprintln!("Stack trace:\n{}", stack);
}
}).await;Sourcepub async fn off_pageerror(&self)
pub async fn off_pageerror(&self)
Remove the page error handler.
Sourcepub async fn on_frameattached<F, Fut>(&self, handler: F)
pub async fn on_frameattached<F, Fut>(&self, handler: F)
Set a handler for frame attached events.
The handler will be called whenever a new frame is attached to the page,
typically when an <iframe> is added to the DOM.
§Example
use viewpoint_core::Page;
page.on_frameattached(|frame| async move {
println!("Frame attached: {}", frame.url());
}).await;Sourcepub async fn off_frameattached(&self)
pub async fn off_frameattached(&self)
Remove the frame attached handler.
Set a handler for frame navigated events.
The handler will be called whenever a frame navigates to a new URL.
§Example
use viewpoint_core::Page;
page.on_framenavigated(|frame| async move {
println!("Frame navigated to: {}", frame.url());
}).await;Remove the frame navigated handler.
Sourcepub async fn on_framedetached<F, Fut>(&self, handler: F)
pub async fn on_framedetached<F, Fut>(&self, handler: F)
Set a handler for frame detached events.
The handler will be called whenever a frame is detached from the page,
typically when an <iframe> is removed from the DOM.
§Example
use viewpoint_core::Page;
page.on_framedetached(|frame| async move {
println!("Frame detached: {}", frame.id());
}).await;Sourcepub async fn off_framedetached(&self)
pub async fn off_framedetached(&self)
Remove the frame detached handler.
Sourcepub async fn expect_console<F, Fut>(
&self,
action: F,
) -> Result<ConsoleMessage, PageError>
pub async fn expect_console<F, Fut>( &self, action: F, ) -> Result<ConsoleMessage, PageError>
Wait for a console message triggered by an action.
§Example
use viewpoint_core::Page;
let message = page.expect_console(|| async {
page.locator("#log-button").click().await?;
Ok(())
}).await?;
println!("Console message: {}", message.text());Sourcepub async fn expect_pageerror<F, Fut>(
&self,
action: F,
) -> Result<PageError, PageError>
pub async fn expect_pageerror<F, Fut>( &self, action: F, ) -> Result<PageError, PageError>
Wait for a page error triggered by an action.
§Example
use viewpoint_core::Page;
let error = page.expect_pageerror(|| async {
page.locator("#trigger-error").click().await?;
Ok(())
}).await?;
println!("Page error: {}", error.message());Sourcepub async fn on_download<F, Fut>(&self, handler: F)
pub async fn on_download<F, Fut>(&self, handler: F)
Set a handler for file downloads.
The handler will be called whenever a download starts.
§Example
use viewpoint_core::Page;
page.on_download(|mut download| async move {
let path = download.path().await.unwrap();
println!("Downloaded: {}", path.display());
}).await;Sourcepub async fn expect_download<F, Fut>(
&self,
action: F,
) -> Result<Download, PageError>
pub async fn expect_download<F, Fut>( &self, action: F, ) -> Result<Download, PageError>
Wait for a download triggered by an action.
§Example
use viewpoint_core::Page;
let mut download = page.expect_download(|| async {
page.locator("a.download").click().await?;
Ok(())
}).await?;
download.save_as("./my-file.pdf").await?;Sourcepub async fn set_intercept_file_chooser(
&self,
enabled: bool,
) -> Result<(), PageError>
pub async fn set_intercept_file_chooser( &self, enabled: bool, ) -> Result<(), PageError>
Set whether to intercept file chooser dialogs.
When enabled, file chooser dialogs will be intercepted and the
on_filechooser handler will be called instead of showing the
native file picker.
Sourcepub async fn on_filechooser<F, Fut>(&self, handler: F)
pub async fn on_filechooser<F, Fut>(&self, handler: F)
Set a handler for file chooser dialogs.
You must call set_intercept_file_chooser(true) before using this.
§Example
use viewpoint_core::Page;
page.set_intercept_file_chooser(true).await?;
page.on_filechooser(|chooser| async move {
chooser.set_files(&["./upload.txt"]).await.unwrap();
}).await;Sourcepub async fn expect_file_chooser<F, Fut>(
&self,
action: F,
) -> Result<FileChooser, PageError>
pub async fn expect_file_chooser<F, Fut>( &self, action: F, ) -> Result<FileChooser, PageError>
Wait for a file chooser triggered by an action.
You must call set_intercept_file_chooser(true) before using this.
§Example
use viewpoint_core::Page;
page.set_intercept_file_chooser(true).await?;
let chooser = page.expect_file_chooser(|| async {
page.locator("input[type=file]").click().await?;
Ok(())
}).await?;
chooser.set_files(&["./upload.txt"]).await?;Source§impl Page
impl Page
Sourcepub fn frame_locator(&self, selector: impl Into<String>) -> FrameLocator<'_>
pub fn frame_locator(&self, selector: impl Into<String>) -> FrameLocator<'_>
Create a locator for an iframe element.
Frame locators allow targeting elements inside iframes. They can be chained to navigate through nested iframes.
§Example
use viewpoint_core::Page;
// Target an element inside an iframe
page.frame_locator("#my-iframe")
.locator("button")
.click()
.await?;
// Navigate through nested iframes
page.frame_locator("#outer")
.frame_locator("#inner")
.locator("input")
.fill("text")
.await?;Sourcepub async fn main_frame(&self) -> Result<Frame, PageError>
pub async fn main_frame(&self) -> Result<Frame, PageError>
Get the main frame of the page.
The main frame is the top-level frame that contains the page content. All other frames are child frames (iframes) of this frame.
§Errors
Returns an error if the frame tree cannot be retrieved.
§Example
use viewpoint_core::Page;
let main_frame = page.main_frame().await?;
println!("Main frame URL: {}", main_frame.url());Sourcepub async fn frame_by_url(
&self,
pattern: &str,
) -> Result<Option<Frame>, PageError>
pub async fn frame_by_url( &self, pattern: &str, ) -> Result<Option<Frame>, PageError>
Get a frame by URL pattern.
The pattern can be a glob pattern (e.g., “/payment/”) or an exact URL. Returns the first frame whose URL matches the pattern.
§Errors
Returns an error if the frame tree cannot be retrieved.
§Example
use viewpoint_core::Page;
if let Some(frame) = page.frame_by_url("**/checkout/**").await? {
println!("Found checkout frame: {}", frame.url());
}Source§impl Page
impl Page
Sourcepub fn keyboard(&self) -> &Keyboard
pub fn keyboard(&self) -> &Keyboard
Get a reference to the keyboard controller.
The keyboard controller provides methods for pressing keys, typing text, and managing modifier key state.
§Example
use viewpoint_core::Page;
// Press a key
page.keyboard().press("Enter").await?;
// Type text
page.keyboard().type_text("Hello, World!").await?;
// Use key combinations
page.keyboard().press("Control+a").await?;
// Hold and release modifiers
page.keyboard().down("Shift").await?;
page.keyboard().press("a").await?; // Types 'A'
page.keyboard().up("Shift").await?;Sourcepub fn mouse(&self) -> &Mouse
pub fn mouse(&self) -> &Mouse
Get a reference to the mouse controller.
The mouse controller provides methods for moving the mouse, clicking, and scrolling.
§Example
use viewpoint_core::Page;
use viewpoint_core::MouseButton;
// Move mouse
page.mouse().move_(100.0, 200.0).send().await?;
// Click at coordinates
page.mouse().click(100.0, 200.0).send().await?;
// Right-click
page.mouse().click(100.0, 200.0).button(MouseButton::Right).send().await?;
// Scroll
page.mouse().wheel(0.0, 100.0).await?;Sourcepub fn touchscreen(&self) -> &Touchscreen
pub fn touchscreen(&self) -> &Touchscreen
Get a reference to the touchscreen controller.
The touchscreen controller provides methods for touch input simulation.
Requires hasTouch: true in browser context options.
§Example
use viewpoint_core::Page;
page.touchscreen().tap(100.0, 200.0).await?;Sourcepub fn clock(&self) -> Clock<'_>
pub fn clock(&self) -> Clock<'_>
Get a clock controller for this page.
The clock controller allows you to mock time-related JavaScript functions
including Date, setTimeout, setInterval, requestAnimationFrame, and
performance.now().
§Example
use viewpoint_core::Page;
use std::time::Duration;
// Install clock mocking
let mut clock = page.clock();
clock.install().await?;
// Freeze time at a specific moment
clock.set_fixed_time("2024-01-01T00:00:00Z").await?;
// Advance time and fire scheduled timers
clock.run_for(Duration::from_secs(5)).await?;
// Cleanup
clock.uninstall().await?;Sourcepub fn drag_and_drop(
&self,
source: impl Into<String>,
target: impl Into<String>,
) -> DragAndDropBuilder<'_>
pub fn drag_and_drop( &self, source: impl Into<String>, target: impl Into<String>, ) -> DragAndDropBuilder<'_>
Drag from source to target element.
Returns a builder for configuring drag options.
§Example
use viewpoint_core::Page;
// Simple drag and drop
page.drag_and_drop("#source", "#target").send().await?;
// With position options
page.drag_and_drop("#source", "#target")
.source_position(10.0, 10.0)
.target_position(5.0, 5.0)
.send()
.await?;Source§impl Page
impl Page
Sourcepub fn locator(&self, selector: impl Into<String>) -> Locator<'_>
pub fn locator(&self, selector: impl Into<String>) -> Locator<'_>
Create a locator for elements matching a CSS selector.
§Example
use viewpoint_core::Page;
let button = page.locator("button.submit");
let items = page.locator(".list > .item");Sourcepub fn get_by_text(&self, text: impl Into<String>) -> Locator<'_>
pub fn get_by_text(&self, text: impl Into<String>) -> Locator<'_>
Create a locator for elements containing the specified text.
§Example
use viewpoint_core::Page;
let heading = page.get_by_text("Welcome");
let exact = page.get_by_text_exact("Welcome to our site");Sourcepub fn get_by_text_exact(&self, text: impl Into<String>) -> Locator<'_>
pub fn get_by_text_exact(&self, text: impl Into<String>) -> Locator<'_>
Create a locator for elements with exact text content.
Sourcepub fn get_by_role(&self, role: AriaRole) -> RoleLocatorBuilder<'_>
pub fn get_by_role(&self, role: AriaRole) -> RoleLocatorBuilder<'_>
Create a locator for elements with the specified ARIA role.
§Example
use viewpoint_core::Page;
use viewpoint_core::page::locator::AriaRole;
let buttons = page.get_by_role(AriaRole::Button);
let submit = page.get_by_role(AriaRole::Button).with_name("Submit");Sourcepub fn get_by_test_id(&self, test_id: impl Into<String>) -> Locator<'_>
pub fn get_by_test_id(&self, test_id: impl Into<String>) -> Locator<'_>
Create a locator for elements with the specified test ID.
By default, looks for data-testid attribute. Use
BrowserContext::set_test_id_attribute() to customize which attribute
is used.
§Example
use viewpoint_core::Page;
let button = page.get_by_test_id("submit-button");Sourcepub fn test_id_attribute(&self) -> &str
pub fn test_id_attribute(&self) -> &str
Get the test ID attribute used by this page.
Sourcepub fn set_test_id_attribute(&mut self, attribute: impl Into<String>)
pub fn set_test_id_attribute(&mut self, attribute: impl Into<String>)
Set the test ID attribute for this page.
This only affects this page. For context-wide configuration,
use BrowserContext::set_test_id_attribute().
Sourcepub fn get_by_label(&self, label: impl Into<String>) -> Locator<'_>
pub fn get_by_label(&self, label: impl Into<String>) -> Locator<'_>
Create a locator for form controls by their associated label text.
§Example
use viewpoint_core::Page;
let email = page.get_by_label("Email address");Sourcepub fn get_by_placeholder(&self, placeholder: impl Into<String>) -> Locator<'_>
pub fn get_by_placeholder(&self, placeholder: impl Into<String>) -> Locator<'_>
Create a locator for inputs by their placeholder text.
§Example
use viewpoint_core::Page;
let search = page.get_by_placeholder("Search...");Sourcepub fn get_by_alt_text(&self, alt: impl Into<String>) -> Locator<'_>
pub fn get_by_alt_text(&self, alt: impl Into<String>) -> Locator<'_>
Create a locator for images by their alt text.
§Example
use viewpoint_core::Page;
let logo = page.get_by_alt_text("Company Logo");Sourcepub fn get_by_alt_text_exact(&self, alt: impl Into<String>) -> Locator<'_>
pub fn get_by_alt_text_exact(&self, alt: impl Into<String>) -> Locator<'_>
Create a locator for images with exact alt text.
Sourcepub fn get_by_title(&self, title: impl Into<String>) -> Locator<'_>
pub fn get_by_title(&self, title: impl Into<String>) -> Locator<'_>
Create a locator for elements by their title attribute.
§Example
use viewpoint_core::Page;
let tooltip = page.get_by_title("Click to expand");Sourcepub fn get_by_title_exact(&self, title: impl Into<String>) -> Locator<'_>
pub fn get_by_title_exact(&self, title: impl Into<String>) -> Locator<'_>
Create a locator for elements with exact title attribute.
Source§impl Page
impl Page
Sourcepub async fn add_locator_handler<F, Fut>(
&self,
locator: impl Into<Locator<'_>>,
handler: F,
) -> LocatorHandlerHandle
pub async fn add_locator_handler<F, Fut>( &self, locator: impl Into<Locator<'_>>, handler: F, ) -> LocatorHandlerHandle
Add a handler for overlay elements that may block actions.
This is useful for automatically dismissing elements like cookie banners, notification popups, or other overlays that appear during tests.
§Example
use viewpoint_core::{Page, AriaRole};
use std::sync::Arc;
// Dismiss cookie banner when it appears
let page_clone = page.clone();
let handle = page.add_locator_handler(
page.get_by_role(AriaRole::Button).with_name("Accept cookies"),
move || {
let page = page_clone.clone();
async move { page.locator(".cookie-banner .accept").click().await }
}
).await;
// Later, remove the handler
page.remove_locator_handler(handle).await;Sourcepub async fn add_locator_handler_with_options<F, Fut>(
&self,
locator: impl Into<Locator<'_>>,
handler: F,
options: LocatorHandlerOptions,
) -> LocatorHandlerHandle
pub async fn add_locator_handler_with_options<F, Fut>( &self, locator: impl Into<Locator<'_>>, handler: F, options: LocatorHandlerOptions, ) -> LocatorHandlerHandle
Add a locator handler with options.
§Example
use viewpoint_core::{Page, LocatorHandlerOptions};
use std::sync::Arc;
// Handler that only runs once
let page_clone = page.clone();
page.add_locator_handler_with_options(
page.locator(".popup"),
move || {
let page = page_clone.clone();
async move { page.locator(".popup .close").click().await }
},
LocatorHandlerOptions { times: Some(1), ..Default::default() }
).await;Sourcepub async fn remove_locator_handler(&self, handle: LocatorHandlerHandle)
pub async fn remove_locator_handler(&self, handle: LocatorHandlerHandle)
Remove a locator handler.
Source§impl Page
impl Page
Sourcepub async fn go_back(
&self,
) -> Result<Option<NavigationResponse>, NavigationError>
pub async fn go_back( &self, ) -> Result<Option<NavigationResponse>, NavigationError>
Navigate back in history.
Returns None if there is no previous page in history.
§Example
if page.go_back().await?.is_some() {
println!("Navigated back");
}Sourcepub async fn go_forward(
&self,
) -> Result<Option<NavigationResponse>, NavigationError>
pub async fn go_forward( &self, ) -> Result<Option<NavigationResponse>, NavigationError>
Navigate forward in history.
Returns None if there is no next page in history.
Sourcepub async fn reload(&self) -> Result<NavigationResponse, NavigationError>
pub async fn reload(&self) -> Result<NavigationResponse, NavigationError>
Source§impl Page
impl Page
Sourcepub async fn route<M, H, Fut>(
&self,
pattern: M,
handler: H,
) -> Result<(), NetworkError>
pub async fn route<M, H, Fut>( &self, pattern: M, handler: H, ) -> Result<(), NetworkError>
Register a route handler for requests matching the given pattern.
The handler will be called for each request that matches the pattern.
Use route.fulfill(), route.continue_(), or route.abort() to handle the request.
Handlers are matched in reverse registration order (LIFO). The last registered handler that matches a URL is called first.
§Example
use viewpoint_core::network::Route;
use viewpoint_core::page::Page;
// Block all CSS requests
page.route("**/*.css", |route: Route| async move {
route.abort().await
}).await?;
// Mock an API response
page.route("**/api/users", |route: Route| async move {
route.fulfill()
.status(200)
.json(&serde_json::json!({"users": []}))
.send()
.await
}).await?;
// Modify request headers
page.route("**/api/**", |route: Route| async move {
route.continue_()
.header("Authorization", "Bearer token")
.await
}).await?;Sourcepub async fn route_predicate<P, H, Fut>(
&self,
predicate: P,
handler: H,
) -> Result<(), NetworkError>
pub async fn route_predicate<P, H, Fut>( &self, predicate: P, handler: H, ) -> Result<(), NetworkError>
Register a route handler with a predicate function.
§Example
use viewpoint_core::network::Route;
use viewpoint_core::page::Page;
// Handle only POST requests
page.route_predicate(
|url| url.contains("/api/"),
|route: Route| async move {
if route.request().method() == "POST" {
route.abort().await
} else {
route.continue_().await
}
}
).await?;Sourcepub async fn unroute(&self, pattern: &str)
pub async fn unroute(&self, pattern: &str)
Unregister handlers matching the given pattern.
§Example
use viewpoint_core::network::Route;
use viewpoint_core::page::Page;
page.route("**/*.css", |route: Route| async move {
route.abort().await
}).await?;
// Later...
page.unroute("**/*.css").await;Sourcepub async fn unroute_all(&self)
pub async fn unroute_all(&self)
Sourcepub async fn route_from_har(
&self,
path: impl AsRef<Path>,
) -> Result<(), NetworkError>
pub async fn route_from_har( &self, path: impl AsRef<Path>, ) -> Result<(), NetworkError>
Route requests from a HAR file.
Requests that match entries in the HAR file will be fulfilled with the recorded responses. Requests that don’t match will continue normally unless strict mode is enabled.
§Example
use viewpoint_core::network::HarReplayOptions;
use viewpoint_core::page::Page;
// Simple HAR routing
page.route_from_har("recordings/api.har").await?;
// With options
page.route_from_har_with_options(
"recordings/api.har",
HarReplayOptions::new()
.url("**/api/**")
.strict(true)
).await?;§Errors
Returns an error if:
- The HAR file cannot be read or parsed
- The page is closed
Sourcepub async fn route_from_har_with_options(
&self,
path: impl AsRef<Path>,
options: HarReplayOptions,
) -> Result<(), NetworkError>
pub async fn route_from_har_with_options( &self, path: impl AsRef<Path>, options: HarReplayOptions, ) -> Result<(), NetworkError>
Route requests from a HAR file with options.
§Example
use viewpoint_core::network::HarReplayOptions;
use viewpoint_core::page::Page;
// Strict mode: fail if no match found
page.route_from_har_with_options(
"api.har",
HarReplayOptions::new().strict(true)
).await?;
// URL filter: only match specific URLs
page.route_from_har_with_options(
"api.har",
HarReplayOptions::new().url("**/api/**")
).await?;
// Simulate original timing
page.route_from_har_with_options(
"api.har",
HarReplayOptions::new().use_original_timing(true)
).await?;§Errors
Returns an error if:
- The HAR file cannot be read or parsed
- The page is closed
Sourcepub fn wait_for_request<M>(&self, pattern: M) -> WaitForRequestBuilder<'_, M>where
M: UrlMatcher + Clone + 'static,
pub fn wait_for_request<M>(&self, pattern: M) -> WaitForRequestBuilder<'_, M>where
M: UrlMatcher + Clone + 'static,
Wait for a request matching the given pattern.
Returns a builder that can be used to configure timeout and wait for the request.
§Example
use std::time::Duration;
use viewpoint_core::page::Page;
// Wait for any API request
let request = page.wait_for_request("**/api/**".to_string())
.timeout(Duration::from_secs(10))
.wait()
.await?;
println!("Request URL: {}", request.url());
// Wait for a specific request
let request = page.wait_for_request("**/users".to_string())
.wait()
.await?;Sourcepub fn wait_for_response<M>(&self, pattern: M) -> WaitForResponseBuilder<'_, M>where
M: UrlMatcher + Clone + 'static,
pub fn wait_for_response<M>(&self, pattern: M) -> WaitForResponseBuilder<'_, M>where
M: UrlMatcher + Clone + 'static,
Wait for a response matching the given pattern.
Returns a builder that can be used to configure timeout and wait for the response.
§Example
use std::time::Duration;
use viewpoint_core::page::Page;
// Wait for any API response
let response = page.wait_for_response("**/api/**".to_string())
.timeout(Duration::from_secs(10))
.wait()
.await?;
println!("Response status: {}", response.status());
// Get the response body
let body = response.text().await?;Sourcepub async fn on_websocket<F, Fut>(&self, handler: F)
pub async fn on_websocket<F, Fut>(&self, handler: F)
Set a handler for WebSocket connection events.
The handler will be called whenever a new WebSocket connection is opened from this page. You can then register handlers on the WebSocket for frame events.
§Example
use viewpoint_core::page::Page;
page.on_websocket(|ws| async move {
println!("WebSocket opened: {}", ws.url());
// Register handlers for frames
ws.on_framesent(|frame| async move {
println!("Sent: {:?}", frame.payload());
}).await;
ws.on_framereceived(|frame| async move {
println!("Received: {:?}", frame.payload());
}).await;
ws.on_close(|| async {
println!("WebSocket closed");
}).await;
}).await;Sourcepub async fn off_websocket(&self)
pub async fn off_websocket(&self)
Remove the WebSocket event handler.
Source§impl Page
impl Page
Sourcepub async fn on_popup<F, Fut>(&self, handler: F)
pub async fn on_popup<F, Fut>(&self, handler: F)
Set a handler for popup window events.
The handler will be called whenever a popup window is opened
from this page (e.g., via window.open() or target="_blank" links).
§Example
use viewpoint_core::page::Page;
page.on_popup(|mut popup| async move {
println!("Popup opened: {}", popup.url().await.unwrap_or_default());
// Work with the popup
let _ = popup.close().await;
}).await;Sourcepub fn wait_for_popup<F, Fut>(
&self,
action: F,
) -> WaitForPopupBuilder<'_, F, Fut>
pub fn wait_for_popup<F, Fut>( &self, action: F, ) -> WaitForPopupBuilder<'_, F, Fut>
Wait for a popup to be opened during an action.
This is useful for handling popups that are opened by clicking links or buttons that open new windows.
§Example
use viewpoint_core::page::Page;
let mut popup = page.wait_for_popup(|| async {
page.locator("a[target=_blank]").click().await
}).wait().await?;
// Now work with the popup page
println!("Popup URL: {}", popup.url().await?);
popup.close().await?;§Errors
Returns an error if:
- The action fails
- No popup is opened within the timeout (30 seconds by default)
Sourcepub fn opener(&self) -> Option<&str>
pub fn opener(&self) -> Option<&str>
Get the opener page that opened this popup.
Returns None if this page is not a popup (was created via context.new_page()).
Note: This method currently returns None because tracking opener pages
requires context-level state management. For now, you can check if a page
is a popup by examining whether it was returned from wait_for_popup().
Source§impl Page
impl Page
Sourcepub async fn add_init_script(
&self,
script: impl AsRef<str>,
) -> Result<String, PageError>
pub async fn add_init_script( &self, script: impl AsRef<str>, ) -> Result<String, PageError>
Add a script to be evaluated before every page load.
The script will run before any scripts on the page, and will persist across navigations.
§Example
// Modify the navigator before page loads
page.add_init_script("Object.defineProperty(navigator, 'webdriver', { get: () => false })").await?;Source§impl Page
impl Page
Sourcepub fn video(&self) -> Option<&Video>
pub fn video(&self) -> Option<&Video>
Get the video recording controller if video recording is enabled.
Returns None if the page was created without video recording options.
§Example
use viewpoint_core::browser::Browser;
use viewpoint_core::page::VideoOptions;
let browser = Browser::launch().headless(true).launch().await?;
// Video recording is enabled via context options
let context = browser.new_context_builder()
.record_video(VideoOptions::new("./videos"))
.build()
.await?;
let page = context.new_page().await?;
page.goto("https://example.com").goto().await?;
// Access the video after actions
if let Some(video) = page.video() {
let path = video.path().await?;
println!("Video saved to: {}", path.display());
}Source§impl Page
impl Page
Sourcepub fn goto(&self, url: impl Into<String>) -> GotoBuilder<'_>
pub fn goto(&self, url: impl Into<String>) -> GotoBuilder<'_>
Navigate to a URL.
Returns a builder for configuring navigation options.
§Example
use viewpoint_core::Page;
use viewpoint_core::DocumentLoadState;
use std::time::Duration;
// Simple navigation
page.goto("https://example.com").goto().await?;
// Navigation with options
page.goto("https://example.com")
.wait_until(DocumentLoadState::DomContentLoaded)
.timeout(Duration::from_secs(10))
.goto()
.await?;Sourcepub async fn goto_url(
&self,
url: &str,
) -> Result<NavigationResponse, NavigationError>
pub async fn goto_url( &self, url: &str, ) -> Result<NavigationResponse, NavigationError>
Navigate to a URL and wait for the specified load state.
This is a convenience method that calls goto(url).goto().await.
§Errors
Returns an error if:
- The page is closed
- Navigation fails
- The wait times out
Sourcepub fn session_id(&self) -> &str
pub fn session_id(&self) -> &str
Get the session ID.
Sourcepub fn connection(&self) -> &Arc<CdpConnection>
pub fn connection(&self) -> &Arc<CdpConnection>
Get a reference to the CDP connection.
Sourcepub fn screenshot(&self) -> ScreenshotBuilder<'_>
pub fn screenshot(&self) -> ScreenshotBuilder<'_>
Create a screenshot builder for capturing page screenshots.
§Example
// Capture viewport screenshot
let bytes = page.screenshot().capture().await?;
// Capture full page screenshot
page.screenshot()
.full_page(true)
.path("screenshot.png")
.capture()
.await?;
// Capture JPEG with quality
page.screenshot()
.jpeg(Some(80))
.path("screenshot.jpg")
.capture()
.await?;Sourcepub fn pdf(&self) -> PdfBuilder<'_>
pub fn pdf(&self) -> PdfBuilder<'_>
Create a PDF builder for generating PDFs from the page.
§Example
use viewpoint_core::page::PaperFormat;
// Generate PDF with default settings
let bytes = page.pdf().generate().await?;
// Generate A4 landscape PDF
page.pdf()
.format(PaperFormat::A4)
.landscape(true)
.path("document.pdf")
.generate()
.await?;
// Generate PDF with custom margins
page.pdf()
.margin(1.0) // 1 inch margins
.print_background(true)
.generate()
.await?;