BrowserContext

Struct BrowserContext 

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

An isolated browser context.

Browser contexts are similar to incognito windows - they have their own cookies, cache, and storage that are isolated from other contexts.

§Features

  • Cookie Management: Add, get, and clear cookies
  • Storage State: Save and restore browser state
  • Permissions: Grant permissions like geolocation, camera, etc.
  • Geolocation: Mock browser location
  • HTTP Credentials: Basic/Digest authentication
  • Extra Headers: Add headers to all requests
  • Offline Mode: Simulate network offline conditions
  • Event Handling: Listen for page creation and context close events
  • Init Scripts: Scripts that run before every page load
  • Custom Test ID: Configure which attribute is used for test IDs

Implementations§

Source§

impl BrowserContext

Source

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

Get an API request context associated with this browser context.

The returned APIRequestContext can be used to make HTTP requests. Cookies from the browser context are automatically synced to the API context.

§Example
use viewpoint_core::{Browser, BrowserContext};

let browser = Browser::launch().await?;
let context = browser.new_context().await?;

// Get API context (includes browser cookies)
let api = context.request().await?;

// Make API requests with browser cookies
let response = api.get("https://api.example.com/data").send().await?;
§Errors

Returns an error if the API context cannot be created.

Source

pub async fn sync_cookies_from_api( &self, api: &APIRequestContext, url: &str, ) -> Result<(), ContextError>

Sync cookies from API responses back to the browser context.

Call this after making API requests that may have set cookies (e.g., login endpoints) to ensure the browser has the same cookies.

§Example
// Login via API
let api = context.request().await?;
let response = api.post("https://api.example.com/login")
    .json(&serde_json::json!({"user": "admin", "pass": "secret"}))
    .send()
    .await?;

// Sync cookies back to browser (e.g., session cookies from Set-Cookie)
context.sync_cookies_from_api(&api, "https://api.example.com").await?;

// Now browser pages will have the session cookie
§Errors

Returns an error if cookie syncing fails.

Source§

impl BrowserContext

Source

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

Expose a Rust function to JavaScript in all pages of this context.

The function will be available as window.<name>() in JavaScript. When called from JavaScript, the function arguments are serialized to JSON, the Rust callback is executed, and the result is returned to JavaScript.

Note: Functions exposed at the context level need to be explicitly applied to each page. This method registers the function for future pages, but you need to call expose_function on existing pages separately.

§Example
// Expose a function to all pages
context.expose_function("add", |args| async move {
    let x = args[0].as_i64().unwrap_or(0);
    let y = args[1].as_i64().unwrap_or(0);
    Ok(serde_json::json!(x + y))
}).await;

// Create a page - function is available
let page = context.new_page().await?;
Source

pub async fn remove_exposed_function(&self, name: &str) -> bool

Remove an exposed function from the context.

Note: This only affects future pages. Existing pages will still have the function available until they are reloaded.

Source§

impl BrowserContext

Source

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

Add cookies to the browser context.

§Example
use viewpoint_core::{BrowserContext, context::{Cookie, SameSite}};

context.add_cookies(vec![
    Cookie::new("session", "abc123")
        .domain("example.com")
        .path("/")
        .secure(true)
        .http_only(true),
]).await?;
§Errors

Returns an error if setting cookies fails.

Source

pub async fn cookies(&self) -> Result<Vec<Cookie>, ContextError>

Get all cookies in the browser context.

§Errors

Returns an error if getting cookies fails.

Source

pub async fn cookies_for_urls( &self, urls: Vec<String>, ) -> Result<Vec<Cookie>, ContextError>

Get cookies for specific URLs.

Note: This method gets all cookies and filters client-side by URL domain matching.

§Errors

Returns an error if getting cookies fails.

Source

pub async fn cookies_for_url( &self, url: impl Into<String>, ) -> Result<Vec<Cookie>, ContextError>

Get cookies for a specific URL.

§Errors

Returns an error if getting cookies fails.

Source

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

Clear all cookies in the browser context.

§Errors

Returns an error if clearing cookies fails.

Source

pub fn clear_cookies_builder(&self) -> ClearCookiesBuilder<'_>

Create a builder for clearing cookies with filters.

Source§

impl BrowserContext

Source

pub async fn clear_geolocation(&self) -> Result<(), ContextError>

Clear the geolocation override.

§Errors

