Skip to main content

Page

Struct Page 

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

Page represents a web page within a browser context.

A Page is created when you call BrowserContext::new_page() or Browser::new_page(). Each page is an isolated tab/window within its parent context.

Initially, pages are navigated to “about:blank”. Use navigation methods Use navigation methods to navigate to URLs.

§Example

use playwright_rs::protocol::{
    Playwright, ScreenshotOptions, ScreenshotType, AddStyleTagOptions, AddScriptTagOptions,
    EmulateMediaOptions, Media, ColorScheme, Viewport,
};
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let playwright = Playwright::launch().await?;
    let browser = playwright.chromium().launch().await?;
    let page = browser.new_page().await?;

    // Demonstrate url() - initially at about:blank
    assert_eq!(page.url(), "about:blank");

    // Demonstrate goto() - navigate to a page
    let html = r#"<!DOCTYPE html>
        <html>
            <head><title>Test Page</title></head>
            <body>
                <h1 id="heading">Hello World</h1>
                <p>First paragraph</p>
                <p>Second paragraph</p>
                <button onclick="alert('Alert!')">Alert</button>
                <a href="data:text/plain,file" download="test.txt">Download</a>
            </body>
        </html>
    "#;
    // Data URLs may not return a response (this is normal)
    let _response = page.goto(&format!("data:text/html,{}", html), None).await?;

    // Demonstrate title()
    let title = page.title().await?;
    assert_eq!(title, "Test Page");

    // Demonstrate content() - returns full HTML including DOCTYPE
    let content = page.content().await?;
    assert!(content.contains("<!DOCTYPE html>") || content.to_lowercase().contains("<!doctype html>"));
    assert!(content.contains("<title>Test Page</title>"));
    assert!(content.contains("Hello World"));

    // Demonstrate locator()
    let heading = page.locator("#heading").await;
    let text = heading.text_content().await?;
    assert_eq!(text, Some("Hello World".to_string()));

    // Demonstrate query_selector()
    let element = page.query_selector("h1").await?;
    assert!(element.is_some(), "Should find the h1 element");

    // Demonstrate query_selector_all()
    let paragraphs = page.query_selector_all("p").await?;
    assert_eq!(paragraphs.len(), 2);

    // Demonstrate evaluate()
    page.evaluate::<(), ()>("console.log('Hello from Playwright!')", None).await?;

    // Demonstrate evaluate_value()
    let result = page.evaluate_value("1 + 1").await?;
    assert_eq!(result, "2");

    // Demonstrate screenshot()
    let bytes = page.screenshot(None).await?;
    assert!(!bytes.is_empty());

    // Demonstrate screenshot_to_file()
    let temp_dir = std::env::temp_dir();
    let path = temp_dir.join("playwright_doctest_screenshot.png");
    let bytes = page.screenshot_to_file(&path, Some(
        ScreenshotOptions::builder()
            .screenshot_type(ScreenshotType::Png)
            .build()
    )).await?;
    assert!(!bytes.is_empty());

    // Demonstrate reload()
    // Data URLs may not return a response on reload (this is normal)
    let _response = page.reload(None).await?;

    // Demonstrate route() - network interception
    page.route("**/*.png", |route| async move {
        route.abort(None).await
    }).await?;

    // Demonstrate on_download() - download handler
    page.on_download(|download| async move {
        println!("Download started: {}", download.url());
        Ok(())
    }).await?;

    // Demonstrate on_dialog() - dialog handler
    page.on_dialog(|dialog| async move {
        println!("Dialog: {} - {}", dialog.type_(), dialog.message());
        dialog.accept(None).await
    }).await?;

    // Demonstrate add_style_tag() - inject CSS
    page.add_style_tag(
        AddStyleTagOptions::builder()
            .content("body { background-color: blue; }")
            .build()
    ).await?;

    // Demonstrate set_extra_http_headers() - set page-level headers
    let mut headers = std::collections::HashMap::new();
    headers.insert("x-custom-header".to_string(), "value".to_string());
    page.set_extra_http_headers(headers).await?;

    // Demonstrate emulate_media() - emulate print media type
    page.emulate_media(Some(
        EmulateMediaOptions::builder()
            .media(Media::Print)
            .color_scheme(ColorScheme::Dark)
            .build()
    )).await?;

    // Demonstrate add_script_tag() - inject a script
    page.add_script_tag(Some(
        AddScriptTagOptions::builder()
            .content("window.injectedByScriptTag = true;")
            .build()
    )).await?;

    // Demonstrate pdf() - generate PDF (Chromium only)
    let pdf_bytes = page.pdf(None).await?;
    assert!(!pdf_bytes.is_empty());

    // Demonstrate set_viewport_size() - responsive testing
    let mobile_viewport = Viewport {
        width: 375,
        height: 667,
    };
    page.set_viewport_size(mobile_viewport).await?;

    // Demonstrate close()
    page.close().await?;

    browser.close().await?;
    Ok(())
}

