Skip to main content

BrowserContext

Struct BrowserContext 

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

A browser context. The default context has browser_context_id == None; isolated contexts are created via Browser::new_context.

Implementations§

Source§

impl BrowserContext

Source

pub fn browser_context_id(&self) -> Option<&str>

The CDP browser-context id, or None for the default context.

Source

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

Open a new page in this context.

Source

pub async fn add_init_script(&self, script: &str) -> Result<()>

Add a script evaluated before each document load (applied to new pages).

Source

pub fn set_default_timeout(&self, timeout_ms: u64)

Set the default action timeout (ms) for pages in this context.

Source

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

Set extra HTTP headers sent on every request (applied to new + existing pages).

Source

pub fn request(&self) -> APIRequestContext

Return a standalone HTTP client (APIRequestContext) tied to this context. Its default headers are seeded (best-effort) from the context’s extra_http_headers. The client is otherwise independent of the browser — it makes direct HTTP requests.

Source

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

All pages opened in this context.

Source

pub fn browser(&self) -> Browser

The owning browser.

Source

pub async fn add_cookies(&self, cookies: &[Cookie]) -> Result<()>

Add cookies to this context.

Source

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

Get cookies for this context.

Source

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

Clear cookies for this context.

Source

pub fn on_page<F, Fut>(&self, handler: F)
where F: Fn(Page) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler called for each new page in this context.

Source

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

Close the context and all its pages. Disposes an isolated context.

Source

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

Grant browser permissions (e.g. ["geolocation", "clipboard-read"]). Applies browser-wide (CDP Browser.grantPermissions is not context-scoped).

Source

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

Reset all granted permissions.

Source

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

Snapshot storage state: cookies plus per-origin localStorage.

For each page in the context, localStorage is captured grouped by location.origin. Pages whose origin is "null" (e.g. about:blank, data: URLs) are skipped.

Source

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

Restore storage state previously captured by Self::storage_state: cookies are added via the Storage domain, and each origin’s localStorage is set by evaluating localStorage.setItem on a page at that origin (an existing page if one matches, otherwise a freshly created one).

Source

pub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
where F: Fn(Route) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a route that intercepts matching requests on ALL pages in this context — including pages created after this call. The handler must continue/fulfill/abort the Route.

A context route is applied to each page by registering the equivalent page-level route on it. Context-level and page-level routes are otherwise independent.

Source

pub async fn unroute(&self, pattern: &str) -> Result<()>

Remove the first context-level route registered with exactly pattern and remove the matching page-level route on each page.

Source

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

Remove all context-level routes and all page-level routes on each page.

Source

pub async fn route_from_har( &self, har_path: impl AsRef<Path>, options: Option<RouteFromHarOptions>, ) -> Result<()>

Replay a HAR file: register one route per HAR entry that serves the recorded response for matching requests on every page (existing and future). Mirrors Playwright’s context.route_from_har.

Behavior:

  • Each HAR entry becomes a context-level route with the entry’s recorded URL as the pattern. On a match (HTTP method + URL), the handler serves the canned response via Route::fulfill and returns; non-matching requests fall through to the network (the handler calls Route::fallback).
  • If options.url is set, only entries whose recorded URL matches that glob are installed; the rest are skipped (their requests go to network).
  • If options.update is Some(true), the file is not replayed: nothing is fulfilled and all requests fall through to the network. (Full HAR recording is deferred — see the module docs of crate::har.)
Source

pub fn tracing(&self) -> Tracing

A performance tracing handle bound to the browser-level CDP session.

Mirrors Playwright’s context.tracing(). The Tracing domain is browser-level; tracing() returns clones of a single shared handle so [Tracing::start] and [Tracing::stop] operate on the same state.

Source

pub async fn clock(&self) -> Result<Clock>

Return a fake-timer handle for this context, bound to the first existing page’s session. If no page exists yet, returns a Clock bound to a brand-new utility page’s session (created lazily); the install options are not applied here — call Clock::install explicitly or use Self::set_clock_install to seed future pages.

Because fake timers are page-scoped, calls on the returned Clock only affect the page it is bound to (the first page). To install fake timers across all future pages, use Self::set_clock_install.

Source

pub async fn set_clock_install( &self, options: Option<ClockInstallOptions>, ) -> Result<()>

Register fake-timer install options to be applied to every page created after this call (and the first existing page immediately). This is the forward-application mechanism for context-level fake timers.

Returns the result of installing on the first existing page (if any); future pages pick up the config in new_page().

Source

pub fn on_close<F, Fut>(&self, handler: F)
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked when any page in the context closes.

Source

pub fn on_console<F, Fut>(&self, handler: F)
where F: Fn(ConsoleMessage) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked for every console message on any page.

Source

pub fn on_request<F, Fut>(&self, handler: F)
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked for every request sent by any page.

Source

pub fn on_response<F, Fut>(&self, handler: F)
where F: Fn(Response) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked for every response received on any page.

Source

pub fn on_requestfailed<F, Fut>(&self, handler: F)
where F: Fn(Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked when any request from any page fails.

Source

pub fn on_download<F, Fut>(&self, handler: F)
where F: Fn(Download) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a handler invoked for each file download on any page.

Source

pub async fn set_geolocation(&self, geolocation: Option<Position>) -> Result<()>

Override geolocation for all current and future pages, or clear it with None.

Mapping note: Position is the crate’s 2D point type ({ x, y }). For geolocation its components are interpreted as { x => latitude, y => longitude } when forwarded to Page::set_geolocation.

Source

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

Toggle network-offline emulation for all current and future pages.

Source

pub fn set_default_navigation_timeout(&self, ms: u64)

Set the default navigation timeout (ms) for all current and future pages.

Source

pub async fn expose_function<F, Fut>( &self, name: &str, callback: F, ) -> Result<()>
where F: Fn(Vec<Value>) -> Fut + Send + Sync + 'static, Fut: Future<Output = Value> + Send + 'static,

Expose a Rust function to every page in the context as window[name], including pages created after this call.

The callback signature matches Page::expose_function: it receives the JS arguments as a Vec<serde_json::Value> and returns a serde_json::Value.

Source

pub async fn new_cdp_session(&self, page: &Page) -> Result<CdpSession>

Attach a fresh CDP session to the given page’s target and return it.

Sends Target.attachToTarget with { targetId, flatten: true } over the browser-level session, then wraps the returned sessionId in a target-scoped CdpSession bound to the same connection.

Trait Implementations§

Source§

impl Clone for BrowserContext

Source§

fn clone(&self) -> BrowserContext

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<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> 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: Sized + 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: Sized + 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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