Skip to main content

BrowserContext

Struct BrowserContext 

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

Implementations§

Source§

impl BrowserContext

Source

pub fn new( parent: Arc<dyn ChannelOwner>, type_name: String, guid: Arc<str>, initializer: Value, ) -> Result<Self>

Creates a new BrowserContext from protocol initialization

This is called by the object factory when the server sends a __create__ message for a BrowserContext object.

§Arguments
  • parent - The parent Browser object
  • type_name - The protocol type name (“BrowserContext”)
  • guid - The unique identifier for this context
  • initializer - The initialization data from the server
§Errors

Returns error if initializer is malformed

Source

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

Adds a script which would be evaluated in one of the following scenarios:

  • Whenever a page is created in the browser context or is navigated.
  • Whenever a child frame is attached or navigated in any page in the browser context.

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

§Arguments
  • script - Script to be evaluated in all pages in the browser context.
§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script

Source

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

Creates a new page in this browser context.

Pages are isolated tabs/windows within a context. Each page starts at “about:blank” and can be navigated independently.

§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-new-page

Source

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

Returns all open pages in the context.

This method provides a snapshot of all currently active pages that belong to this browser context instance. Pages created via new_page() and popup pages opened through user interactions are included.

In persistent contexts launched with --app=url, this will include the initial page created automatically by Playwright.

§Errors

This method does not return errors. It provides a snapshot of pages at the time of invocation.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-pages

Source

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

Returns the browser instance that owns this context.

Returns None only for contexts created outside of normal browser (e.g., Android or Electron contexts). For both regular contexts and persistent contexts, this returns the owning Browser instance.

§Errors

This method does not return errors.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-browser

Source

pub async fn request(&self) -> Result<APIRequestContext>

Returns the APIRequestContext associated with this context.

The APIRequestContext is created automatically by the server for each BrowserContext. It enables performing HTTP requests and is used internally by Route::fetch().

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-request

Source

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

Creates a new Chrome DevTools Protocol session for the given page.

CDPSession provides low-level access to the Chrome DevTools Protocol. This method is only available in Chromium-based browsers.

§Arguments
  • page - The page to create a CDP session for
§Errors

Returns error if:

  • The browser is not Chromium-based
  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-new-cdp-session

Source

pub async fn tracing(&self) -> Result<Tracing>

Returns the Tracing object for this browser context.

The Tracing object is created automatically by the Playwright server for each BrowserContext. Use it to start and stop trace recording.

§Errors

Returns error if no Tracing object is available for this context (rare, should not happen in normal usage).

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-tracing

Source

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

Closes the browser context and all its pages.

This is a graceful operation that sends a close command to the context and waits for it to shut down properly.

§Errors

Returns error if:

  • Context has already been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-close

Source

pub async fn set_default_timeout(&self, timeout: f64)

Sets the default timeout for all operations in this browser context.

This applies to all pages already open in this context as well as pages created subsequently. Pass 0 to disable timeouts.

§Arguments
  • timeout - Timeout in milliseconds

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout

Source

pub async fn set_default_navigation_timeout(&self, timeout: f64)

Sets the default timeout for navigation operations in this browser context.

This applies to all pages already open in this context as well as pages created subsequently. Pass 0 to disable timeouts.

§Arguments
  • timeout - Timeout in milliseconds

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-navigation-timeout

Source

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

Pauses the browser context.

This pauses the execution of all pages in the context.

Source

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

Returns storage state for this browser context.

Contains current cookies and local storage snapshots.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state

Source

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

Adds cookies into this browser context.

All pages within this context will have these cookies installed. Cookies can be granularly specified with name, value, url, domain, path, expires, httpOnly, secure, sameSite.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-add-cookies

Source

pub async fn cookies(&self, urls: Option<&[&str]>) -> Result<Vec<Cookie>>

Returns cookies for this browser context, optionally filtered by URLs.

If urls is None or empty, all cookies are returned.

§Arguments
  • urls - Optional list of URLs to filter cookies by
§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-cookies

Source

pub async fn clear_cookies( &self, options: Option<ClearCookiesOptions>, ) -> Result<()>

Clears cookies from this browser context, with optional filters.