Returns an error if clearing geolocation fails.

Source

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

Set extra HTTP headers to be sent with every request.

§Example
use viewpoint_core::BrowserContext;
use std::collections::HashMap;

let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), "Bearer token123".to_string());
context.set_extra_http_headers(headers).await?;
§Errors

Returns an error if setting headers fails.

Source

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

Set offline mode.

§Example
use viewpoint_core::BrowserContext;

// Go offline
context.set_offline(true).await?;

// Go back online
context.set_offline(false).await?;
§Errors

Returns an error if setting offline mode fails.

Source§

impl BrowserContext

Source

pub async fn record_har( &self, path: impl Into<PathBuf>, ) -> Result<HarRecordingBuilder, NetworkError>

Start recording network traffic to a HAR file.

All network requests and responses will be captured and saved to the specified path when close() is called or when save_har() is called.

§Example
// Basic recording
context.record_har("output.har").await?;

// Navigate and make requests...
page.goto("https://example.com").await?;

// HAR is saved automatically on context.close()
context.close().await?;
§Errors

Returns an error if:

  • HAR recording is already active
  • The context is closed
Source

pub async fn start_har_recording( &self, options: HarRecordingOptions, ) -> Result<(), NetworkError>

Start HAR recording with the given options.

§Example
use viewpoint_core::network::HarRecordingBuilder;

// Record only API requests
context.start_har_recording(
    HarRecordingBuilder::new("api.har")
        .url_filter("**/api/**")
        .build()
).await?;

// Omit response content
context.start_har_recording(
    HarRecordingBuilder::new("requests.har")
        .omit_content(true)
        .build()
).await?;
§Errors

Returns an error if the context is closed or HAR recording is already active.

Source

pub async fn save_har(&self) -> Result<PathBuf, NetworkError>

Save the current HAR recording to file.

§Example
context.record_har("output.har").await?;
// ... do some navigation ...
let path = context.save_har().await?;
println!("HAR saved to: {}", path.display());
§Errors

Returns an error if:

  • No HAR recording is active
  • Failed to write the file
Source

pub async fn stop_har_recording( &self, save: bool, ) -> Result<Option<PathBuf>, NetworkError>

Stop HAR recording and optionally save to file.

If save is true, the HAR file is saved before stopping.

§Errors

Returns an error if saving the HAR file fails.

Source§

impl BrowserContext

Source

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

Register a handler for new page events.

The handler will be called whenever a new page is created in this context. Returns a handler ID that can be used to remove the handler with off_page.

§Example
let handler_id = context.on_page(|page: Page| async move {
    println!("New page created: {}", page.url().await.unwrap_or_default());
}).await;

// Later, remove the handler
context.off_page(handler_id).await;
Source

pub async fn off_page(&self, handler_id: HandlerId) -> bool

Remove a page event handler by its ID.

Returns true if a handler was removed, false if the ID was not found.

Source

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

Register a handler for context close events.

The handler will be called when the context is about to close, before cleanup begins.

§Example
let handler_id = context.on_close(|| async {
    println!("Context is closing!");
}).await;

// Later, remove the handler
context.off_close(handler_id).await;
Source

pub async fn off_close(&self, handler_id: HandlerId) -> bool

Remove a close event handler by its ID.

Returns true if a handler was removed, false if the ID was not found.

Source

pub fn wait_for_page<F, Fut>(&self, action: F) -> WaitForPageBuilder<'_, F, Fut>
where F: FnOnce() -> Fut, Fut: Future<Output = Result<(), ContextError>>,

Wait for a new page to be created during an action.

This is useful for handling popups or links that open in new tabs. The action is executed and the method waits for a new page to be created as a result.

§Example
let popup = context.wait_for_page(|| async {
    page.locator("a[target=_blank]").click().await?;
    Ok(())
}).await?;

// Now work with the popup page
popup.goto("https://example.com").goto().await?;
§Errors

Returns an error if:

  • The action fails
  • No page is created within the timeout (30 seconds)
Source§

impl BrowserContext

Source

pub async fn grant_permissions( &self, permissions: Vec<Permission>, ) -> Result<(), ContextError>

Grant permissions to the browser context.

§Example
use viewpoint_core::{BrowserContext, context::Permission};

context.grant_permissions(vec![
    Permission::Geolocation,
    Permission::Notifications,
]).await?;
§Errors

Returns an error if granting permissions fails.

