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
impl Page
Sourcepub fn new(inner: AnyPage) -> Arc<Self> ⓘ
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.
Sourcepub fn with_context(inner: AnyPage, context: ContextRef) -> Arc<Self> ⓘ
pub fn with_context(inner: AnyPage, context: ContextRef) -> Arc<Self> ⓘ
Construct a Page bound to a BrowserContext. Same init
contract as Self::new.
Sourcepub async fn sync_frames(self: &Arc<Self>) -> Result<()>
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.
Sourcepub fn context(&self) -> Option<&ContextRef>
pub fn context(&self) -> Option<&ContextRef>
Get the BrowserContext this page belongs to (matches Playwright’s page.context()).
Sourcepub fn set_default_timeout(&self, ms: u64)
pub fn set_default_timeout(&self, ms: u64)
Set the default timeout for all operations (milliseconds).
Sourcepub fn default_timeout(&self) -> u64
pub fn default_timeout(&self) -> u64
Get the default timeout (milliseconds).
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).
Current effective navigation timeout (milliseconds). If
Self::set_default_navigation_timeout was not called, returns the
same value as Self::default_timeout.
Sourcepub async fn viewport_size(&self) -> Result<(i64, i64)>
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.
Sourcepub async fn goto(
self: &Arc<Self>,
url: &str,
opts: Option<GotoOptions>,
) -> Result<Option<Response>>
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.
Sourcepub async fn go_back(
&self,
opts: Option<GotoOptions>,
) -> Result<Option<Response>>
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.
Sourcepub async fn go_forward(
&self,
opts: Option<GotoOptions>,
) -> Result<Option<Response>>
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.
Sourcepub async fn reload(
&self,
opts: Option<GotoOptions>,
) -> Result<Option<Response>>
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.
Sourcepub fn url(&self) -> String
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.
Sourcepub async fn title(&self) -> Result<String>
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.
pub fn locator( self: &Arc<Self>, selector: &str, options: Option<FilterOptions>, ) -> Locator
Sourcepub fn add_locator_handler(
self: &Arc<Self>,
locator: &Locator,
handler: LocatorHandlerFn,
times: Option<u32>,
no_wait_after: bool,
) -> Result<()>
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.
Sourcepub fn remove_locator_handler(self: &Arc<Self>, locator: &Locator)
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).
pub fn get_by_role(self: &Arc<Self>, role: &str, opts: &RoleOptions) -> Locator
pub fn get_by_text( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator
pub fn get_by_label( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator
pub fn get_by_placeholder( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator
pub fn get_by_alt_text( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator
pub fn get_by_title( self: &Arc<Self>, text: &StringOrRegex, opts: &TextOptions, ) -> Locator
pub fn get_by_test_id(self: &Arc<Self>, test_id: &StringOrRegex) -> Locator
Sourcepub fn frame_locator(self: &Arc<Self>, selector: &str) -> FrameLocator
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).
Sourcepub async fn query_selector(
self: &Arc<Self>,
selector: &str,
) -> Result<Option<ElementHandle>>
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).
Sourcepub async fn query_selector_all(
self: &Arc<Self>,
selector: &str,
) -> Result<Vec<ElementHandle>>
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).
Sourcepub async fn evaluate(
self: &Arc<Self>,
fn_source: &str,
arg: SerializedArgument,
is_function: Option<bool>,
) -> Result<SerializedValue>
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.
Sourcepub async fn evaluate_handle(
self: &Arc<Self>,
fn_source: &str,
arg: SerializedArgument,
is_function: Option<bool>,
) -> Result<JSHandle>
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.
Sourcepub async fn click(
self: &Arc<Self>,
selector: &str,
opts: Option<ClickOptions>,
) -> Result<()>
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.
Sourcepub async fn dblclick(
self: &Arc<Self>,
selector: &str,
opts: Option<DblClickOptions>,
) -> Result<()>
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.
Sourcepub async fn fill(
self: &Arc<Self>,
selector: &str,
value: &str,
opts: Option<FillOptions>,
) -> Result<()>
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.
Sourcepub async fn type(
self: &Arc<Self>,
selector: &str,
text: &str,
opts: Option<TypeOptions>,
) -> Result<()>
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.
Sourcepub async fn press(
self: &Arc<Self>,
selector: &str,
key: &str,
opts: Option<PressOptions>,
) -> Result<()>
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.
Sourcepub async fn hover(
self: &Arc<Self>,
selector: &str,
opts: Option<HoverOptions>,
) -> Result<()>
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.
Sourcepub async fn select_option(
self: &Arc<Self>,
selector: &str,
values: Vec<SelectOptionValue>,
opts: Option<SelectOptionOptions>,
) -> Result<Vec<String>>
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.
Sourcepub async fn set_input_files(
self: &Arc<Self>,
selector: &str,
files: InputFiles,
opts: Option<SetInputFilesOptions>,
) -> Result<()>
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.
Sourcepub async fn check(
self: &Arc<Self>,
selector: &str,
opts: Option<CheckOptions>,
) -> Result<()>
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.
Sourcepub async fn uncheck(
self: &Arc<Self>,
selector: &str,
opts: Option<CheckOptions>,
) -> Result<()>
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.
Sourcepub async fn set_checked(
self: &Arc<Self>,
selector: &str,
checked: bool,
opts: Option<CheckOptions>,
) -> Result<()>
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.
Sourcepub async fn tap(
self: &Arc<Self>,
selector: &str,
opts: Option<TapOptions>,
) -> Result<()>
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.
Sourcepub async fn set_content(&self, html: &str) -> Result<()>
pub async fn set_content(&self, html: &str) -> Result<()>
Sourcepub async fn text_content(
self: &Arc<Self>,
selector: &str,
) -> Result<Option<String>>
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.
Sourcepub async fn inner_text(self: &Arc<Self>, selector: &str) -> Result<String>
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.
Sourcepub async fn inner_html(self: &Arc<Self>, selector: &str) -> Result<String>
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.
Sourcepub async fn get_attribute(
self: &Arc<Self>,
selector: &str,
name: &str,
) -> Result<Option<String>>
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.
Sourcepub async fn input_value(self: &Arc<Self>, selector: &str) -> Result<String>
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.
Sourcepub async fn is_visible(self: &Arc<Self>, selector: &str) -> Result<bool>
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.
Check if an element matching the selector is hidden.
§Errors
Returns an error if the element is not found.
Sourcepub async fn is_enabled(self: &Arc<Self>, selector: &str) -> Result<bool>
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.
Sourcepub async fn is_disabled(self: &Arc<Self>, selector: &str) -> Result<bool>
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.
Sourcepub async fn is_checked(self: &Arc<Self>, selector: &str) -> Result<bool>
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.
Sourcepub async fn wait_for_selector(
self: &Arc<Self>,
selector: &str,
opts: WaitOptions,
) -> Result<()>
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.
Sourcepub async fn wait_for_url(&self, matcher: UrlMatcher) -> Result<()>
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.
pub async fn wait_for_timeout(&self, ms: u64)
Sourcepub async fn wait_for_load_state(&self, state: Option<&str>) -> Result<()>
pub async fn wait_for_load_state(&self, state: Option<&str>) -> Result<()>
Wait for a specific load state. Supported states:
"load"(default) - wait fordocument.readyState === "complete""domcontentloaded"- wait fordocument.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.
Sourcepub async fn screenshot(&self, opts: ScreenshotOptions) -> Result<Vec<u8>>
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.
Sourcepub async fn screenshot_element(
self: &Arc<Self>,
selector: &str,
) -> Result<Vec<u8>>
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.
Sourcepub async fn pdf(&self, opts: PdfOptions) -> Result<Vec<u8>>
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.
Sourcepub async fn snapshot_for_ai(
&self,
opts: SnapshotOptions,
) -> Result<SnapshotForAI>
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 treeincremental: only changed/new nodes since last call with sametrackkeyref_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,NSAccessibilitydepth onWebKit.track: enables incremental tracking per key.
§Errors
Returns an error if the accessibility snapshot cannot be built.
Sourcepub async fn aria_snapshot(&self, opts: SnapshotOptions) -> Result<String>
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.
Sourcepub async fn set_viewport_size(&self, width: i64, height: i64) -> Result<()>
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.
Sourcepub async fn click_at_opts(
&self,
x: f64,
y: f64,
button: &str,
click_count: u32,
) -> Result<()>
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.
Sourcepub async fn move_mouse_smooth(
&self,
from_x: f64,
from_y: f64,
to_x: f64,
to_y: f64,
steps: u32,
) -> Result<()>
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.
Sourcepub async fn drag_and_drop(
self: &Arc<Self>,
source_selector: &str,
target_selector: &str,
options: Option<DragAndDropOptions>,
) -> Result<()>
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.
Sourcepub async fn find_element(&self, selector: &str) -> Result<AnyElement>
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.
Sourcepub async fn apply_context_options(
&self,
opts: &BrowserContextOptions,
) -> Result<()>
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.
Sourcepub async fn emulate_media(&self, opts: &EmulateMediaOptions) -> Result<()>
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.
Sourcepub async fn set_extra_http_headers(
&self,
headers: &FxHashMap<String, String>,
) -> Result<()>
pub async fn set_extra_http_headers( &self, headers: &FxHashMap<String, String>, ) -> Result<()>
Sourcepub async fn set_http_credentials(
&self,
creds: Option<HttpCredentials>,
) -> Result<()>
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.
Sourcepub async fn start_tracing(&self) -> Result<()>
pub async fn start_tracing(&self) -> Result<()>
Sourcepub async fn stop_tracing(&self) -> Result<()>
pub async fn stop_tracing(&self) -> Result<()>
Sourcepub async fn metrics(&self) -> Result<Vec<MetricData>>
pub async fn metrics(&self) -> Result<Vec<MetricData>>
Sourcepub async fn storage_state(&self) -> Result<Value>
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.
Sourcepub async fn set_storage_state(&self, state: &Value) -> Result<()>
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.
Sourcepub async fn dispatch_event(
self: &Arc<Self>,
selector: &str,
event_type: &str,
event_init: Option<Value>,
opts: Option<DispatchEventOptions>,
) -> Result<()>
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.
Sourcepub async fn is_editable(self: &Arc<Self>, selector: &str) -> Result<bool>
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.
Sourcepub async fn wait_for_function(
&self,
expression: &str,
timeout_ms: Option<u64>,
) -> Result<Value>
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.
Wait for the page to navigate to a URL matching the pattern.
§Errors
Returns an error if the wait times out.
Sourcepub async fn bring_to_front(&self) -> Result<()>
pub async fn bring_to_front(&self) -> Result<()>
Sourcepub fn main_frame(self: &Arc<Self>) -> Frame
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:
- The frame listener spawned in
seed_frame_cachepicks up aFrameNavigatedevent and writesmain_id. gotocallsensure_frame_cache_seededafter thePage.navigateresponse lands, which seeds via the backend’speek_main_frame_id()(no RTT).- Below: when this accessor is reached without (1) or (2) — for
example, an MCP tool that constructs a fresh
Pagewrapper over an already-navigated inner page — we synchronously seed frompeek_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.
Sourcepub fn frames(self: &Arc<Self>) -> Vec<Frame>
pub fn frames(self: &Arc<Self>) -> Vec<Frame>
All non-detached frames attached to the page, main-frame first. Sync — reads the cache.
Sourcepub fn frame(
self: &Arc<Self>,
selector: impl Into<FrameSelector>,
) -> Option<Frame>
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').
Sourcepub fn events(&self) -> &EventEmitter
pub fn events(&self) -> &EventEmitter
Get the event emitter for subscribing to page events.
Sourcepub fn on(&self, event_name: &str, callback: EventCallback) -> ListenerId
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);
}
}));Sourcepub fn once(&self, event_name: &str, callback: EventCallback) -> ListenerId
pub fn once(&self, event_name: &str, callback: EventCallback) -> ListenerId
Subscribe to a single event, then auto-remove the listener.
Sourcepub fn off(&self, id: ListenerId)
pub fn off(&self, id: ListenerId)
Remove an event listener by ID.
Sourcepub fn remove_all_listeners(&self)
pub fn remove_all_listeners(&self)
Remove all event listeners.
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.
Sourcepub fn expect_response(
&self,
url_pattern: &str,
timeout_ms: Option<u64>,
) -> impl Future<Output = Result<Response>> + '_
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.
Sourcepub fn expect_request(
&self,
url_pattern: &str,
timeout_ms: Option<u64>,
) -> impl Future<Output = Result<Request>> + '_
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.
Sourcepub async fn wait_for_event(
&self,
event_name: &str,
timeout_ms: Option<u64>,
) -> Result<PageEvent>
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.
Sourcepub async fn wait_for_request(
&self,
matcher: UrlMatcher,
timeout_ms: Option<u64>,
) -> Result<Request>
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.
Sourcepub async fn wait_for_response(
&self,
matcher: UrlMatcher,
timeout_ms: Option<u64>,
) -> Result<Response>
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.
Sourcepub async fn route(
&self,
matcher: UrlMatcher,
handler: RouteHandler,
times: Option<u32>,
) -> Result<Disposable>
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.
Sourcepub async fn route_from_har(
&self,
path: &Path,
options: RouteFromHarOptions,
) -> Result<()>
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.
Sourcepub async fn unroute(&self, matcher: &UrlMatcher) -> Result<()>
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.
Sourcepub async fn unroute_all(&self, behavior: Option<UnrouteBehavior>) -> Result<()>
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.
Sourcepub async fn pick_locator(self: &Arc<Self>) -> Result<Locator>
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.
Sourcepub async fn cancel_pick_locator(&self) -> Result<()>
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.
Sourcepub async fn hide_highlight(&self) -> Result<()>
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.
Sourcepub async fn expose_function(&self, name: &str, func: ExposedFn) -> Result<()>
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.
Sourcepub async fn remove_exposed_function(&self, name: &str) -> Result<()>
pub async fn remove_exposed_function(&self, name: &str) -> Result<()>
Sourcepub async fn add_script_tag(
&self,
url: Option<&str>,
content: Option<&str>,
script_type: Option<&str>,
) -> Result<()>
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.
Sourcepub async fn add_style_tag(
&self,
url: Option<&str>,
content: Option<&str>,
) -> Result<()>
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.
Sourcepub async fn wait_for_dialog(&self, timeout_ms: u64) -> Result<Dialog>
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.
Sourcepub async fn wait_for_file_chooser(
&self,
timeout_ms: u64,
) -> Result<FileChooser>
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.
Sourcepub async fn wait_for_download(&self, timeout_ms: u64) -> Result<Download>
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.
Sourcepub async fn add_init_script(
&self,
script: InitScriptSource,
arg: Option<Value>,
) -> Result<Disposable>
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.
Sourcepub async fn remove_init_script(&self, identifier: &str) -> Result<()>
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.
Sourcepub async fn close(&self, opts: Option<PageCloseOptions>) -> Result<()>
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.
Sourcepub fn close_reason(&self) -> Option<String>
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.
Sourcepub fn video(&self) -> Option<Arc<Video>>
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:4756
— video(): 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.
Sourcepub fn touchscreen(&self) -> Touchscreen<'_>
pub fn touchscreen(&self) -> Touchscreen<'_>
Get the Touchscreen interface for this page.
Sourcepub async fn start_screencast(
&self,
quality: u8,
max_width: u32,
max_height: u32,
) -> Result<(UnboundedReceiver<(Vec<u8>, f64)>, Sender<()>)>
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.