See: https://playwright.dev/docs/api/class-page

Implementations§

Source§

impl Page

Source

pub fn new( parent: Arc<dyn ChannelOwner>, type_name: String, guid: Arc<str>, initializer: Value, ) -> Result<Self>

Creates a new Page from protocol initialization

This is called by the object factory when the server sends a __create__ message for a Page object.

§Arguments
  • parent - The parent BrowserContext object
  • type_name - The protocol type name (“Page”)
  • guid - The unique identifier for this page
  • initializer - The initialization data from the server
§Errors

Returns error if initializer is malformed

Source

pub async fn main_frame(&self) -> Result<Frame>

Returns the main frame of the page.

The main frame is where navigation and DOM operations actually happen.

This method also wires up the back-reference from the frame to the page so that frame.page(), frame.locator(), and frame.get_by_*() work correctly.

Source

pub fn url(&self) -> String

Returns the current URL of the page.

This returns the last committed URL, including hash fragments from anchor navigation. Initially, pages are at “about:blank”.

See: https://playwright.dev/docs/api/class-page#page-url

Source

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

Closes the page.

This is a graceful operation that sends a close command to the page and waits for it to shut down properly.

§Errors

Returns error if:

  • Page has already been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-close

Source

pub fn is_closed(&self) -> bool

Returns whether the page has been closed.

Returns true after close() has been called on this page, or after the page receives a close event from the server (e.g. when the browser context is closed).

See: https://playwright.dev/docs/api/class-page#page-is-closed

Source

pub fn console_messages(&self) -> Vec<ConsoleMessage>

Returns all console messages received so far on this page.

Messages are accumulated in order as they arrive via the console event. Each call returns a snapshot; new messages arriving concurrently may or may not be included depending on timing.

See: https://playwright.dev/docs/api/class-page#page-console-messages

Source

pub fn page_errors(&self) -> Vec<String>

Returns all uncaught JavaScript error messages received so far on this page.

Errors are accumulated in order as they arrive via the pageError event. Each string is the .message field of the thrown Error.

Source

pub async fn opener(&self) -> Result<Option<Page>>

Returns the page that opened this popup, or None if this page was not opened by another page.

The opener is available from the page’s initializer — it is the page that called window.open() or triggered a link with target="_blank". Returns None for top-level pages that were not opened as popups.

§Errors

Returns error if the opener page GUID is present in the initializer but the object is not found in the connection registry.

See: https://playwright.dev/docs/api/class-page#page-opener

Source

pub fn workers(&self) -> Vec<Worker>

Returns all active web workers belonging to this page.

Workers are tracked as they are created (worker event) and this method returns a snapshot of the current list.

See: https://playwright.dev/docs/api/class-page#page-workers

Source

pub async fn set_default_timeout(&self, timeout: f64)

Sets the default timeout for all operations on this page.

The timeout applies to actions such as click, fill, locator.wait_for, etc. Pass 0 to disable timeouts.

This stores the value locally so that subsequent action calls use it when no explicit timeout is provided, and also notifies the Playwright server so it can apply the same default on its side.

§Arguments
  • timeout - Timeout in milliseconds

See: https://playwright.dev/docs/api/class-page#page-set-default-timeout

Source

pub async fn set_default_navigation_timeout(&self, timeout: f64)

Sets the default timeout for navigation operations on this page.

The timeout applies to navigation actions such as goto, reload, go_back, and go_forward. Pass 0 to disable timeouts.

§Arguments
  • timeout - Timeout in milliseconds

See: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout

Source

pub fn default_timeout_ms(&self) -> f64

Returns the current default action timeout in milliseconds.

Source

pub fn default_navigation_timeout_ms(&self) -> f64

Returns the current default navigation timeout in milliseconds.

Source

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

Returns all frames in the page, including the main frame.

Currently returns only the main (top-level) frame. Iframe enumeration is not yet implemented and will be added in a future release.

§Errors

Returns error if:

  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-frames

Source

pub async fn goto( &self, url: &str, options: Option<GotoOptions>, ) -> Result<Option<Response>>

Navigates to the specified URL.

