Page

Struct Page 

Source
pub struct Page { /* private fields */ }
Expand description

A browser page (tab).

Implementations§

Source§

impl Page

Source

pub async fn expose_function<F, Fut>( &self, name: &str, callback: F, ) -> Result<(), PageError>
where F: Fn(Vec<Value>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Value, String>> + Send + 'static,

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

pub async fn remove_exposed_function(&self, name: &str) -> Result<(), PageError>

Remove an exposed function.

The function will no longer be available in JavaScript after this call.

Source§

impl Page

Source

pub async fn content(&self) -> Result<String, PageError>

Get the full HTML content of the page including the doctype.

§Example
let html = page.content().await?;
println!("Page HTML: {}", html);
§Errors

Returns an error if the page is closed or evaluation fails.

Source

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?;
Source

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?;
Source

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

Source

pub fn viewport_size(&self) -> Option<ViewportSize>

Get the current viewport size.

Returns the width and height in pixels.

Source

pub async fn set_viewport_size( &self, width: i32, height: i32, ) -> Result<(), PageError>

Set the viewport size.

§Example
page.set_viewport_size(1280, 720).await?;
Source

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.

Source

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?;
Source

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

Source

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?;
Source

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

Source

pub async fn evaluate<T>(&self, expression: &str) -> Result<T, PageError>

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. Use serde_json::Value for 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
Source

pub async fn evaluate_with_arg<T, A>( &self, expression: &str, arg: A, ) -> Result<T, PageError>

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?;
Source

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

Source

pub async fn on_dialog<F, Fut>(&self, handler: F)
where F: Fn(Dialog) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), PageError>> + Send + 'static,

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
// 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;
Source

pub async fn off_dialog(&self)

Remove the dialog handler.

After calling this, dialogs will be automatically dismissed.

Source

pub async fn on_console<F, Fut>(&self, handler: F)
where F: Fn(ConsoleMessage) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Set a handler for console messages (console.log, console.error, etc.).

The handler will be called whenever JavaScript code logs to the console.

§Example
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;
Source

pub async fn off_console(&self)

Remove the console message handler.

Source

pub async fn on_pageerror<F, Fut>(&self, handler: F)
where F: Fn(PageError) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Set a handler for page errors (uncaught exceptions).

The handler will be called whenever an uncaught JavaScript exception occurs.

§Example
page.on_pageerror(|error| async move {
    eprintln!("Page error: {}", error.message());
    if let Some(stack) = error.stack() {
        eprintln!("Stack trace:\n{}", stack);
    }
}).await;
Source

pub async fn off_pageerror(&self)

Remove the page error handler.

Source

pub async fn on_frameattached<F, Fut>(&self, handler: F)
where F: Fn(Frame) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

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
page.on_frameattached(|frame| async move {
    println!("Frame attached: {}", frame.url());
}).await;
Source

pub async fn off_frameattached(&self)

Remove the frame attached handler.

Source

pub async fn on_framenavigated<F, Fut>(&self, handler: F)
where F: Fn(Frame) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Set a handler for frame navigated events.

The handler will be called whenever a frame navigates to a new URL.

§Example
page.on_framenavigated(|frame| async move {
    println!("Frame navigated to: {}", frame.url());
}).await;
Source

pub async fn off_framenavigated(&self)

Remove the frame navigated handler.

Source

pub async fn on_framedetached<F, Fut>(&self, handler: F)
where F: Fn(Frame) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

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
page.on_framedetached(|frame| async move {
    println!("Frame detached: {}", frame.id());
}).await;
Source

pub async fn off_framedetached(&self)

Remove the frame detached handler.

Source

pub async fn expect_console<F, Fut>( &self, action: F, ) -> Result<ConsoleMessage, PageError>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), LocatorError>>,

Wait for a console message triggered by an action.

§Example
let message = page.expect_console(async {
    page.locator("#log-button").click().await?;
    Ok(())
}).await?;

println!("Console message: {}", message.text());
Source

pub async fn expect_pageerror<F, Fut>( &self, action: F, ) -> Result<PageError, PageError>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), LocatorError>>,

Wait for a page error triggered by an action.

§Example
let error = page.expect_pageerror(async {
    page.locator("#trigger-error").click().await?;
    Ok(())
}).await?;

println!("Page error: {}", error.message());
Source

pub async fn on_download<F, Fut>(&self, handler: F)
where F: Fn(Download) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Set a handler for file downloads.

The handler will be called whenever a download starts.

§Example
page.on_download(|download| async move {
    let path = download.path().await.unwrap();
    println!("Downloaded: {}", path.display());
}).await;
Source

pub async fn expect_download<F, Fut>( &self, action: F, ) -> Result<Download, PageError>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), LocatorError>>,

Wait for a download triggered by an action.

§Example
let download = page.wait_for_download(async {
    page.locator("a.download").click().await?;
    Ok(())
}).await?;

