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
impl BrowserContext
Sourcepub fn browser_context_id(&self) -> Option<&str>
pub fn browser_context_id(&self) -> Option<&str>
The CDP browser-context id, or None for the default context.
Sourcepub async fn add_init_script(&self, script: &str) -> Result<()>
pub async fn add_init_script(&self, script: &str) -> Result<()>
Add a script evaluated before each document load (applied to new pages).
Sourcepub fn set_default_timeout(&self, timeout_ms: u64)
pub fn set_default_timeout(&self, timeout_ms: u64)
Set the default action timeout (ms) for pages in this context.
Sourcepub async fn set_extra_http_headers(&self, headers: Headers) -> Result<()>
pub async fn set_extra_http_headers(&self, headers: Headers) -> Result<()>
Set extra HTTP headers sent on every request (applied to new + existing pages).
Sourcepub fn request(&self) -> APIRequestContext
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.
Add cookies to this context.
Get cookies for this context.
Clear cookies for this context.
Sourcepub fn on_page<F, Fut>(&self, handler: F)
pub fn on_page<F, Fut>(&self, handler: F)
Register a handler called for each new page in this context.
Sourcepub async fn close(&self) -> Result<()>
pub async fn close(&self) -> Result<()>
Close the context and all its pages. Disposes an isolated context.
Sourcepub async fn grant_permissions(&self, permissions: &[&str]) -> Result<()>
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).
Sourcepub async fn clear_permissions(&self) -> Result<()>
pub async fn clear_permissions(&self) -> Result<()>
Reset all granted permissions.
Sourcepub async fn storage_state(&self) -> Result<StorageState>
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.
Sourcepub async fn set_storage_state(&self, state: &StorageState) -> Result<()>
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).
Sourcepub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
pub async fn route<F, Fut>(&self, pattern: &str, handler: F) -> Result<()>
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.
Sourcepub async fn unroute(&self, pattern: &str) -> Result<()>
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.
Sourcepub async fn unroute_all(&self) -> Result<()>
pub async fn unroute_all(&self) -> Result<()>
Remove all context-level routes and all page-level routes on each page.
Sourcepub async fn route_from_har(
&self,
har_path: impl AsRef<Path>,
options: Option<RouteFromHarOptions>,
) -> Result<()>
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
routewith the entry’s recorded URL as the pattern. On a match (HTTP method + URL), the handler serves the canned response viaRoute::fulfilland returns; non-matching requests fall through to the network (the handler callsRoute::fallback). - If
options.urlis set, only entries whose recorded URL matches that glob are installed; the rest are skipped (their requests go to network). - If
options.updateisSome(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 ofcrate::har.)
Sourcepub fn tracing(&self) -> Tracing
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.
Sourcepub async fn clock(&self) -> Result<Clock>
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.
Sourcepub async fn set_clock_install(
&self,
options: Option<ClockInstallOptions>,
) -> Result<()>
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().
Sourcepub fn on_close<F, Fut>(&self, handler: F)
pub fn on_close<F, Fut>(&self, handler: F)
Register a handler invoked when any page in the context closes.
Sourcepub fn on_console<F, Fut>(&self, handler: F)
pub fn on_console<F, Fut>(&self, handler: F)
Register a handler invoked for every console message on any page.
Sourcepub fn on_request<F, Fut>(&self, handler: F)
pub fn on_request<F, Fut>(&self, handler: F)
Register a handler invoked for every request sent by any page.
Sourcepub fn on_response<F, Fut>(&self, handler: F)
pub fn on_response<F, Fut>(&self, handler: F)
Register a handler invoked for every response received on any page.
Sourcepub async fn expect_page(&self, timeout: Option<Duration>) -> Result<Page>
pub async fn expect_page(&self, timeout: Option<Duration>) -> Result<Page>
Wait for the context to produce a new page (via new_page or a
window.open popup), returning it. Times out after timeout
(default 30s) with Error::Timeout.
A one-shot handler is registered with on_page; it
sends the first page over a tokio::sync::oneshot channel and then
drains its sender to None, so subsequent events are no-ops. The
handler is not removed from the handler list after it fires — it
simply has nothing to send — so it is idempotent and harmless to leave
in place (one extra closure in a Vec, no side effects).
Typical use races the wait against the action that opens the page:
let (page, _) = tokio::join!(
ctx.expect_page(Some(Duration::from_secs(5))),
ctx.new_page(),
);
page.unwrap().close().await.ok();Sourcepub async fn expect_request(
&self,
url_predicate: &str,
timeout: Option<Duration>,
) -> Result<Request>
pub async fn expect_request( &self, url_predicate: &str, timeout: Option<Duration>, ) -> Result<Request>
Wait for a request whose URL contains url_predicate on any page in
this context, returning it. Times out after timeout (default 30s)
with Error::Timeout.
The matcher is a plain substring test against the request URL
(str::contains), not a regex or glob — keep predicates literal.
A one-shot handler is registered with on_request;
it sends the first matching event over a tokio::sync::oneshot channel
and then drains its sender to None, so subsequent events are no-ops.
The handler is not removed from the handler list after it fires — it
simply has nothing to send — so it is idempotent and harmless to leave
in place (one extra closure in a Vec, no side effects).
Typical use races the wait against the navigation that triggers it:
let (req, _) = tokio::join!(
ctx.expect_request("127.0.0.1", Some(Duration::from_secs(5))),
page.goto(url, None),
);
req.unwrap().url().to_string();Sourcepub async fn expect_console(
&self,
text_predicate: &str,
timeout: Option<Duration>,
) -> Result<ConsoleMessage>
pub async fn expect_console( &self, text_predicate: &str, timeout: Option<Duration>, ) -> Result<ConsoleMessage>
Wait for a console message whose text contains text_predicate on any
page in this context, returning it. Times out after timeout
(default 30s) with Error::Timeout.
The matcher is a plain substring test against the message text
(str::contains), not a regex or glob — keep predicates literal.
A one-shot handler is registered with on_console;
it sends the first matching event over a tokio::sync::oneshot channel
and then drains its sender to None, so subsequent events are no-ops.
The handler is not removed from the handler list after it fires — it
simply has nothing to send — so it is idempotent and harmless to leave
in place (one extra closure in a Vec, no side effects).
Typical use races the wait against the action that logs the message:
let (msg, _) = tokio::join!(
ctx.expect_console("hello", Some(Duration::from_secs(5))),
page.evaluate::<()>("console.log('hello world')"),
);
msg.unwrap().text().to_string();Sourcepub fn on_requestfailed<F, Fut>(&self, handler: F)
pub fn on_requestfailed<F, Fut>(&self, handler: F)
Register a handler invoked when any request from any page fails.
Sourcepub fn on_download<F, Fut>(&self, handler: F)
pub fn on_download<F, Fut>(&self, handler: F)
Register a handler invoked for each file download on any page.
Sourcepub async fn set_geolocation(&self, geolocation: Option<Position>) -> Result<()>
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.
Sourcepub async fn set_offline(&self, offline: bool) -> Result<()>
pub async fn set_offline(&self, offline: bool) -> Result<()>
Toggle network-offline emulation for all current and future pages.
Set the default navigation timeout (ms) for all current and future pages.
Sourcepub async fn expose_function<F, Fut>(
&self,
name: &str,
callback: F,
) -> Result<()>
pub async fn expose_function<F, Fut>( &self, name: &str, callback: F, ) -> Result<()>
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.
Sourcepub async fn new_cdp_session(&self, page: &Page) -> Result<CdpSession>
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
impl Clone for BrowserContext
Source§fn clone(&self) -> BrowserContext
fn clone(&self) -> BrowserContext
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more