Returns None when navigating to URLs that don’t produce responses (e.g., data URLs, about:blank). This matches Playwright’s behavior across all language bindings.

§Arguments
  • url - The URL to navigate to
  • options - Optional navigation options (timeout, wait_until)
§Errors

Returns error if:

  • URL is invalid
  • Navigation timeout (default 30s)
  • Network error

See: https://playwright.dev/docs/api/class-page#page-goto

Source

pub fn context(&self) -> Result<BrowserContext>

Returns the browser context that the page belongs to.

Source

pub fn clock(&self) -> Result<Clock>

Returns the Clock object for this page’s browser context.

This is a convenience accessor that delegates to the parent context’s clock. All clock RPCs are sent on the BrowserContext channel regardless of whether the Clock is obtained via page.clock() or context.clock().

§Errors

Returns error if the page’s parent is not a BrowserContext.

See: https://playwright.dev/docs/api/class-clock

Source

pub fn video(&self) -> Option<Video>

Returns the Video object associated with this page, if video recording is enabled.

Returns Some(Video) when the browser context was created with the record_video option; returns None otherwise.

The Video shell is created eagerly. The underlying recording artifact is wired up when the Playwright server fires the internal "video" event (which typically happens when the page is first navigated). Calling crate::protocol::Video::save_as or crate::protocol::Video::path before the artifact arrives returns an error; close the page first to guarantee the artifact is ready.

See: https://playwright.dev/docs/api/class-page#page-video

Source

pub async fn pause(&self) -> Result<()>

Pauses script execution.

Playwright will stop executing the script and wait for the user to either press “Resume” in the page overlay or in the debugger.

See: https://playwright.dev/docs/api/class-page#page-pause

Source

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

Source

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

Returns the full HTML content of the page, including the DOCTYPE.

This method retrieves the complete HTML markup of the page, including the doctype declaration and all DOM elements.

See: https://playwright.dev/docs/api/class-page#page-content

Source

pub async fn set_content( &self, html: &str, options: Option<GotoOptions>, ) -> Result<()>

Source

pub async fn wait_for_load_state(&self, state: Option<WaitUntil>) -> Result<()>

Waits for the required load state to be reached.

This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If the current document has already reached the required state, resolves immediately.

See: https://playwright.dev/docs/api/class-page#page-wait-for-load-state

Source

pub async fn wait_for_url( &self, url: &str, options: Option<GotoOptions>, ) -> Result<()>

Waits for the main frame to navigate to a URL matching the given string or glob pattern.

See: https://playwright.dev/docs/api/class-page#page-wait-for-url

Source

pub async fn locator(&self, selector: &str) -> Locator

Creates a locator for finding elements on the page.

Locators are the central piece of Playwright’s auto-waiting and retry-ability. They don’t execute queries until an action is performed.

§Arguments
  • selector - CSS selector or other locating strategy

See: https://playwright.dev/docs/api/class-page#page-locator

Source

pub async fn frame_locator(&self, selector: &str) -> FrameLocator

Creates a FrameLocator for an iframe on this page.

The selector identifies the iframe element (e.g., "iframe[name='content']").

See: https://playwright.dev/docs/api/class-page#page-frame-locator

Source

