Skip to main content

Page

Struct Page 

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

High-level page API, mirrors Playwright’s Page interface. Always constructed behind Arc<Page> — locators, frames, and consumers hold Arc refs. No cloning of the Page struct itself.

Implementations§

Source§

impl Page

Source

pub fn new(inner: AnyPage) -> Arc<Self>

Construct a Page (no BrowserContext). Synchronous — only spawns the frame-cache listener; the eager Page.getFrameTree RTT was dropped (see PERF_AUDIT §M.4). The listener seeds the cache on the first frame event, and Self::ensure_frame_cache_seeded does an on-demand fetch only when a sync accessor fires before any navigation.

Source

pub fn with_context(inner: AnyPage, context: ContextRef) -> Arc<Self>

Construct a Page bound to a BrowserContext. Same init contract as Self::new.

Source

pub async fn sync_frames(self: &Arc<Self>) -> Result<()>

Refresh the frame cache from the backend without touching the listener. Useful when a caller wants to guarantee freshness before reading sync accessors (e.g. right after a navigation where event delivery is racing with the caller).

§Errors

Returns an error if the backend’s get_frame_tree() call fails.

Source

pub fn context(&self) -> Option<&ContextRef>

Get the BrowserContext this page belongs to (matches Playwright’s page.context()).

Source

pub fn inner(&self) -> &AnyPage

Access the underlying backend page (escape hatch).

Source

pub fn set_default_timeout(&self, ms: u64)

Set the default timeout for all operations (milliseconds).

Source

pub fn default_timeout(&self) -> u64

Get the default timeout (milliseconds).

Source

pub fn set_default_navigation_timeout(&self, ms: u64)

Set the default timeout for navigation-family operations (goto, reload, go_back, go_forward, wait_for_url). Mirrors Playwright’s page.setDefaultNavigationTimeout(timeout). Overrides the non-navigation default returned by Self::default_timeout for navigation calls only. Passing 0 means “no timeout” (Playwright parity).

Source

pub fn default_navigation_timeout(&self) -> u64

Current effective navigation timeout (milliseconds). If Self::set_default_navigation_timeout was not called, returns the same value as Self::default_timeout.

Source

pub async fn viewport_size(&self) -> Result<(i64, i64)>

Get the current viewport size by querying the browser.

§Errors

Returns an error if the JavaScript evaluation fails.

Source

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

Navigate to a URL with optional options (waitUntil, timeout).

Returns the main-document Response when the backend can observe it, or None for same-document navigations (no new request was issued) / backends that genuinely cannot expose the main-document response (stock WKWebView has no public API for this — see the §1.4 backend gap matrix in PLAYWRIGHT_COMPAT.md). Mirrors Playwright’s Promise<Response | null> contract on page.goto.

§Errors

Returns an error if the navigation fails or the wait condition times out.

Source

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

Navigate back in history. Returns the main-document Response on the same basis as goto (or None).

§Errors

Returns an error if the navigation fails or the wait condition times out.

Source

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

Navigate forward in history. Returns the main-document Response on the same basis as goto (or None).

§Errors

Returns an error if the navigation fails or the wait condition times out.

Source

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

Reload the current page. Returns the main-document Response on the same basis as goto (or None).

§Errors

Returns an error if the reload fails or the wait condition times out.

Source

pub fn url(&self) -> String

Get the current page URL — the main frame’s URL.

Playwright: page.url() is synchronous (url(): string). It reads the locally-tracked main-frame URL (kept current by navigation/lifecycle events), the same source Frame::url uses — no backend round-trip.

Source

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

Get the current page title.

§Errors

Returns an error if the title cannot be retrieved from the backend.

Source

pub fn locator( self: &Arc<Self>, selector: &str, options: Option<FilterOptions>, ) -> Locator

Source

pub fn add_locator_handler( self: &Arc<Self>, locator: &Locator, handler: LocatorHandlerFn, times: Option<u32>, no_wait_after: bool, ) -> Result<()>

Register a handler that runs when locator becomes visible during an actionability wait. Mirrors Playwright page.addLocatorHandler(locator, handler, options?: { times?, noWaitAfter? }) (/tmp/playwright/packages/playwright-core/src/client/page.ts:397).

The handler must belong to the main frame of this page. times: Some(0) registers nothing. When times runs out the handler auto-removes.

§Errors

Returns crate::error::FerriError if locator is not bound to this page’s main frame.

Source