When called with no options, all cookies are removed. Use ClearCookiesOptions to filter which cookies to clear by name, domain, or path.

§Arguments
  • options - Optional filters for which cookies to clear
§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-clear-cookies

Source

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

Sets extra HTTP headers that will be sent with every request from this context.

These headers are merged with per-page extra headers set with page.set_extra_http_headers(). If the page has specific headers that conflict, page-level headers take precedence.

§Arguments
  • headers - Map of header names to values. All header names are lowercased.
§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers

Source

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

Grants browser permissions to the context.

Permissions are granted for all pages in the context. The optional origin in GrantPermissionsOptions restricts the grant to a specific URL origin.

Common permissions: "geolocation", "notifications", "camera", "microphone", "clipboard-read", "clipboard-write".

§Arguments
  • permissions - List of permission strings to grant
  • options - Optional options, including origin to restrict the grant
§Errors

Returns error if:

  • Permission name is not recognised
  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions

Source

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

Clears all permission overrides for this browser context.

Reverts all permissions previously set with grant_permissions() back to the browser default state.

§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-clear-permissions

Source

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

Sets or clears the geolocation for all pages in this context.

Pass Some(Geolocation { ... }) to set a specific location, or None to clear the override and let the browser handle location requests naturally.

Note: Geolocation access requires the "geolocation" permission to be granted via grant_permissions() for navigator.geolocation to succeed.

§Arguments
  • geolocation - Location to set, or None to clear
§Errors

Returns error if:

  • Latitude or longitude is out of range
  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation

Source

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

Toggles the offline mode for this browser context.

When true, all network requests from pages in this context will fail with a network error. Set to false to restore network connectivity.

§Arguments
  • offline - true to go offline, false to go back online
§Errors

Returns error if:

  • Context has been closed
  • Communication with browser process fails

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline

Source

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

Registers a route handler for context-level network interception.

Routes registered on a context apply to all pages within the context. Page-level routes take precedence over context-level routes.

