Skip to main content

ContextRef

Struct ContextRef 

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

Handle to a browser context. Created by Browser::new_context() / default_context(). Provides the Playwright-compatible context API by delegating to BrowserState.

Implementations§

Source§

impl ContextRef

Source

pub fn new(state: Arc<RwLock<BrowserState>>, name: String) -> Self

Source

pub fn browser(&self) -> Option<&Browser>

Parent browser handle, or None for a context not created from a crate::Browser. Mirrors Playwright’s browserContext.browser(): Browser | null (/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:290).

Source

pub fn is_closed(&self) -> bool

Whether this context has been closed. Mirrors Playwright’s browserContext.isClosed(): boolean (/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:298). false from handle creation until Self::close is called (or the underlying browser instance is shut down / disconnected), matching Playwright’s _closingStatus !== 'none'. Uses the shared BrowserState::context_closed flag so a close() on one handle is seen by every clone with the same composite key.

Source

pub fn events(&self) -> &ContextEventEmitter

Context-scoped event emitter. Cheap to clone.

Source

pub fn name(&self) -> &str

Context name.

Source

pub async fn new_page(&self) -> Result<Arc<Page>>

Create a new page in this context.

§Errors

Returns an error if page creation fails.

Source

pub async fn pages(&self) -> Result<Vec<Arc<Page>>>

Get all pages in this context as Page handles.

§Errors

Returns an error if the context does not exist.

Source

pub async fn cookies(&self) -> Result<Vec<CookieData>>

Get all cookies in this context.

§Errors

Returns an error if the context does not exist or cookie retrieval fails.

Source

pub async fn storage_state( &self, opts: Option<StorageStateOptions>, ) -> Result<StorageState>

Export the current storage state of this context — cookies plus a per-origin localStorage snapshot.

Playwright: storageState(options?: { path?: string, indexedDB?: boolean }) : Promise<{ cookies, origins }> (/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:460; server collection at .../server/browserContext.ts:609).

Cookies are read via the existing Self::cookies surface. For each live page in the context we evaluate Object.entries(localStorage) to snapshot its origin’s storage, grouping by location.origin and skipping origins with no entries (mirrors Playwright’s if (storage.localStorage .length) filter). opts.path, when set, writes the JSON-serialized state (pretty-printed) to disk; opts.indexed_db is accepted for signature parity but does not yet collect IndexedDB databases.

§Errors

Returns an error if the context does not exist, cookie retrieval fails, or (when path is set) the file cannot be written.

Source

pub async fn add_cookies(&self, cookies: Vec<CookieData>) -> Result<()>

Add cookies to this context.

§Errors

Returns an error if the context does not exist or setting cookies fails.

Source

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

Clear all cookies in this context.

§Errors

Returns an error if the context does not exist or clearing cookies fails.

Source

pub async fn clear_cookies_filtered( &self, options: &ClearCookieOptions, ) -> Result<()>

Clear cookies matching the given filters (matches Playwright’s context.clearCookies(options?)). If no filters are specified, all cookies are cleared.

§Errors

Returns an error if the context does not exist or clearing cookies fails.

Delete a specific cookie by name and optional domain (matches Playwright’s context.clearCookies({ name })).

§Errors

Returns an error if the context does not exist or deleting fails.

Source

pub fn set_default_timeout(&self, ms: u64)

Set the default timeout for actions in this context (ms). Mirrors Playwright’s browserContext.setDefaultTimeout(timeout). Takes &self (interior mutability via Arc<AtomicU64>) so it works behind a shared handle.

Source

pub fn set_default_navigation_timeout(&self, ms: u64)

Set the default navigation timeout for this context (ms). Mirrors Playwright’s browserContext.setDefaultNavigationTimeout(timeout).

Source

pub fn default_timeout(&self) -> u64

Current default action timeout (ms). 0 = no override.

Source

pub fn default_navigation_timeout(&self) -> u64

Current default navigation timeout (ms). 0 = no override.

Source

pub async fn grant_permissions( &self, permissions: &[String], _origin: Option<&str>, ) -> Result<()>

Grant permissions in this context. Stores the list on the options bag and re-applies to every open page — matches Playwright’s browserContext.grantPermissions semantics where the grant persists for future pages too.

The origin parameter is currently ignored at the backend level (CDP Browser.grantPermissions accepts an origin but we don’t thread it through the options bag yet — the bag-stored list grants for every origin).

§Errors

Returns an error if the re-application fails on any page.

Source

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

Clear all granted permissions.

§Errors

Returns an error if resetting permissions fails.

Source

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

Close this context (remove from BrowserState).

§Errors

Returns an error if state lock acquisition fails.

Source

pub fn state(&self) -> &Arc<RwLock<BrowserState>>

Access the internal state (for MCP server integration).

Source

pub async fn set_record_video(&self, opts: RecordVideoOptions) -> Result<()>