download.save_as("./my-file.pdf").await?;
Source

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.

Source

pub async fn on_filechooser<F, Fut>(&self, handler: F)
where F: Fn(FileChooser) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Set a handler for file chooser dialogs.

You must call set_intercept_file_chooser(true) before using this.

§Example
page.set_intercept_file_chooser(true).await?;
page.on_filechooser(|chooser| async move {
    chooser.set_files(&["./upload.txt"]).await.unwrap();
}).await;
Source

pub async fn expect_file_chooser<F, Fut>( &self, action: F, ) -> Result<FileChooser, PageError>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), LocatorError>>,

Wait for a file chooser triggered by an action.

You must call set_intercept_file_chooser(true) before using this.

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

Source

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
// 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?;
Source

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
let main_frame = page.main_frame().await?;
println!("Main frame URL: {}", main_frame.url());
Source

pub async fn frames(&self) -> Result<Vec<Frame>, PageError>

Get all frames in the page, including the main frame and all iframes.

§Errors

Returns an error if the frame tree cannot be retrieved.

§Example
let frames = page.frames().await?;
for frame in frames {
    println!("Frame: {} - {}", frame.name(), frame.url());
}
Source

pub async fn frame(&self, name: &str) -> Result<Option<Frame>, PageError>

Get a frame by its name attribute.

Returns None if no frame with the given name is found.

§Errors

Returns an error if the frame tree cannot be retrieved.

§Example
if let Some(frame) = page.frame("payment-frame").await? {
    frame.goto("https://payment.example.com").await?;
}
Source

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
if let Some(frame) = page.frame_by_url("**/checkout/**").await? {
    println!("Found checkout frame: {}", frame.url());
}
Source§

impl Page

Source

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
// 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?;
Source

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
// 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?;
Source

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
page.touchscreen().tap(100.0, 200.0).await?;
Source

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 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?;
Source

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
// Simple drag and drop
page.drag_and_drop("#source", "#target").await?;

// With position options
page.drag_and_drop("#source", "#target")
    .source_position(10.0, 10.0)
    .target_position(5.0, 5.0)
    .await?;
Source§

impl Page

Source

pub fn locator(&self, selector: impl Into<String>) -> Locator<'_>

Create a locator for elements matching a CSS selector.

§Example
let button = page.locator("button.submit");
let items = page.locator(".list > .item");
Source

pub fn get_by_text(&self, text: impl Into<String>) -> Locator<'_>

Create a locator for elements containing the specified text.

§Example
let heading = page.get_by_text("Welcome");
let exact = page.get_by_text_exact("Welcome to our site");
Source

pub fn get_by_text_exact(&self, text: impl Into<String>) -> Locator<'_>

Create a locator for elements with exact text content.

Source

pub fn get_by_role(&self, role: AriaRole) -> RoleLocatorBuilder<'_>

Create a locator for elements with the specified ARIA role.

§Example
let buttons = page.get_by_role(AriaRole::Button);
let submit = page.get_by_role(AriaRole::Button).with_name("Submit");
Source

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
let button = page.get_by_test_id("submit-button");
Source

pub fn test_id_attribute(&self) -> &str

Get the test ID attribute used by this page.

Source

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().

Source

pub fn get_by_label(&self, label: impl Into<String>) -> Locator<'_>

Create a locator for form controls by their associated label text.

§Example
let email = page.get_by_label("Email address");
Source

pub fn get_by_placeholder(&self, placeholder: impl Into<String>) -> Locator<'_>

Create a locator for inputs by their placeholder text.

§Example
let search = page.get_by_placeholder("Search...");
Source

pub fn get_by_alt_text(&self, alt: impl Into<String>) -> Locator<'_>

Create a locator for images by their alt text.

§Example
let logo = page.get_by_alt_text("Company Logo");
Source

pub fn get_by_alt_text_exact(&self, alt: impl Into<String>) -> Locator<'_>

Create a locator for images with exact alt text.

Source

pub fn get_by_title(&self, title: impl Into<String>) -> Locator<'_>

Create a locator for elements by their title attribute.

§Example
let tooltip = page.get_by_title("Click to expand");
Source

pub fn get_by_title_exact(&self, title: impl Into<String>) -> Locator<'_>

Create a locator for elements with exact title attribute.

Source§

impl Page

Source

pub async fn add_locator_handler<F, Fut>( &self, locator: impl Into<Locator<'_>>, handler: F, ) -> LocatorHandlerHandle
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), LocatorError>> + Send + 'static,

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
// Dismiss cookie banner when it appears
let handle = page.add_locator_handler(
    page.get_by_role(AriaRole::Button).with_name("Accept cookies"),
    || async {
        page.locator(".cookie-banner .accept").click().await
    }
).await;

// Later, remove the handler
page.remove_locator_handler(handle).await;
Source