pub async fn get_by_text(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements containing the given text.

By default, matching is case-insensitive and searches for a substring. Set exact to true for case-sensitive exact matching.

See: https://playwright.dev/docs/api/class-page#page-get-by-text

Source

pub async fn get_by_label(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their associated label text.

See: https://playwright.dev/docs/api/class-page#page-get-by-label

Source

pub async fn get_by_placeholder(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their placeholder text.

See: https://playwright.dev/docs/api/class-page#page-get-by-placeholder

Source

pub async fn get_by_alt_text(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their alt text.

See: https://playwright.dev/docs/api/class-page#page-get-by-alt-text

Source

pub async fn get_by_title(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their title attribute.

See: https://playwright.dev/docs/api/class-page#page-get-by-title

Source

pub async fn get_by_test_id(&self, test_id: &str) -> Locator

Returns a locator that matches elements by their test ID attribute.

By default, uses the data-testid attribute. Call playwright.selectors().set_test_id_attribute() to change the attribute name.

Always uses exact matching (case-sensitive).

See: https://playwright.dev/docs/api/class-page#page-get-by-test-id

Source

pub async fn get_by_role( &self, role: AriaRole, options: Option<GetByRoleOptions>, ) -> Locator

Returns a locator that matches elements by their ARIA role.

See: https://playwright.dev/docs/api/class-page#page-get-by-role

Source

pub fn keyboard(&self) -> Keyboard

Returns the keyboard instance for low-level keyboard control.

See: https://playwright.dev/docs/api/class-page#page-keyboard

Source

pub fn mouse(&self) -> Mouse

Returns the mouse instance for low-level mouse control.

See: https://playwright.dev/docs/api/class-page#page-mouse

Source

pub fn touchscreen(&self) -> Touchscreen

Returns the touchscreen instance for low-level touch input simulation.

Requires a touch-enabled browser context (has_touch: true in BrowserContextOptions).

See: https://playwright.dev/docs/api/class-page#page-touchscreen

Source

pub async fn drag_and_drop( &self, source: &str, target: &str, options: Option<DragToOptions>, ) -> Result<()>

Performs a drag from source selector to target selector.

This is the page-level equivalent of Locator::drag_to(). It resolves both selectors in the main frame and performs the drag.

§Arguments
  • source - A CSS selector for the element to drag from
  • target - A CSS selector for the element to drop onto
  • options - Optional drag options (positions, force, timeout, trial)
§Errors

Returns error if either selector does not resolve to an element, the drag action times out, or the page has been closed.

See: https://playwright.dev/docs/api/class-page#page-drag-and-drop

Source

pub async fn reload( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>

Reloads the current page.

§Arguments
  • options - Optional reload options (timeout, wait_until)

Returns None when reloading pages that don’t produce responses (e.g., data URLs, about:blank). This matches Playwright’s behavior across all language bindings.

See: https://playwright.dev/docs/api/class-page#page-reload

Source

pub async fn go_back( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>

Navigates to the previous page in history.

Returns the main resource response. In case of multiple server redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns None.

See: https://playwright.dev/docs/api/class-page#page-go-back

Source

pub async fn go_forward( &self, options: Option<GotoOptions>, ) -> Result<Option<Response>>

Navigates to the next page in history.

Returns the main resource response. In case of multiple server redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns None.

See: https://playwright.dev/docs/api/class-page#page-go-forward

Source

pub async fn query_selector( &self, selector: &str, ) -> Result<Option<Arc<ElementHandle>>>

Returns the first element matching the selector, or None if not found.

See: https://playwright.dev/docs/api/class-page#page-query-selector

Source

pub async fn query_selector_all( &self, selector: &str, ) -> Result<Vec<Arc<ElementHandle>>>

Returns all elements matching the selector.

See: https://playwright.dev/docs/api/class-page#page-query-selector-all

Source

pub async fn screenshot( &self, options: Option<ScreenshotOptions>, ) -> Result<Vec<u8>>

Takes a screenshot of the page and returns the image bytes.

See: https://playwright.dev/docs/api/class-page#page-screenshot

Source

pub async fn screenshot_to_file( &self, path: &Path, options: Option<ScreenshotOptions>, ) -> Result<Vec<u8>>

Takes a screenshot and saves it to a file, also returning the bytes.

See: https://playwright.dev/docs/api/class-page#page-screenshot

Source

pub async fn evaluate_expression(&self, expression: &str) -> Result<()>

Evaluates JavaScript in the page context (without return value).

Executes the provided JavaScript expression or function within the page’s context without returning a value.

See: https://playwright.dev/docs/api/class-page#page-evaluate

Source

pub async fn evaluate<T: Serialize, U: DeserializeOwned>( &self, expression: &str, arg: Option<&T>, ) -> Result<U>

Evaluates JavaScript in the page context with optional arguments.

Executes the provided JavaScript expression or function within the page’s context and returns the result. The return value must be JSON-serializable.

§Arguments
  • expression - JavaScript code to evaluate
  • arg - Optional argument to pass to the expression (must implement Serialize)
§Returns

The result as a serde_json::Value

See: https://playwright.dev/docs/api/class-page#page-evaluate

Source

pub async fn evaluate_value(&self, expression: &str) -> Result<String>

Evaluates a JavaScript expression and returns the result as a String.

§Arguments
  • expression - JavaScript code to evaluate
§Returns

The result converted to a String

See: https://playwright.dev/docs/api/class-page#page-evaluate

Source

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

Registers a route handler for network interception.

When a request matches the specified pattern, the handler will be called with a Route object that can abort, continue, or fulfill the request.

§Arguments
  • pattern - URL pattern to match (supports glob patterns like “**/*.png”)
  • handler - Async closure that handles the route

See: https://playwright.dev/docs/api/class-page#page-route

Source

pub async fn unroute(&self, pattern: &str) -> Result<()>

Removes route handler(s) matching the given URL pattern.

§Arguments
  • pattern - URL pattern to remove handlers for

See: https://playwright.dev/docs/api/class-page#page-unroute

Source

pub async fn unroute_all( &self, _behavior: Option<UnrouteBehavior>, ) -> Result<()>

Removes all registered route handlers.

§Arguments
  • behavior - Optional behavior for in-flight handlers

See: https://playwright.dev/docs/api/class-page#page-unroute-all

Source

pub async fn route_from_har( &self, har_path: &str, options: Option<RouteFromHarOptions>, ) -> Result<()>

Replays network requests from a HAR file recorded previously.

Requests matching options.url (or all requests if omitted) will be served from the archive instead of hitting the network. Unmatched requests are either aborted or passed through depending on options.not_found ("abort" is the default).

§Arguments
  • har_path - Path to the .har file on disk
  • options - Optional settings (url filter, not_found policy, update mode)
§Errors

Returns error if:

  • har_path does not exist or cannot be read by the Playwright server
  • The Playwright server fails to open the archive

See: https://playwright.dev/docs/api/class-page#page-route-from-har

Source

pub async fn route_web_socket<F, Fut>( &self, url: &str, handler: F, ) -> Result<()>
where F: Fn(WebSocketRoute) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Intercepts WebSocket connections matching the given URL pattern.

When a WebSocket connection from the page matches url, the handler is called with a WebSocketRoute object. The handler must call connect_to_server to forward the connection to the real server, or close to terminate it.

§Arguments
  • url — URL glob pattern (e.g. "ws://**" or "wss://example.com/ws").
  • handler — Async closure receiving a WebSocketRoute.
§Errors

Returns an error if the RPC call to enable interception fails.

See: https://playwright.dev/docs/api/class-page#page-route-web-socket

Source

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

Registers a download event handler.

The handler will be called when a download is triggered by the page. Downloads occur when the page initiates a file download (e.g., clicking a link with the download attribute, or a server response with Content-Disposition: attachment).

§Arguments
  • handler - Async closure that receives the Download object

See: https://playwright.dev/docs/api/class-page#page-event-download

Source

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

Registers a dialog event handler.

The handler will be called when a JavaScript dialog is triggered (alert, confirm, prompt, or beforeunload). The dialog must be explicitly accepted or dismissed, otherwise the page will freeze.

§Arguments
  • handler - Async closure that receives the Dialog object

See: https://playwright.dev/docs/api/class-page#page-event-dialog

Source

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

Registers a console event handler.

The handler is called whenever the page emits a JavaScript console message (e.g. console.log, console.error, console.warn, etc.).

The server only sends console events after the first handler is registered (subscription is managed automatically).

§Arguments

See: https://playwright.dev/docs/api/class-page#page-event-console

Source

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

Registers a handler for file chooser events.

The handler is called whenever the page opens a file chooser dialog (e.g. when the user clicks an <input type="file"> element).

Use FileChooser::set_files inside the handler to satisfy the file chooser without OS-level interaction.

The server only sends "fileChooser" events after the first handler is registered (subscription is managed automatically via updateSubscription).

§Arguments
§Example
page.on_filechooser(|chooser| async move {
    chooser.set_files(&[std::path::PathBuf::from("/tmp/file.txt")]).await
}).await?;

See: https://playwright.dev/docs/api/class-page#page-event-file-chooser

Source

pub async fn expect_file_chooser( &self, timeout: Option<f64>, ) -> Result<EventWaiter<FileChooser>>

Creates a one-shot waiter that resolves when the next file chooser opens.

The waiter must be created before the action that triggers the file chooser to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if the file chooser does not open within the timeout.

§Example
// Set up waiter BEFORE triggering the file chooser
let waiter = page.expect_file_chooser(None).await?;
page.locator("input[type=file]").await.click(None).await?;
let chooser = waiter.wait().await?;
chooser.set_files(&[PathBuf::from("/tmp/file.txt")]).await?;

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_popup( &self, timeout: Option<f64>, ) -> Result<EventWaiter<Page>>

Creates a one-shot waiter that resolves when the next popup window opens.

The waiter must be created before the action that opens the popup to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if no popup opens within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_download( &self, timeout: Option<f64>, ) -> Result<EventWaiter<Download>>

Creates a one-shot waiter that resolves when the next download starts.

The waiter must be created before the action that triggers the download to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if no download starts within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_response( &self, timeout: Option<f64>, ) -> Result<EventWaiter<ResponseObject>>

Creates a one-shot waiter that resolves when the next network response is received.

The waiter must be created before the action that triggers the response to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if no response arrives within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_request( &self, timeout: Option<f64>, ) -> Result<EventWaiter<Request>>

Creates a one-shot waiter that resolves when the next network request is issued.

The waiter must be created before the action that issues the request to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if no request is issued within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_console_message( &self, timeout: Option<f64>, ) -> Result<EventWaiter<ConsoleMessage>>

Creates a one-shot waiter that resolves when the next console message is produced.

The waiter must be created before the action that produces the console message to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::Timeout if no console message is produced within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

pub async fn expect_event( &self, event: &str, timeout: Option<f64>, ) -> Result<EventWaiter<EventValue>>

Waits for the given event to fire and returns a typed EventValue.

This is the generic version of the specific expect_* methods. It matches the playwright-python / playwright-js page.expect_event(event_name) API.

The waiter must be created before the action that triggers the event.

§Supported event names

"request", "response", "popup", "download", "console", "filechooser", "close", "load", "crash", "pageerror", "frameattached", "framedetached", "framenavigated", "worker"

§Arguments
  • event - Event name (case-sensitive, matches Playwright protocol names).
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns crate::error::Error::InvalidArgument for unknown event names. Returns crate::error::Error::Timeout if the event does not fire within the timeout.

See: https://playwright.dev/docs/api/class-page#page-wait-for-event

Source

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

Source

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

Source

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

Source

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

Source

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

Adds a listener for the websocket event.

The handler will be called when a WebSocket request is dispatched.

§Arguments
  • handler - The function to call when the event occurs

See: https://playwright.dev/docs/api/class-page#page-on-websocket

Source

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

Registers a handler for the worker event.

The handler is called when a new Web Worker is created in the page.

§Arguments
  • handler - Async closure called with the new Worker object

See: https://playwright.dev/docs/api/class-page#page-event-worker

Source

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

Registers a handler for the close event.

The handler is called when the page is closed, either by calling page.close(), by the browser context being closed, or when the browser process exits.

§Arguments
  • handler - Async closure called with no arguments when the page closes

See: https://playwright.dev/docs/api/class-page#page-event-close

Source

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

Registers a handler for the load event.

The handler is called when the page’s load event fires, i.e. after all resources including stylesheets and images have finished loading.

The server only sends "load" events after the first handler is registered (subscription is managed automatically).

§Arguments
  • handler - Async closure called with no arguments when the page loads

See: https://playwright.dev/docs/api/class-page#page-event-load

Source

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

Registers a handler for the crash event.

The handler is called when the page crashes (e.g. runs out of memory).

§Arguments
  • handler - Async closure called with no arguments when the page crashes

See: https://playwright.dev/docs/api/class-page#page-event-crash

Source

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

Registers a handler for the pageError event.

The handler is called when an uncaught JavaScript exception is thrown in the page. The handler receives the error message as a String.

The server only sends "pageError" events after the first handler is registered (subscription is managed automatically).

§Arguments
  • handler - Async closure that receives the error message string

See: https://playwright.dev/docs/api/class-page#page-event-page-error

Source

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

Registers a handler for the popup event.

The handler is called when the page opens a popup window (e.g. via window.open()). The handler receives the new popup Page object.

The server only sends "popup" events after the first handler is registered (subscription is managed automatically).

§Arguments
  • handler - Async closure that receives the popup Page

See: https://playwright.dev/docs/api/class-page#page-event-popup

Source

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

Registers a handler for the frameAttached event.

The handler is called when a new frame (iframe) is attached to the page. The handler receives the attached Frame object.

§Arguments
  • handler - Async closure that receives the attached Frame

See: https://playwright.dev/docs/api/class-page#page-event-frameattached

Source

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

Registers a handler for the frameDetached event.

The handler is called when a frame (iframe) is detached from the page. The handler receives the detached Frame object.

§Arguments
  • handler - Async closure that receives the detached Frame

See: https://playwright.dev/docs/api/class-page#page-event-framedetached

Source

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

Registers a handler for the frameNavigated event.

The handler is called when a frame navigates to a new URL. The handler receives the navigated Frame object.

§Arguments
  • handler - Async closure that receives the navigated Frame

See: https://playwright.dev/docs/api/class-page#page-event-framenavigated

Source

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

Exposes a Rust function to this page as window[name] in JavaScript.

When JavaScript code calls window[name](arg1, arg2, …) the Playwright server fires a bindingCall event on the page channel that invokes callback with the deserialized arguments. The return value is sent back to JS so the await window[name](…) expression resolves with it.

The binding is page-scoped and not visible to other pages in the same context.

§Arguments
  • name – JavaScript identifier that will be available as window[name].
  • callback – Async closure called with Vec<serde_json::Value> (JS arguments) returning serde_json::Value (the result).
§Errors

Returns error if:

  • The page has been closed.
  • Communication with the browser process fails.

See: https://playwright.dev/docs/api/class-page#page-expose-function

Source

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

Exposes a Rust function to this page as window[name] in JavaScript, with needsHandle: true.

Identical to expose_function but the Playwright server passes the first argument as a JSHandle object rather than a plain value.

§Arguments
  • name – JavaScript identifier.
  • callback – Async closure with Vec<serde_json::Value>serde_json::Value.
§Errors

Returns error if:

  • The page has been closed.
  • Communication with the browser process fails.

See: https://playwright.dev/docs/api/class-page#page-expose-binding

Source

pub async fn add_locator_handler<F, Fut>( &self, locator: &Locator, handler: F, options: Option<AddLocatorHandlerOptions>, ) -> Result<()>
where F: Fn(Locator) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Registers a handler function that runs whenever a locator matches an element on the page.

This is useful for handling overlays (cookie banners, modals, permission dialogs) that appear unexpectedly and need to be dismissed before test actions can proceed.

When a matching element appears, Playwright sends a locatorHandlerTriggered event. The handler is called with the matching Locator. After the handler completes, Playwright is notified via resolveLocatorHandler so it can resume pending actions.

§Arguments
  • locator - A locator identifying the overlay element to watch for
  • handler - Async function called with the matching Locator when the element appears
  • options - Optional settings (no_wait_after, times)
§Errors

Returns error if communication with the browser process fails.

See: https://playwright.dev/docs/api/class-page#page-add-locator-handler

Source

pub async fn remove_locator_handler(&self, locator: &Locator) -> Result<()>

Removes a previously registered locator handler.

Sends unregisterLocatorHandler to the Playwright server using the uid that was assigned when the handler was first registered.

§Arguments
  • locator - The same locator that was passed to add_locator_handler
§Errors

Returns error if no handler for this locator is registered, or if communication with the browser process fails.

See: https://playwright.dev/docs/api/class-page#page-remove-locator-handler

Source

pub async fn trigger_dialog_event(&self, dialog: Dialog)

Triggers dialog event (called by BrowserContext when dialog events arrive)

Dialog events are sent to BrowserContext and forwarded to the associated Page. This method is public so BrowserContext can forward dialog events.

Source

pub async fn add_style_tag( &self, options: AddStyleTagOptions, ) -> Result<Arc<ElementHandle>>

Adds a <style> tag into the page with the desired content.

§Arguments
  • options - Style tag options (content, url, or path)
§Returns

Returns an ElementHandle pointing to the injected <style> tag

§Example
use playwright_rs::protocol::AddStyleTagOptions;

// With inline CSS
page.add_style_tag(
    AddStyleTagOptions::builder()
        .content("body { background-color: red; }")
        .build()
).await?;

// With external URL
page.add_style_tag(
    AddStyleTagOptions::builder()
        .url("https://example.com/style.css")
        .build()
).await?;

// From file
page.add_style_tag(
    AddStyleTagOptions::builder()
        .path("./styles/custom.css")
        .build()
).await?;

See: https://playwright.dev/docs/api/class-page#page-add-style-tag

Source

pub async fn add_init_script(&self, script: &str) -> Result<()>

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever the page is navigated
  • Whenever a child frame is attached or navigated

The script is evaluated after the document was created but before any of its scripts were run.

§Arguments
  • script - JavaScript code to be injected into the page
§Example
page.add_init_script("window.injected = 123;").await?;

See: https://playwright.dev/docs/api/class-page#page-add-init-script

Source

pub async fn set_viewport_size(&self, viewport: Viewport) -> Result<()>

Sets the viewport size for the page.

This method allows dynamic resizing of the viewport after page creation, useful for testing responsive layouts at different screen sizes.

§Arguments
  • viewport - The viewport dimensions (width and height in pixels)
§Example
// Set viewport to mobile size
let mobile = Viewport {
    width: 375,
    height: 667,
};
page.set_viewport_size(mobile).await?;

// Later, test desktop layout
let desktop = Viewport {
    width: 1920,
    height: 1080,
};
page.set_viewport_size(desktop).await?;
§Errors

Returns error if:

  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-set-viewport-size

Source

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

Brings this page to the front (activates the tab).

Activates the page in the browser, making it the focused tab. This is useful in multi-page tests to ensure actions target the correct page.

§Errors

Returns error if:

  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-bring-to-front

Source

pub async fn request_gc(&self) -> Result<()>

Forces garbage collection in the browser (Chromium only).

See: https://playwright.dev/docs/api/class-page#page-request-gc

Source

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

Sets extra HTTP headers that will be sent with every request from this page.

These headers are sent in addition to headers set on the browser context via BrowserContext::set_extra_http_headers(). Page-level headers take precedence over context-level headers when names conflict.

§Arguments
  • headers - Map of header names to values.
§Errors

Returns error if:

  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-set-extra-http-headers

Source

pub async fn emulate_media( &self, options: Option<EmulateMediaOptions>, ) -> Result<()>

Emulates media features for the page.

This method allows emulating CSS media features such as media, color-scheme, reduced-motion, and forced-colors. Pass None to call with no changes.

To reset a specific feature to the browser default, use the NoOverride variant.

§Arguments
  • options - Optional emulation options. If None, this is a no-op.
§Example
// Emulate print media
page.emulate_media(Some(
    EmulateMediaOptions::builder()
        .media(Media::Print)
        .build()
)).await?;

// Emulate dark color scheme
page.emulate_media(Some(
    EmulateMediaOptions::builder()
        .color_scheme(ColorScheme::Dark)
        .build()
)).await?;
§Errors

Returns error if:

  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-emulate-media

Source

pub async fn pdf(&self, options: Option<PdfOptions>) -> Result<Vec<u8>>

Generates a PDF of the page and returns it as bytes.

Note: Generating a PDF is only supported in Chromium headless. PDF generation is not supported in Firefox or WebKit.

The PDF bytes are returned. If options.path is set, the PDF will also be saved to that file.

§Arguments
  • options - Optional PDF generation options
§Example
let pdf_bytes = page.pdf(None).await?;
assert!(!pdf_bytes.is_empty());
§Errors

Returns error if:

  • The browser is not Chromium (PDF only supported in Chromium)
  • Page has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-page#page-pdf

Source

pub async fn add_script_tag( &self, options: Option<AddScriptTagOptions>, ) -> Result<Arc<ElementHandle>>

Adds a <script> tag into the page with the desired URL or content.

§Arguments
  • options - Optional script tag options (content, url, or path). If None, returns an error because no source is specified.

At least one of content, url, or path must be provided.

§Example
// With inline JavaScript
page.add_script_tag(Some(
    AddScriptTagOptions::builder()
        .content("window.myVar = 42;")
        .build()
)).await?;

// With external URL
page.add_script_tag(Some(
    AddScriptTagOptions::builder()
        .url("https://example.com/script.js")
        .build()
)).await?;
§Errors

Returns error if:

  • options is None or no content/url/path is specified
  • Page has been closed
  • Script loading fails (e.g., invalid URL)

See: https://playwright.dev/docs/api/class-page#page-add-script-tag

Source

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

Returns the current viewport size of the page, or None if no viewport is set.

Returns None when the context was created with no_viewport: true. Otherwise returns the dimensions configured at context creation time or updated via set_viewport_size().

§Example
let context = browser.new_context_with_options(
    BrowserContextOptions::builder().viewport(Viewport { width: 1280, height: 720 }).build()
).await?;
let page = context.new_page().await?;
let size = page.viewport_size().expect("Viewport should be set");
assert_eq!(size.width, 1280);
assert_eq!(size.height, 720);

See: https://playwright.dev/docs/api/class-page#page-viewport-size

Source

pub fn accessibility(&self) -> Accessibility

Returns the Accessibility object for this page.

Use accessibility().snapshot() to capture the current state of the page’s accessibility tree.

See: https://playwright.dev/docs/api/class-page#page-accessibility

Source

pub fn coverage(&self) -> Coverage

Returns the Coverage object for this page (Chromium only).

Use coverage().start_js_coverage() / stop_js_coverage() and start_css_coverage() / stop_css_coverage() to collect code coverage data.

Coverage is only available in Chromium. Calling coverage methods on Firefox or WebKit will return an error from the Playwright server.

See: https://playwright.dev/docs/api/class-page#page-coverage

Trait Implementations§

Source§

impl Clone for Page

Source§

fn clone(&self) -> Page

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Page

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Page

§

impl !RefUnwindSafe for Page

§

impl Send for Page

§

impl Sync for Page

§

impl Unpin for Page

§

impl UnsafeUnpin 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

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