Enable recordVideo for pages opened in this context AFTER the call. Pages already open do not retroactively start recording — matches Playwright’s context-creation-time binding semantics (browser.newContext({ recordVideo: { dir, size? } })).

Transitional shim — prefer passing recordVideo to browser.newContext(options) directly.

§Errors

Returns an error if the state write fails. Does NOT re-apply to already-open pages (the recording runtime attaches at page open via start_video_recording).

Source

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

Register a context-level event listener. Supported events: 'weberror' (unhandled errors / rejections on any page in this context — mirrors Playwright’s browserContext.on('weberror', (webError: WebError) => ...)).

Source

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

One-shot context-level listener — see Self::on.

Source

pub fn off(&self, id: ListenerId)

Remove a previously registered context-level listener.

Source

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

Wait for the next context-level event matching event_name, with timeout_ms. Mirrors Playwright’s browserContext.waitForEvent(event, options?).

§Errors

Returns an error if the timeout elapses or the event channel is closed.

Source

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

Add an init script to all pages in this context (current + future). Mirrors Playwright’s browserContext.addInitScript(script, arg) from /tmp/playwright/packages/playwright-core/src/client/browserContext.ts:356. See crate::page::Page::add_init_script for argument semantics.

Returns a crate::disposable::Disposable whose dispose() removes the injected script from every page it was added to. Mirrors Playwright browserContext.addInitScript(...) which returns a DisposableObject (client/browserContext.ts:361).

§Errors

Returns an error if evaluation_script lowering fails, the context does not exist, or script injection fails on any page.

Source

pub async fn set_geolocation( &self, lat: f64, lng: f64, accuracy: f64, ) -> Result<()>

Playwright: browserContext.setGeolocation(geo) — mutates the options bag and re-applies to every open page.

§Errors

Returns an error if re-application fails on any page.

Source

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

Playwright: browserContext.setExtraHTTPHeaders(headers).

§Errors

Returns an error if re-application fails on any page.

Source

pub async fn set_offline(&self, offline: bool) -> Result<()>

Playwright: browserContext.setOffline(offline).

§Errors

Returns an error if re-application fails on any page.

Source

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

Playwright: browserContext.setHTTPCredentials(httpCredentials | null) (/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:355). Stores the credentials on the context options bag so pages opened later inherit them, and applies them to every already-open page. Passing None clears stored credentials — future 401 challenges then surface as the browser’s native auth dialog rather than being answered automatically.

The bag mutation alone cannot express “clear” (the per-field apply_context_options future is keyed on Some), so this drives the dedicated crate::Page::set_http_credentials backend path on each open page directly.

§Errors

Returns an error if any open page’s backend rejects the change (e.g. a backend that does not support auth-challenge interception).

Source

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

Register a route handler for all pages in this context.

Returns a crate::disposable::Disposable whose dispose() removes the handler from every page (equivalent to Self::unroute). Mirrors Playwright browserContext.route(...) which returns a DisposableStub (client/browserContext.ts:377).

§Errors

Returns an error if the context does not exist or route registration fails.

Source

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

Playwright: browserContext.routeFromHAR(har, options?). Replays a HAR file across every page in this context. Replay-only; recording (update: true) is unsupported.

§Errors

Returns an error if the HAR file cannot be read/parsed or routes fail to install.

Source

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

Remove route handlers matching the given matcher from all pages.

§Errors

Returns an error if the context does not exist or route removal fails.

Source

pub async fn expose_binding( &self, name: &str, callback: ExposedBinding, ) -> Result<Disposable>

Playwright: browserContext.exposeBinding(name, callback) from /tmp/playwright/packages/playwright-core/src/client/browserContext.ts:364.

Registers window[name] on every page in this context (current + future). The page-side call routes back into callback, which receives a crate::events::BindingSource as its first argument followed by the page-side call args. The callback’s return value (after awaiting any returned promise in the binding layers) is delivered to the page-side caller.

Returns a crate::disposable::Disposable whose dispose() removes the binding from the registry and from every page in the context.

§Errors

Returns an error if the context does not exist or injection fails on any page.

Source

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

Playwright: browserContext.exposeFunction(name, callback) from /tmp/playwright/packages/playwright-core/src/client/browserContext.ts:370.

exposeFunction is exposeBinding minus the source argument: the supplied source-less crate::events::ExposedFn is wrapped into an crate::events::ExposedBinding that discards the crate::events::BindingSource.

§Errors

Returns an error if the context does not exist or injection fails on any page.

Source

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

Remove a previously exposed binding/function from the registry and from every page in this context. Mirrors Playwright’s BrowserContext.removeExposedBinding (driven by Disposable).

§Errors

Returns an error if removal fails on any open page.

Trait Implementations§

Source§

impl Clone for ContextRef

Source§

fn clone(&self) -> ContextRef

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

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> 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

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

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

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
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,