pub async fn add_locator_handler_with_options<F, Fut>( &self, locator: impl Into<Locator<'_>>, handler: F, options: LocatorHandlerOptions, ) -> LocatorHandlerHandle
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), LocatorError>> + Send + 'static,

Add a locator handler with options.

§Example
// Handler that only runs once
page.add_locator_handler_with_options(
    page.locator(".popup"),
    || async { page.locator(".popup .close").click().await },
    LocatorHandlerOptions { times: Some(1), ..Default::default() }
).await;
Source

pub async fn remove_locator_handler(&self, handle: LocatorHandlerHandle)

Remove a locator handler.

Source§

impl Page

Source

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");
}
Source

pub async fn go_forward( &self, ) -> Result<Option<NavigationResponse>, NavigationError>

Navigate forward in history.

Returns None if there is no next page in history.

Source

pub async fn reload(&self) -> Result<NavigationResponse, NavigationError>

Reload the current page.

§Example
page.reload().await?;
Source§

impl Page

Source

pub async fn route<M, H, Fut>( &self, pattern: M, handler: H, ) -> Result<(), NetworkError>
where M: Into<UrlPattern>, H: Fn(Route) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,

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::Route;

// 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?;
Source

pub async fn route_predicate<P, H, Fut>( &self, predicate: P, handler: H, ) -> Result<(), NetworkError>
where P: Fn(&str) -> bool + Send + Sync + 'static, H: Fn(Route) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,

Register a route handler with a predicate function.

§Example
// 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?;
Source

pub async fn unroute(&self, pattern: &str)

Unregister handlers matching the given pattern.

§Example
page.route("**/*.css", handler).await?;
// Later...
page.unroute("**/*.css").await;
Source

pub async fn unroute_all(&self)

Unregister all route handlers.

§Example
page.unroute_all().await;
Source

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

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, TimingMode};

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

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;

// Wait for any API request
let request = page.wait_for_request("**/api/**")
    .timeout(Duration::from_secs(10))
    .wait()
    .await?;

println!("Request URL: {}", request.url());

// Wait for a specific request
let request = page.wait_for_request("**/users")
    .wait()
    .await?;
Source

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;

// Wait for any API response
let response = page.wait_for_response("**/api/**")
    .timeout(Duration::from_secs(10))
    .wait()
    .await?;

println!("Response status: {}", response.status());

// Get the response body
let body = response.text().await?;
Source

pub async fn on_websocket<F, Fut>(&self, handler: F)
where F: Fn(WebSocket) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

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

pub async fn off_websocket(&self)

Remove the WebSocket event handler.

Source§

impl Page

Source

pub async fn on_popup<F, Fut>(&self, handler: F)
where F: Fn(Page) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

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
page.on_popup(|popup| async move {
    println!("Popup opened: {}", popup.url().await.unwrap_or_default());
    // Work with the popup
    popup.close().await?;
    Ok(())
}).await;
Source

pub async fn off_popup(&self)

Remove the popup handler.

Source

pub fn wait_for_popup<F, Fut>( &self, action: F, ) -> WaitForPopupBuilder<'_, F, Fut>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), LocatorError>>,

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
let popup = page.wait_for_popup(|| async {
    page.locator("a[target=_blank]").click().await
}).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)
Source

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

Source

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

pub async fn add_init_script_path( &self, path: impl AsRef<Path>, ) -> Result<String, PageError>

Add an init script from a file path.

§Errors

Returns an error if the file cannot be read or the script cannot be added.

Source§

impl Page

Source

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
// Video recording is enabled via context options
let context = browser.new_context()
    .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

Source

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?;
Source

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
Source

pub async fn close(&mut self) -> Result<(), PageError>

Close this page.

§Errors

Returns an error if closing fails.

Source

pub fn target_id(&self) -> &str

Get the target ID.

Source

pub fn session_id(&self) -> &str

Get the session ID.

Source

pub fn frame_id(&self) -> &str

Get the main frame ID.

Source

pub fn is_closed(&self) -> bool

Check if this page has been closed.

Source

pub fn connection(&self) -> &Arc<CdpConnection>

Get a reference to the CDP connection.

Source

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?;
Source

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?;
Source

pub async fn url(&self) -> Result<String, PageError>

Get the current page URL.

§Errors

Returns an error if the page is closed or the evaluation fails.

Source

pub async fn title(&self) -> Result<String, PageError>

Get the current page title.

§Errors

Returns an error if the page is closed or the evaluation fails.

Trait Implementations§

Source§

impl Debug for Page

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'a> Expectable<'a> for Page

Source§

type Assertions = PageAssertions<'a>

The assertion builder type for this value.
Source§

fn assertions(&'a self) -> Self::Assertions

Create an assertion builder for this value.

Auto Trait Implementations§

§

impl !Freeze for Page

§

impl !RefUnwindSafe for Page

§

impl Send for Page

§

impl Sync for Page

§

impl Unpin for Page

§

impl !UnwindSafe for Page

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

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

Source§

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

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