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
impl ContextRef
pub fn new(state: Arc<RwLock<BrowserState>>, name: String) -> Self
Sourcepub fn browser(&self) -> Option<&Browser>
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).
Sourcepub fn is_closed(&self) -> bool
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.
Sourcepub fn events(&self) -> &ContextEventEmitter
pub fn events(&self) -> &ContextEventEmitter
Context-scoped event emitter. Cheap to clone.
Sourcepub async fn pages(&self) -> Result<Vec<Arc<Page>>>
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.
Get all cookies in this context.
§Errors
Returns an error if the context does not exist or cookie retrieval fails.
Sourcepub async fn storage_state(
&self,
opts: Option<StorageStateOptions>,
) -> Result<StorageState>
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.
Add cookies to this context.
§Errors
Returns an error if the context does not exist or setting cookies fails.
Clear all cookies in this context.
§Errors
Returns an error if the context does not exist or clearing cookies fails.
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.
Sourcepub fn set_default_timeout(&self, ms: u64)
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.
Set the default navigation timeout for this context (ms). Mirrors
Playwright’s browserContext.setDefaultNavigationTimeout(timeout).
Sourcepub fn default_timeout(&self) -> u64
pub fn default_timeout(&self) -> u64
Current default action timeout (ms). 0 = no override.
Current default navigation timeout (ms). 0 = no override.
Sourcepub async fn grant_permissions(
&self,
permissions: &[String],
_origin: Option<&str>,
) -> Result<()>
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.
Sourcepub async fn clear_permissions(&self) -> Result<()>
pub async fn clear_permissions(&self) -> Result<()>
Sourcepub async fn close(&self) -> Result<()>
pub async fn close(&self) -> Result<()>
Close this context (remove from BrowserState).
§Errors
Returns an error if state lock acquisition fails.
Sourcepub fn state(&self) -> &Arc<RwLock<BrowserState>> ⓘ
pub fn state(&self) -> &Arc<RwLock<BrowserState>> ⓘ
Access the internal state (for MCP server integration).
Sourcepub async fn set_record_video(&self, opts: RecordVideoOptions) -> Result<()>
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).
Sourcepub fn on(&self, event_name: &str, callback: ContextEventCallback) -> ListenerId
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) => ...)).
Sourcepub fn once(
&self,
event_name: &str,
callback: ContextEventCallback,
) -> ListenerId
pub fn once( &self, event_name: &str, callback: ContextEventCallback, ) -> ListenerId
One-shot context-level listener — see Self::on.
Sourcepub fn off(&self, id: ListenerId)
pub fn off(&self, id: ListenerId)
Remove a previously registered context-level listener.
Sourcepub async fn wait_for_event(
&self,
event_name: &str,
timeout_ms: u64,
) -> Result<ContextEvent>
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.
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>
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.
Sourcepub async fn set_geolocation(
&self,
lat: f64,
lng: f64,
accuracy: f64,
) -> Result<()>
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.
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<()>
Playwright: browserContext.setExtraHTTPHeaders(headers).
§Errors
Returns an error if re-application fails on any page.
Sourcepub async fn set_offline(&self, offline: bool) -> Result<()>
pub async fn set_offline(&self, offline: bool) -> Result<()>
Playwright: browserContext.setOffline(offline).
§Errors
Returns an error if re-application fails on any page.
Sourcepub async fn set_http_credentials(
&self,
credentials: Option<HttpCredentials>,
) -> Result<()>
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).
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>
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.
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: 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.
Sourcepub async fn unroute(&self, matcher: &UrlMatcher) -> Result<()>
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.
Sourcepub async fn expose_binding(
&self,
name: &str,
callback: ExposedBinding,
) -> Result<Disposable>
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.
Sourcepub async fn expose_function(
&self,
name: &str,
callback: ExposedFn,
) -> Result<Disposable>
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.
Sourcepub async fn remove_exposed_binding(&self, name: &str) -> Result<()>
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
impl Clone for ContextRef
Source§fn clone(&self) -> ContextRef
fn clone(&self) -> ContextRef
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more