§Arguments
  • pattern - URL pattern to match (supports glob patterns like “**/*.png”)
  • handler - Async closure that handles the route

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-route

Source

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

Removes route handler(s) matching the given URL pattern.

§Arguments
  • pattern - URL pattern to remove handlers for

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute

Source

pub async fn unroute_all( &self, _behavior: Option<UnrouteBehavior>, ) -> Result<()>

Removes all registered route handlers.

§Arguments
  • behavior - Optional behavior for in-flight handlers

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute-all

Source

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

Adds a listener for the page event.

The handler is called whenever a new page is created in this context, including popup pages opened through user interactions.

§Arguments
  • handler - Async function that receives the new Page

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-page

Source

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

Adds a listener for the close event.

The handler is called when the browser context is closed.

§Arguments
  • handler - Async function called with no arguments when the context closes

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-close

Source

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

Adds a listener for the request event.

The handler fires whenever a request is issued from any page in the context. This is equivalent to subscribing to on_request on each individual page, but covers all current and future pages of the context.

Context-level handlers fire before page-level handlers.

§Arguments
  • handler - Async function that receives the Request

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-request

Source

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

Adds a listener for the requestFinished event.

The handler fires after the request has been successfully received by the server and a response has been fully downloaded for any page in the context.

Context-level handlers fire before page-level handlers.

§Arguments
  • handler - Async function that receives the completed Request

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-request-finished

Source

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

Adds a listener for the requestFailed event.

The handler fires when a request from any page in the context fails, for example due to a network error or if the server returned an error response.

Context-level handlers fire before page-level handlers.

§Arguments
  • handler - Async function that receives the failed Request

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-request-failed

Source

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

Adds a listener for the response event.

The handler fires whenever a response is received from any page in the context.

Context-level handlers fire before page-level handlers.

§Arguments
  • handler - Async function that receives the ResponseObject

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-response

Source

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

Adds a listener for the dialog event on this browser context.

The handler fires whenever a JavaScript dialog (alert, confirm, prompt, or beforeunload) is triggered from any page in the context. Context-level handlers fire before page-level handlers.

The dialog must be explicitly accepted or dismissed; otherwise the page will freeze waiting for a response.

§Arguments
  • handler - Async function that receives the Dialog and calls dialog.accept() or dialog.dismiss().
§Errors

Returns error if communication with the browser process fails.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-dialog

Source

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

Registers a context-level console event handler.

The handler fires for any console message emitted by any page in this context. Context-level handlers fire before page-level handlers.

The server only sends console events after the first handler is registered (subscription is managed automatically per context channel).

§Arguments

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-console

Source

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

Registers a context-level handler for uncaught JavaScript exceptions.

The handler fires whenever a page in this context throws an unhandled JavaScript error (i.e. an exception that propagates to window.onerror or an unhandled promise rejection). The WebError passed to the handler contains the error message and an optional back-reference to the originating page.

§Arguments
  • handler - Async closure that receives a WebError.
§Errors

Returns error if communication with the browser process fails.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-web-error

Source

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

Registers a handler for the serviceWorker event.

The handler is called when a new service worker is registered in the browser context.

Note: Service worker testing typically requires HTTPS and a registered service worker.

§Arguments
  • handler - Async closure called with the new Worker object

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-service-worker

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,

Exposes a Rust function to every page in this browser context as window[name] in JavaScript.

When JavaScript code calls window[name](arg1, arg2, …) the Playwright server fires a bindingCall event that invokes callback with the deserialized arguments. The return value of callback is serialized back to JavaScript so the await window[name](…) expression resolves with it.

The binding is injected into every existing page and every new page created in this context.

§Arguments
  • name – JavaScript identifier that will be available as window[name].
  • callback – Async closure called with Vec<serde_json::Value> (the JS arguments) and returning serde_json::Value (the result).
§Errors

Returns error if:

  • The context has been closed.
  • Communication with the browser process fails.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-function

Source

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

Exposes a Rust function to every page in this browser context as window[name] in JavaScript, with needsHandle: true.

Identical to expose_function but the Playwright server passes the first argument as a JSHandle object rather than a plain value. Use this when the JS caller passes complex objects that you want to inspect on the Rust side.

§Arguments
  • name – JavaScript identifier.
  • callback – Async closure with Vec<serde_json::Value>serde_json::Value.
§Errors

Returns error if:

  • The context has been closed.
  • Communication with the browser process fails.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-binding

Source

pub async fn expect_page( &self, timeout: Option<f64>, ) -> Result<EventWaiter<Page>>

Waits for a new page to be created in this browser context.

Creates a one-shot waiter that resolves when the next page event fires. The waiter must be created before the action that triggers the new page (e.g. new_page() or a user action that opens a popup) to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns Error::Timeout if no page is created within the timeout.

§Example
// Set up the waiter BEFORE the triggering action
let waiter = context.expect_page(None).await?;
let _page = context.new_page().await?;
let new_page = waiter.wait().await?;

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-wait-for-event

Source

pub async fn expect_close( &self, timeout: Option<f64>, ) -> Result<EventWaiter<()>>

Waits for this browser context to be closed.

Creates a one-shot waiter that resolves when the close event fires. The waiter must be created before the action that closes the context to avoid a race condition.

§Arguments
  • timeout - Timeout in milliseconds. Defaults to 30 000 ms if None.
§Errors

Returns Error::Timeout if the context is not closed within the timeout.

§Example
// Set up the waiter BEFORE closing
let waiter = context.expect_close(None).await?;
context.close().await?;
waiter.wait().await?;

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-wait-for-event

Source

pub async fn expect_console_message( &self, timeout: Option<f64>, ) -> Result<EventWaiter<ConsoleMessage>>

Waits for a console message from any page in this context.

See: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-console

Source

pub fn deserialize_binding_args_pub(raw_args: &Value) -> Vec<Value>

Deserializes binding call arguments from Playwright’s protocol format.

The args field in the BindingCall initializer is a JSON array where each element is in serialize_argument format: {"value": <tagged>, "handles": []}. This helper extracts the inner “value” from each entry and parses it.

This is pub so that Page::on_event("bindingCall") can reuse it without duplicating the deserialization logic.

Trait Implementations§

Source§

impl Clone for BrowserContext

Source§

fn clone(&self) -> BrowserContext

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for BrowserContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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> 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