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 (implemented in Phase 3) to navigate to URLs.

§Example

use playwright_core::protocol::{Playwright, ScreenshotOptions, ScreenshotType};
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#"
        <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 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!')").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 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 fn url(&self) -> String

Returns the current URL of the page.

This returns the last committed URL. 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 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 async fn title(&self) -> Result<String>

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 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 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 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(&self, expression: &str) -> Result<()>

Evaluates JavaScript in the page context.

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

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

Trait Implementations§

Source§

impl ChannelOwner for Page

Source§

fn guid(&self) -> &str

Returns the unique GUID for this object. Read more
Source§

fn type_name(&self) -> &str

Returns the protocol type name (e.g., “Browser”, “Page”).
Source§

fn parent(&self) -> Option<Arc<dyn ChannelOwner>>

Returns the parent object, if any. Read more
Source§

fn connection(&self) -> Arc<dyn ConnectionLike>

Returns the connection this object belongs to.
Source§

fn initializer(&self) -> &Value

Returns the raw initializer JSON from the server. Read more
Source§

fn channel(&self) -> &Channel

Returns the channel for RPC communication.
Source§

fn dispose(&self, reason: DisposeReason)

Disposes this object and all its children. Read more
Source§

fn adopt(&self, child: Arc<dyn ChannelOwner>)

Adopts a child object (moves from old parent to this parent). Read more
Source§

fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>)

Adds a child object to this parent’s registry. Read more
Source§

fn remove_child(&self, guid: &str)

Removes a child object from this parent’s registry. Read more
Source§

fn on_event(&self, method: &str, params: Value)

Handles a protocol event sent to this object. Read more
Source§

fn was_collected(&self) -> bool

Returns true if this object was garbage collected.
Source§

fn as_any(&self) -> &dyn Any

Enables downcasting to concrete types. Read more
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 !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> 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<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