pub fn remove_locator_handler(self: &Arc<Self>, locator: &Locator)

Remove all handlers registered for locator. Mirrors Playwright page.removeLocatorHandler(locator) (/tmp/playwright/packages/playwright-core/src/client/page.ts:423).

Source

pub fn get_by_role(self: &Arc<Self>, role: &str, opts: &RoleOptions) -> Locator

Source

pub fn get_by_text( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator

Source

pub fn get_by_label( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator

Source

pub fn get_by_placeholder( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator

Source

pub fn get_by_alt_text( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator

Source

pub fn get_by_title( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator

Source

pub fn get_by_test_id(self: &Arc<Self>, test_id: &StringOrRegex) -> Locator

Source

pub fn frame_locator(self: &Arc<Self>, selector: &str) -> FrameLocator

Create a FrameLocator for an <iframe> matching the selector.

Equivalent to Playwright’s page.frameLocator(selector).

Source

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

Resolve the selector once and return a lifecycle crate::element_handle::ElementHandle — or None when the selector matches no element. Mirrors Playwright’s page.querySelector(selector) / page.$(selector) (/tmp/playwright/packages/playwright-core/src/client/page.ts).

Unlike Self::locator (lazy, re-resolves on every action), the returned handle is pinned to the element resolved at call time. Subsequent DOM mutations that remove the element won’t invalidate the handle itself — actions against a detached element surface a backend-specific error — but the handle’s lifecycle is decoupled from the page’s frame cache. Callers release it via crate::element_handle::ElementHandle::dispose or let it drop when the page closes.

§Errors

Returns an error if the backend cannot execute the underlying query (protocol failure, target closed, etc.). A selector that does not match any element returns Ok(None).

Source

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

Playwright: page.querySelectorAll(selector): Promise<ElementHandle[]>. Returns one crate::element_handle::ElementHandle per match in document order. Each element is pinned individually — disposing one does not affect the others.

Implementation uses the selector engine’s query_all which tags every match with data-fd-sel='<i>'; we then evaluate a lookup by tag for each index and wrap the result. Tags are cleaned up on completion.

§Errors

Returns an error on selector parse failure, protocol error, or if a match cannot be resolved (e.g. the DOM changed mid-iteration).

Source

pub async fn evaluate( self: &Arc<Self>, fn_source: &str, arg: SerializedArgument, is_function: Option<bool>, ) -> Result<SerializedValue>

Playwright: page.evaluate(pageFunction, arg?): Promise<R> (/tmp/playwright/packages/playwright-core/src/client/page.ts:515). Delegates to the main frame, same as Playwright’s this._mainFrame.evaluate(...).

§Errors

Returns a crate::error::FerriError on page-side exception or protocol failure.

Source

pub async fn evaluate_handle( self: &Arc<Self>, fn_source: &str, arg: SerializedArgument, is_function: Option<bool>, ) -> Result<JSHandle>

Playwright: page.evaluateHandle(pageFunction, arg?): Promise<JSHandle>. Delegates to the main frame.

§Errors

See Self::evaluate.

Source

pub async fn click( self: &Arc<Self>, selector: &str, opts: Option<ClickOptions>, ) -> Result<()>

Click on an element matching the selector. Accepts Playwright’s full PageClickOptions bag (see crate::options::ClickOptions). Delegates to mainFrame().click(selector, opts).

§Errors

Returns an error if the element is not found or the click fails.

Source

pub async fn dblclick( self: &Arc<Self>, selector: &str, opts: Option<DblClickOptions>, ) -> Result<()>

Double-click an element matching the selector.

§Errors

Returns an error if the element is not found or the double-click fails.

Source

pub async fn fill( self: &Arc<Self>, selector: &str, value: &str, opts: Option<FillOptions>, ) -> Result<()>

Fill an input element matching the selector with a value.

§Errors

Returns an error if the element is not found or is not fillable.

Source

pub async fn type( self: &Arc<Self>, selector: &str, text: &str, opts: Option<TypeOptions>, ) -> Result<()>

Type text character-by-character into an element matching the selector.

§Errors

Returns an error if the element is not found or typing fails.

Source

pub async fn press( self: &Arc<Self>, selector: &str, key: &str, opts: Option<PressOptions>, ) -> Result<()>

Press a key on an element matching the selector.

§Errors

Returns an error if the element is not found or the key press fails.

Source

pub async fn hover( self: &Arc<Self>, selector: &str, opts: Option<HoverOptions>, ) -> Result<()>

Hover over an element matching the selector.

§Errors

Returns an error if the element is not found or the hover fails.

Source

pub async fn select_option( self: &Arc<Self>, selector: &str, values: Vec<SelectOptionValue>, opts: Option<SelectOptionOptions>, ) -> Result<Vec<String>>

Select an option in a <select> element matching the selector.

§Errors

Returns an error if the element is not found or the option cannot be selected.

Source

pub async fn set_input_files( self: &Arc<Self>, selector: &str, files: InputFiles, opts: Option<SetInputFilesOptions>, ) -> Result<()>

Set input files on a file input element matching the selector.

§Errors

Returns an error if the element is not found or file setting fails.

Source

pub async fn check( self: &Arc<Self>, selector: &str, opts: Option<CheckOptions>, ) -> Result<()>

Check a checkbox or radio button matching the selector.

§Errors

Returns an error if the element is not found or is not checkable.

Source

pub async fn uncheck( self: &Arc<Self>, selector: &str, opts: Option<CheckOptions>, ) -> Result<()>

Uncheck a checkbox matching the selector.

§Errors

Returns an error if the element is not found or is not uncheckable.

Source

pub async fn set_checked( self: &Arc<Self>, selector: &str, checked: bool, opts: Option<CheckOptions>, ) -> Result<()>

Set a checkbox or radio matching selector to checked. Mirrors Playwright’s page.setChecked(selector, checked, options?) (/tmp/playwright/packages/playwright-core/src/client/frame.ts:439).

§Errors

Returns an error if the element is not found or is not checkable.

Source

pub async fn tap( self: &Arc<Self>, selector: &str, opts: Option<TapOptions>, ) -> Result<()>

Tap (touch) the element matched by selector. Mirrors Playwright’s page.tap(selector, options?) (/tmp/playwright/packages/playwright-core/src/client/frame.ts:308). Distinct from Touchscreen::tap(x, y) which is the lower-level coordinate-based touch primitive.

§Errors

Returns an error if the element is not found or the tap fails.

Source

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

Get the full HTML content of the page.

§Errors

Returns an error if the content cannot be retrieved.

Source

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

Set the page’s HTML content.

§Errors

Returns an error if the content cannot be set.

Source

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

Extract the page content as markdown.

§Errors

Returns an error if the markdown extraction fails.

Source

pub async fn text_content( self: &Arc<Self>, selector: &str, ) -> Result<Option<String>>

Get the text content of an element matching the selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn inner_text(self: &Arc<Self>, selector: &str) -> Result<String>

Get the inner text of an element matching the selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn inner_html(self: &Arc<Self>, selector: &str) -> Result<String>

Get the inner HTML of an element matching the selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn get_attribute( self: &Arc<Self>, selector: &str, name: &str, ) -> Result<Option<String>>

Get an attribute value from an element matching the selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn input_value(self: &Arc<Self>, selector: &str) -> Result<String>

Get the input value of a form element matching the selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn is_visible(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if an element matching the selector is visible.

§Errors

Returns an error if the element is not found.

Source

pub async fn is_hidden(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if an element matching the selector is hidden.

§Errors

Returns an error if the element is not found.

Source

pub async fn is_enabled(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if an element matching the selector is enabled.

§Errors

Returns an error if the element is not found.

Source

pub async fn is_disabled(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if an element matching the selector is disabled.

§Errors

Returns an error if the element is not found.

Source

pub async fn is_checked(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if a checkbox or radio button matching the selector is checked.

§Errors

Returns an error if the element is not found.

Source

pub async fn wait_for_selector( self: &Arc<Self>, selector: &str, opts: WaitOptions, ) -> Result<()>

Wait for an element matching the selector to satisfy the wait condition.

§Errors

Returns an error if the wait times out.

Source

pub async fn wait_for_url(&self, matcher: UrlMatcher) -> Result<()>

Wait for the page URL to match the given matcher.

Accepts glob, regex, or predicate via crate::url_matcher::UrlMatcher. Mirrors Playwright’s page.waitForURL(url | RegExp | predicate) semantic.

§Errors

Returns an error if the wait times out.

Source

pub async fn wait_for_timeout(&self, ms: u64)

Source

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

Wait for a specific load state. Supported states:

  • "load" (default) - wait for document.readyState === "complete"
  • "domcontentloaded" - wait for document.readyState !== "loading"
  • "networkidle" - wait for no network activity for 500ms
§Errors

Returns an error if the wait times out before the load state is reached.

Source

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

Take a screenshot of the page. Mirrors Playwright’s page.screenshot(options?: PageScreenshotOptions) per /tmp/playwright/packages/playwright-core/types/types.d.ts:23280.

Lowers the Playwright-shaped ScreenshotOptions bag into the backend-level ScreenshotOpts wire struct. Handles Rust-side concerns (writing path to disk, applying timeout via a tokio::time::timeout race) that don’t belong in the per-backend dispatch path.

§Errors

Returns crate::error::FerriError::Timeout if the capture exceeds opts.timeout milliseconds; otherwise propagates any backend-specific failure.

Source

pub async fn screenshot_element( self: &Arc<Self>, selector: &str, ) -> Result<Vec<u8>>

Take a screenshot of a specific element matching the selector.

§Errors

Returns an error if the element is not found or screenshot capture fails.

Source

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

Generate a PDF of the current page (Chrome-family backends only).

Accepts the full Playwright PDFOptions surface via crate::options::PdfOptions. If opts.path is set, the rendered bytes are additionally written to that path (creating parent directories as needed) — mirroring Playwright’s page.pdf({ path }) behavior.

§Errors

Returns an error if PDF generation is not supported by the active backend (WebKit has no printToPDF analogue), if the paper format is unknown, if CDP rejects the parameters, or if writing to path fails.

Source

pub async fn snapshot_for_ai( &self, opts: SnapshotOptions, ) -> Result<SnapshotForAI>

LLM-optimized accessibility snapshot with page context header, optional depth limiting, and incremental change tracking.

Returns SnapshotForAI:

  • full: page header (URL, title, scroll, console errors) + accessibility tree
  • incremental: only changed/new nodes since last call with same track key
  • ref_map: element refs (e.g. “e5”) to backend DOM node IDs

Options:

  • depth: limits accessibility tree depth (-1 or None = unlimited). Uses native CDP depth param on Chrome, NSAccessibility depth on WebKit.
  • track: enables incremental tracking per key.
§Errors

Returns an error if the accessibility snapshot cannot be built.

Source

pub async fn aria_snapshot(&self, opts: SnapshotOptions) -> Result<String>

Playwright page.ariaSnapshot(options?): Promise<string> — the full accessibility-tree text (the full field of the structured snapshot).

§Errors

Returns an error if the accessibility snapshot cannot be built.

Source

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

Set the viewport size by width and height.

§Errors

Returns an error if the viewport emulation fails.

Source

pub async fn click_at(&self, x: f64, y: f64) -> Result<()>

Click at specific coordinates.

§Errors

Returns an error if the click dispatch fails.

Source

pub async fn click_at_opts( &self, x: f64, y: f64, button: &str, click_count: u32, ) -> Result<()>

Click at specific coordinates with button and click count options.

§Errors

Returns an error if the click dispatch fails.

Source

pub async fn move_mouse_smooth( &self, from_x: f64, from_y: f64, to_x: f64, to_y: f64, steps: u32, ) -> Result<()>

Move the mouse smoothly from one point to another over multiple steps.

§Errors

Returns an error if the mouse move dispatch fails.

Source

pub async fn drag_and_drop( self: &Arc<Self>, source_selector: &str, target_selector: &str, options: Option<DragAndDropOptions>, ) -> Result<()>

Drag an element matching source_selector onto an element matching target_selector. Mirrors Playwright’s page.dragAndDrop(source, target, options) per /tmp/playwright/packages/playwright-core/types/types.d.ts:2486.

The crate::options::DragAndDropOptions::strict field, when set, overrides the default strict-mode of the source/target locators — Some(true) errors on multi-match, Some(false) allows the first match, None keeps the default (strict = true). All other fields are forwarded to crate::locator::Locator::drag_to.

§Errors

Returns an error if either element cannot be found or the drag-and-drop operation fails.

Source

pub async fn find_element(&self, selector: &str) -> Result<AnyElement>

Find element by CSS selector (raw backend access).

§Errors

Returns an error if the element is not found.

Source

pub async fn apply_context_options( &self, opts: &BrowserContextOptions, ) -> Result<()>

Apply a full crate::options::BrowserContextOptions bag to this page. The single entry point for context-level state — delegates to the backend’s apply_context_options which fires every relevant protocol command in parallel and aggregates errors per field. Mirrors Playwright’s pattern of storing the bag on the context and having each FrameSession._initialize() read from it on page open (see /tmp/playwright/packages/playwright-core/src/server/chromium/crPage.ts:510-545).

Box::pinned because the inner future composes 16 per-field OptionFutures whose combined state machine is too large for an async-fn stack frame by clippy’s default.

§Errors

Returns an aggregated error when one or more fields fail to apply. The aggregated message lists each failing field by name.

Source

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

Emulate media features (color scheme, reduced motion, media type, forced-colors, contrast). Mirrors Playwright’s page.emulateMedia(options?) — each call is a partial update applied on top of the page’s persistent emulated-media state. A field set to Some(value) overrides; a field left None is unchanged.

§Errors

Returns an error if the backend rejects the media emulation.

Source

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

Enable or disable JavaScript execution.

§Errors

Set extra HTTP headers that will be sent with every request. Playwright public: page.setExtraHTTPHeaders(headers).

§Errors

Returns an error if the headers cannot be set.

Source

pub async fn set_http_credentials( &self, creds: Option<HttpCredentials>, ) -> Result<()>

Set (or clear) the HTTP credentials answered to auth challenges. Backs crate::ContextRef::set_http_credentials (Playwright browserContext.setHTTPCredentials(creds | null)).

§Errors

Returns an error if the backend cannot apply the credentials.

Source

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

Start performance tracing.

§Errors

Returns an error if tracing cannot be started.

Source

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

Stop performance tracing.

§Errors

Returns an error if tracing cannot be stopped.

Source

pub async fn metrics(&self) -> Result<Vec<MetricData>>

Get performance metrics from the page.

§Errors

Returns an error if metrics cannot be retrieved.

Source

pub async fn storage_state(&self) -> Result<Value>

Serialize the current page’s storage state (cookies + localStorage) to JSON.

Returns Playwright-compatible format:

{
  "cookies": [{ "name": "...", "value": "...", "domain": "...", ... }],
  "origins": [{ "origin": "https://...", "localStorage": [{ "name": "...", "value": "..." }] }]
}

Can be saved to a file and loaded later with set_storage_state or via test config storage_state: "auth.json".

§Errors

Returns an error if cookies or localStorage cannot be retrieved.

Source

pub async fn set_storage_state(&self, state: &Value) -> Result<()>

Restore a previously saved storage state (cookies + localStorage).

Accepts Playwright-compatible format with origins[].localStorage[] (name/value pairs).

§Errors

Returns an error if cookies or localStorage cannot be restored.

Source

pub async fn focus(self: &Arc<Self>, selector: &str) -> Result<()>

Focus an element by selector.

§Errors

Returns an error if the element is not found.

Source

pub async fn dispatch_event( self: &Arc<Self>, selector: &str, event_type: &str, event_init: Option<Value>, opts: Option<DispatchEventOptions>, ) -> Result<()>

Dispatch an event on an element by selector.

§Errors

Returns an error if the element is not found or the event dispatch fails.

Source

pub async fn is_editable(self: &Arc<Self>, selector: &str) -> Result<bool>

Check if an element is editable (not disabled, not readonly).

§Errors

Returns an error if the element is not found.

Source

pub async fn wait_for_function( &self, expression: &str, timeout_ms: Option<u64>, ) -> Result<Value>

Wait for a JS function/expression to return a truthy value.

§Errors

Returns an error if the wait times out.

Source

pub async fn wait_for_navigation(&self, timeout_ms: Option<u64>) -> Result<()>

Wait for the page to navigate to a URL matching the pattern.

§Errors

Returns an error if the wait times out.

Source

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

Bring this page to front (focus).

§Errors

Returns an error if the page cannot be focused.

Source

pub fn main_frame(self: &Arc<Self>) -> Frame

Main frame of this page. Mirrors Playwright’s page.mainFrame(): Frame (non-null).

The cache is seeded one of three ways:

  1. The frame listener spawned in seed_frame_cache picks up a FrameNavigated event and writes main_id.
  2. goto calls ensure_frame_cache_seeded after the Page.navigate response lands, which seeds via the backend’s peek_main_frame_id() (no RTT).
  3. Below: when this accessor is reached without (1) or (2) — for example, an MCP tool that constructs a fresh Page wrapper over an already-navigated inner page — we synchronously seed from peek_main_frame_id() so the user-visible API never panics on a live, navigated page.
§Panics

Panics only when the cache is empty AND the backend has never observed a top-level frame (i.e. no navigation has ever occurred on this inner page). This is genuine API misuse — Playwright itself can’t return a Frame either before the first navigation.

Source

pub fn frames(self: &Arc<Self>) -> Vec<Frame>

All non-detached frames attached to the page, main-frame first. Sync — reads the cache.

Source

pub fn frame( self: &Arc<Self>, selector: impl Into<FrameSelector>, ) -> Option<Frame>

Locate a frame by name or URL. Sync — reads the cache. Playwright: page.frame(string | { name?, url? }) — see /tmp/playwright/packages/playwright-core/types/types.d.ts:2755.

§Panics

Panics if selector specifies neither name nor url — matches Playwright’s assert(name || url, 'Either name or url matcher should be specified').

Source

pub fn events(&self) -> &EventEmitter

Get the event emitter for subscribing to page events.

Source

pub fn on(&self, event_name: &str, callback: EventCallback) -> ListenerId

Subscribe to page events. Calls the callback for each matching event. Returns a ListenerId for later removal with off().

let id = page.on("response", Arc::new(|event| {
    if let PageEvent::Response(r) = event {
        println!("Response: {} {}", r.status, r.url);
    }
}));
Source

pub fn once(&self, event_name: &str, callback: EventCallback) -> ListenerId

Subscribe to a single event, then auto-remove the listener.

Source

pub fn off(&self, id: ListenerId)

Remove an event listener by ID.

Source

pub fn remove_all_listeners(&self)

Remove all event listeners.

Source

pub fn expect_navigation( &self, timeout_ms: Option<u64>, ) -> impl Future<Output = Result<()>> + '_

Start listening for a navigation event. Call BEFORE the action that triggers navigation. Returns a future that resolves when navigation completes.

let nav = page.expect_navigation(None);
page.click("#link", None).await?;
nav.await?; // resolves when navigation completes
§Errors

Returns an error if the navigation event does not occur within the timeout.

Source

pub fn expect_response( &self, url_pattern: &str, timeout_ms: Option<u64>, ) -> impl Future<Output = Result<Response>> + '_

Start listening for a response matching URL pattern. Call BEFORE the action.

§Errors

Returns an error if no matching response is received within the timeout.

Source

pub fn expect_request( &self, url_pattern: &str, timeout_ms: Option<u64>, ) -> impl Future<Output = Result<Request>> + '_

Start listening for a request matching URL pattern. Call BEFORE the action.

§Errors

Returns an error if no matching request is received within the timeout.

Source

pub async fn wait_for_event( &self, event_name: &str, timeout_ms: Option<u64>, ) -> Result<PageEvent>

Wait for a specific event (by name) with timeout.

§Errors

Returns an error if the event does not occur within the timeout.

Source

pub async fn wait_for_request( &self, matcher: UrlMatcher, timeout_ms: Option<u64>, ) -> Result<Request>

Wait for a network request matching a URL pattern.

§Errors

Returns an error if no matching request occurs within the timeout.

Source

pub async fn wait_for_response( &self, matcher: UrlMatcher, timeout_ms: Option<u64>, ) -> Result<Response>

Wait for a network response matching a URL pattern.

§Errors

Returns an error if no matching response occurs within the timeout.

Source

pub async fn route( &self, matcher: UrlMatcher, handler: RouteHandler, times: Option<u32>, ) -> Result<Disposable>

Intercept network requests matching a crate::url_matcher::UrlMatcher. The handler receives a crate::route::Route and must call exactly one of fulfill(), continue_route(), or abort().

use ferridriver::route::{Route, FulfillResponse};
use ferridriver::url_matcher::UrlMatcher;
use std::sync::Arc;

// Mock an API endpoint
page.route(UrlMatcher::glob("**/api/data")?, Arc::new(|route: Route| {
    route.fulfill(FulfillResponse {
        status: 200,
        body: b"{\"mocked\": true}".to_vec(),
        content_type: Some("application/json".into()),
        ..Default::default()
    });
}), None).await?;

// Block image loading
page.route(UrlMatcher::glob("**/*.{png,jpg,gif}")?, Arc::new(|route: Route| {
    route.abort("blockedbyclient");
}), None).await?;

Returns a crate::disposable::Disposable whose dispose() reverses the registration (equivalent to calling Page::unroute with the same matcher). Mirrors Playwright page.route(...) which returns a DisposableStub (client/page.ts:535).

§Errors

Returns an error if the route interception cannot be set up.

Source

pub async fn route_from_har( &self, path: &Path, options: RouteFromHarOptions, ) -> Result<()>

Playwright: page.routeFromHAR(har, options?). Replay recorded responses from a HAR file for matching requests. Replay-only; HAR recording (update: true) is not supported.

§Errors

Returns an error if the HAR file cannot be read/parsed or the route cannot be installed.

Source

pub async fn unroute(&self, matcher: &UrlMatcher) -> Result<()>

Remove all route handlers whose matcher is crate::url_matcher::UrlMatcher::equivalent to the given matcher.

§Errors

Returns an error if the route handlers cannot be removed.

Source

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

Remove all route handlers registered via Page::route.

Mirrors Playwright’s page.unrouteAll({ behavior?: 'wait' | 'ignoreErrors' | 'default' }). The behavior selects how to treat handlers still running when the call is made; ferridriver route handlers run synchronously inside the interception loop, so once the routes are cleared no detached handler task can still be in flight — every variant performs the same teardown (clear routes, disable interception).

§Errors

Returns an error if the underlying interception teardown fails.

Source

pub async fn pick_locator(self: &Arc<Self>) -> Result<Locator>

Open the interactive locator picker: highlight elements under the cursor and resolve with a Locator for the element the user clicks.

Mirrors Playwright’s page.pickLocator(): Promise<Locator>. The picker generates a selector for the clicked element using the same engine that backs codegen/recording, then returns page.locator(selector).

Cancel an in-progress pick with Page::cancel_pick_locator.

§Errors

Returns an error if the picker scaffolding cannot be injected, the page closes before a selection is made, or the returned selector is empty.

Source

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

Cancel an in-progress Page::pick_locator and hide its highlight.

Mirrors Playwright’s page.cancelPickLocator(). Any pending pick_locator future resolves with a page closed-style error once the page-side picker is torn down (the exposed callback is removed, so the oneshot sender drops).

§Errors

Returns an error if the page-side teardown evaluation fails.

Source

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

Hide any highlight overlay currently shown by the picker or by highlight-style helpers.

Mirrors Playwright’s page.hideHighlight().

§Errors

Returns an error if the page-side teardown evaluation fails.

Source

pub async fn expose_function(&self, name: &str, func: ExposedFn) -> Result<()>

Expose a Rust function to the page as window.<name>(...). The page can call it as an async function and receive the return value. The exposed function persists across navigations.

use std::sync::Arc;

page.expose_function("compute", Arc::new(|args| {
    Box::pin(async move {
        let x = args.first().and_then(|v| v.as_f64()).unwrap_or(0.0);
        serde_json::json!(x * 2.0)
    })
})).await?;

// In the page:
// const result = await window.compute(21); // returns 42
§Errors

Returns an error if the function cannot be exposed to the page.

Source

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

Remove a previously exposed function.

§Errors

Returns an error if the function cannot be removed.

Source

pub async fn add_script_tag( &self, url: Option<&str>, content: Option<&str>, script_type: Option<&str>, ) -> Result<()>

Add a <script> tag to the page. Provide either url (external) or content (inline). For URL scripts, waits for the script to load before returning.

§Errors

Returns an error if neither url nor content is provided, or if injection fails.

Source

pub async fn add_style_tag( &self, url: Option<&str>, content: Option<&str>, ) -> Result<()>

Add a <style> tag or <link> stylesheet to the page. Provide either url (external CSS) or content (inline CSS). For URL stylesheets, waits for the stylesheet to load before returning.

§Errors

Returns an error if neither url nor content is provided, or if injection fails.

Source

pub async fn wait_for_dialog(&self, timeout_ms: u64) -> Result<Dialog>

Wait for the next dialog of any type, with a timeout. Returns the live crate::dialog::Dialog handle; the caller must then call accept(...) or dismiss() exactly once. Mirrors Playwright’s page.waitForEvent('dialog', { timeout }).

Registers a one-shot handler with the page’s crate::dialog::DialogManager that claims the first dialog and delivers it here. The handler is removed automatically on resolve or timeout.

§Errors

Returns crate::error::FerriError::Timeout if no dialog opens within timeout_ms. Returns crate::error::FerriError::TargetClosed if the page closes before a dialog arrives.

Source

pub async fn wait_for_file_chooser( &self, timeout_ms: u64, ) -> Result<FileChooser>

Wait for the next file chooser to open, with a timeout. Returns the live crate::file_chooser::FileChooser handle; the caller may then call set_files(...) (or drop the handle to cancel the upload — the native picker was already suppressed by CDP’s Page.setInterceptFileChooserDialog). Mirrors Playwright’s page.waitForEvent('filechooser', { timeout }).

Registers a one-shot handler with the page’s crate::file_chooser::FileChooserManager that claims the first chooser and delivers it here. The handler is removed automatically on resolve or timeout.

§Errors

Returns crate::error::FerriError::Timeout if no file chooser opens within timeout_ms. Returns crate::error::FerriError::TargetClosed if the page closes before a chooser arrives.

Source

pub async fn wait_for_download(&self, timeout_ms: u64) -> Result<Download>

Wait for the next download, with a timeout. Returns the live crate::download::Download handle; the caller may then call save_as(path) / path() / failure() / cancel() / delete(). Mirrors Playwright’s page.waitForEvent('download', { timeout }).

Registers a one-shot handler with the page’s crate::download::DownloadManager; the handler is removed automatically on resolve or timeout.

§Errors

Returns crate::error::FerriError::Timeout if no download begins within timeout_ms. Returns crate::error::FerriError::TargetClosed if the page closes before a download begins.

Source

pub async fn add_init_script( &self, script: InitScriptSource, arg: Option<Value>, ) -> Result<Disposable>

Register a script to run before any page JS on every navigation. Mirrors Playwright’s page.addInitScript(script, arg) from /tmp/playwright/packages/playwright-core/src/client/page.ts:520.

Accepts the full Playwright argument shape: a JS function body (pre-serialised via fn.toString() at the binding layer), a verbatim source string, a { path }, or a { content }. The optional arg is JSON-stringified and composed into a (body)(arg) wrapper for the Function variant; passing arg alongside any non-function variant is a Playwright-parity error (see crate::options::evaluation_script).

Returns a crate::disposable::Disposable whose dispose() removes the injected script (equivalent to Page::remove_init_script with the generated identifier). Mirrors Playwright page.addInitScript(...) which returns a Disposable (client/page.ts:532).

§Errors

Returns an error if evaluation_script lowering fails (bad path, bad arg combination, JSON serialisation) or the backend injection fails.

Source

pub async fn remove_init_script(&self, identifier: &str) -> Result<()>

Remove a previously injected init script by identifier.

§Errors

Returns an error if the init script cannot be removed.

Source

pub async fn close(&self, opts: Option<PageCloseOptions>) -> Result<()>

Close this page. After closing, most operations will fail.

Accepts Option<crate::options::PageCloseOptions> — mirrors Playwright’s page.close({ runBeforeUnload, reason } = {}). runBeforeUnload=true fires the page’s beforeunload handlers before unloading. reason, if set, is stored on the Page and surfaces through any TargetClosed error returned to in-flight operations on this page. Pass None for the common no-options case.

§Errors

Returns an error if the page cannot be closed.

Source

pub fn close_reason(&self) -> Option<String>

Reason passed to the most recent Page::close call, if any. Used by error-surfacing code to attach a human-readable explanation to TargetClosed errors emitted after close.

Source

pub fn is_closed(&self) -> bool

Check if this page has been closed.

Source

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

Video handle for this page when recording is enabled on the owning context. Playwright: /tmp/playwright/packages/playwright-core/types/types.d.ts:4756video(): null | Video. Returns None for pages in contexts that were not created with recordVideo. Recording is driven by start_screencast, which every backend (CDP, BiDi, Playwright WebKit) implements, so any context created with recordVideo yields a handle.

Source

pub fn keyboard(&self) -> Keyboard<'_>

Get the Keyboard interface for this page.

Source

pub fn mouse(&self) -> Mouse<'_>

Get the Mouse interface for this page.

Source

pub fn touchscreen(&self) -> Touchscreen<'_>

Get the Touchscreen interface for this page.

Source

pub async fn start_screencast( &self, quality: u8, max_width: u32, max_height: u32, ) -> Result<(UnboundedReceiver<(Vec<u8>, f64)>, Sender<()>)>

Start CDP screencast. Returns a channel of (jpeg_bytes, timestamp_secs) pairs. Timestamp is Chrome’s metadata.timestamp from the screencastFrame event.

§Errors

Returns an error if screencast cannot be started on the backend.

Source

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

Stop CDP screencast.

§Errors

Returns an error if screencast cannot be stopped on the backend.

Trait Implementations§

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

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,