Source

pub async fn grant_permissions_for_origin( &self, permissions: Vec<Permission>, origin: impl Into<String>, ) -> Result<(), ContextError>

Grant permissions for a specific origin.

§Errors

Returns an error if granting permissions fails.

Source

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

Clear all granted permissions.

§Errors

Returns an error if clearing permissions fails.

Source§

impl BrowserContext

Source

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

Register a route handler that applies to all pages in this context.

Routes registered at the context level are applied to all pages, including new pages created after the route is registered. Context routes are checked before page-level routes.

§Example
use viewpoint_core::Route;

// Block all analytics requests for all pages
context.route("**/analytics/**", |route: Route| async move {
    route.abort().await
}).await?;

// Mock an API for all pages
context.route("**/api/users", |route: Route| async move {
    route.fulfill()
        .status(200)
        .json(&serde_json::json!({"users": []}))
        .send()
        .await
}).await?;
§Errors

Returns an error if the context is closed.

Source

pub async fn route_predicate<P, H, Fut>( &self, predicate: P, handler: H, ) -> Result<(), NetworkError>
where P: Fn(&str) -> bool + Send + Sync + 'static, H: Fn(Route) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), NetworkError>> + Send + 'static,

Register a route handler with a predicate function.

§Example
// Block POST requests to any API endpoint
context.route_predicate(
    |url| url.contains("/api/"),
    |route: Route| async move {
        if route.request().method() == "POST" {
            route.abort().await
        } else {
            route.continue_().await
        }
    }
).await?;
§Errors

Returns an error if the context is closed.

Source

pub async fn unroute(&self, pattern: &str)

Unregister handlers matching the given pattern.

This removes handlers registered with route() that match the pattern.

Source

pub async fn unroute_all(&self)

Unregister all route handlers.

This removes all handlers registered with route().

Source

pub async fn route_from_har( &self, path: impl AsRef<Path>, ) -> Result<(), NetworkError>

Route requests from a HAR file for all pages in this context.

Requests that match entries in the HAR file will be fulfilled with the recorded responses. Requests that don’t match will continue normally unless strict mode is enabled.

§Example
// Simple HAR routing for all pages
context.route_from_har("recordings/api.har").await?;

// With options
context.route_from_har_with_options(
    "recordings/api.har",
    HarReplayOptions::new()
        .url("**/api/**")
        .strict(true)
).await?;
§Errors

Returns an error if:

  • The HAR file cannot be read or parsed
  • The context is closed
Source

pub async fn route_from_har_with_options( &self, path: impl AsRef<Path>, options: HarReplayOptions, ) -> Result<(), NetworkError>

Route requests from a HAR file with options for all pages in this context.

§Example
use viewpoint_core::network::{HarReplayOptions, TimingMode};

// Strict mode: fail if no match found
context.route_from_har_with_options(
    "api.har",
    HarReplayOptions::new().strict(true)
).await?;

// URL filter: only match specific URLs
context.route_from_har_with_options(
    "api.har",
    HarReplayOptions::new().url("**/api/**")
).await?;

// Simulate original timing
context.route_from_har_with_options(
    "api.har",
    HarReplayOptions::new().use_original_timing(true)
).await?;
§Errors

Returns an error if:

  • The HAR file cannot be read or parsed
  • The context is closed
Source§

impl BrowserContext

Source

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

Add a script to be evaluated before every new page load.

The script will run before any scripts on the page, and will persist for all pages created in this context (including popups).

Unlike page.add_init_script(), this applies to all pages in the context, not just a single page.

§Example
// Mock navigator.webdriver for all pages
context.add_init_script(
    "Object.defineProperty(navigator, 'webdriver', { get: () => false })"
).await?;

// All new pages will have this script applied
let page = context.new_page().await?;
§Errors

Returns an error if the context is closed.

Source

pub async fn add_init_script_path( &self, path: impl AsRef<Path>, ) -> Result<(), ContextError>

Add an init script from a file path.

The file contents will be read and registered as an init script for all pages in this context.

§Example
context.add_init_script_path("./scripts/mock-auth.js").await?;
§Errors

Returns an error if the file cannot be read or the context is closed.

Source

pub async fn init_scripts(&self) -> Vec<String>

Get all context-level init scripts.

This returns the scripts that will be applied to all new pages.

Source§

impl BrowserContext

Source

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

Get the storage state (cookies and localStorage).

This method collects cookies and localStorage for all pages in the context. For more advanced options including IndexedDB, use storage_state_builder().

§Example
use viewpoint_core::BrowserContext;

let state = context.storage_state().await?;
state.save("auth.json").await?;
§Errors

Returns an error if getting storage state fails.

Source

pub fn storage_state_builder(&self) -> StorageStateBuilder<'_>

Create a builder for collecting storage state with options.

Use this method when you need to include IndexedDB data or configure other collection options.

§Example
use viewpoint_core::BrowserContext;

// Include IndexedDB data
let state = context.storage_state_builder()
    .indexed_db(true)
    .collect()
    .await?;

state.save("full-state.json").await?;
Source§

impl BrowserContext

Source

pub async fn set_test_id_attribute(&self, name: impl Into<String>)

Set the custom test ID attribute for this context.

By default, get_by_test_id() uses the data-testid attribute. Call this method to use a different attribute name.

§Example
// Use data-test instead of data-testid
context.set_test_id_attribute("data-test").await;

// Now get_by_test_id looks for data-test attribute
let page = context.new_page().await?;
let button = page.get_by_test_id("submit"); // looks for [data-test="submit"]
Source

pub async fn test_id_attribute(&self) -> String

Get the current test ID attribute name.

Returns the attribute name used by get_by_test_id() (default: data-testid).

Source§

impl BrowserContext

Source

pub fn tracing(&self) -> Tracing

Get a tracing controller for recording test execution traces.

Traces capture screenshots, DOM snapshots, and network activity for debugging test failures. The resulting trace files are compatible with Playwright’s Trace Viewer.

Note: At least one page must exist in the context before starting tracing. The tracing state is shared across all tracing() calls within the same context.

§Example
use viewpoint_core::context::TracingOptions;

// Create a page first (required before starting tracing)
let page = context.new_page().await.unwrap();

// Start tracing with screenshots
context.tracing().start(
    TracingOptions::new()
        .screenshots(true)
        .snapshots(true)
).await.unwrap();

// Perform test actions
page.goto("https://example.com").goto().await.unwrap();

// Stop and save trace (state persists across tracing() calls)
context.tracing().stop("/tmp/trace.zip").await.unwrap();
Source§

impl BrowserContext

Source

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

Set a handler for web errors (uncaught exceptions from any page).

The handler will be called whenever an uncaught JavaScript exception occurs in any page within this context.

§Example
context.on_weberror(|error| async move {
    eprintln!("Error in {}: {}", error.target_id(), error.message());
    if let Some(stack) = error.stack() {
        eprintln!("Stack:\n{}", stack);
    }
}).await;
Source

pub async fn off_weberror(&self)

Remove the web error handler.

Source§

impl BrowserContext

Source

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

Create a new page in this context.

§Errors

Returns an error if page creation fails.

Source

pub async fn pages(&self) -> Result<Vec<PageInfo>, ContextError>

Get all pages in this context.

§Errors

Returns an error if querying targets fails.

Source

pub fn set_geolocation( &self, latitude: f64, longitude: f64, ) -> SetGeolocationBuilder<'_>

Set the geolocation.

§Example
use viewpoint_core::BrowserContext;

// San Francisco
context.set_geolocation(37.7749, -122.4194).await?;
§Errors

Returns an error if setting geolocation fails.

Source

pub fn set_default_timeout(&mut self, timeout: Duration)

Set the default timeout for actions.

This timeout is used for actions like clicking, typing, etc.

Source

pub fn default_timeout(&self) -> Duration

Get the default timeout for actions.

Source

pub fn set_default_navigation_timeout(&mut self, timeout: Duration)

Set the default navigation timeout.

This timeout is used for navigation operations like goto, reload, etc.

Source

pub fn default_navigation_timeout(&self) -> Duration

Get the default navigation timeout.

Source

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

Close this browser context and all its pages.

§Errors

Returns an error if closing fails.

Source

pub fn id(&self) -> &str

Get the context ID.

Source

pub fn is_closed(&self) -> bool

Check if this context has been closed.

Source

pub fn connection(&self) -> &Arc<CdpConnection>

Get a reference to the CDP connection.

Source

pub fn context_id(&self) -> &str

Get the context ID.

Trait Implementations§

Source§

impl Debug for BrowserContext

Source§

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

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> 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, 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