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
impl BrowserContext
Sourcepub async fn request(&self) -> Result<APIRequestContext, ContextError>
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.
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
impl BrowserContext
Sourcepub async fn expose_function<F, Fut>(&self, name: &str, callback: F)
pub async fn expose_function<F, Fut>(&self, name: &str, callback: F)
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?;Sourcepub async fn remove_exposed_function(&self, name: &str) -> bool
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
impl BrowserContext
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.
Create a builder for clearing cookies with filters.
Source§impl BrowserContext
impl BrowserContext
Sourcepub async fn clear_geolocation(&self) -> Result<(), ContextError>
pub async fn clear_geolocation(&self) -> Result<(), ContextError>
Sourcepub async fn set_extra_http_headers(
&self,
headers: HashMap<String, String>,
) -> Result<(), ContextError>
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.
Sourcepub async fn set_offline(&self, offline: bool) -> Result<(), ContextError>
pub async fn set_offline(&self, offline: bool) -> Result<(), ContextError>
Source§impl BrowserContext
impl BrowserContext
Sourcepub async fn record_har(
&self,
path: impl Into<PathBuf>,
) -> Result<HarRecordingBuilder, NetworkError>
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
Sourcepub async fn start_har_recording(
&self,
options: HarRecordingOptions,
) -> Result<(), NetworkError>
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.
Sourcepub async fn save_har(&self) -> Result<PathBuf, NetworkError>
pub async fn save_har(&self) -> Result<PathBuf, NetworkError>
Sourcepub async fn stop_har_recording(
&self,
save: bool,
) -> Result<Option<PathBuf>, NetworkError>
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
impl BrowserContext
Sourcepub async fn on_page<F, Fut>(&self, handler: F) -> HandlerId
pub async fn on_page<F, Fut>(&self, handler: F) -> HandlerId
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;Sourcepub async fn off_page(&self, handler_id: HandlerId) -> bool
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.
Sourcepub async fn off_close(&self, handler_id: HandlerId) -> bool
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.
Sourcepub fn wait_for_page<F, Fut>(&self, action: F) -> WaitForPageBuilder<'_, F, Fut>
pub fn wait_for_page<F, Fut>(&self, action: F) -> WaitForPageBuilder<'_, F, Fut>
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
impl BrowserContext
Sourcepub async fn grant_permissions(
&self,
permissions: Vec<Permission>,
) -> Result<(), ContextError>
pub async fn grant_permissions( &self, permissions: Vec<Permission>, ) -> Result<(), ContextError>
Sourcepub async fn grant_permissions_for_origin(
&self,
permissions: Vec<Permission>,
origin: impl Into<String>,
) -> Result<(), ContextError>
pub async fn grant_permissions_for_origin( &self, permissions: Vec<Permission>, origin: impl Into<String>, ) -> Result<(), ContextError>
Sourcepub async fn clear_permissions(&self) -> Result<(), ContextError>
pub async fn clear_permissions(&self) -> Result<(), ContextError>
Source§impl BrowserContext
impl BrowserContext
Sourcepub async fn route<M, H, Fut>(
&self,
pattern: M,
handler: H,
) -> Result<(), NetworkError>
pub async fn route<M, H, Fut>( &self, pattern: M, handler: H, ) -> Result<(), NetworkError>
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.
Sourcepub async fn route_predicate<P, H, Fut>(
&self,
predicate: P,
handler: H,
) -> Result<(), NetworkError>
pub async fn route_predicate<P, H, Fut>( &self, predicate: P, handler: H, ) -> Result<(), NetworkError>
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.
Sourcepub async fn unroute(&self, pattern: &str)
pub async fn unroute(&self, pattern: &str)
Unregister handlers matching the given pattern.
This removes handlers registered with route() that match the pattern.
Sourcepub async fn unroute_all(&self)
pub async fn unroute_all(&self)
Unregister all route handlers.
This removes all handlers registered with route().
Sourcepub async fn route_from_har(
&self,
path: impl AsRef<Path>,
) -> Result<(), NetworkError>
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
Sourcepub async fn route_from_har_with_options(
&self,
path: impl AsRef<Path>,
options: HarReplayOptions,
) -> Result<(), NetworkError>
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
impl BrowserContext
Sourcepub async fn add_init_script(
&self,
script: impl AsRef<str>,
) -> Result<(), ContextError>
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.
Sourcepub async fn add_init_script_path(
&self,
path: impl AsRef<Path>,
) -> Result<(), ContextError>
pub async fn add_init_script_path( &self, path: impl AsRef<Path>, ) -> Result<(), ContextError>
Sourcepub async fn init_scripts(&self) -> Vec<String>
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
impl BrowserContext
Sourcepub async fn storage_state(&self) -> Result<StorageState, ContextError>
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.
Sourcepub fn storage_state_builder(&self) -> StorageStateBuilder<'_>
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
impl BrowserContext
Sourcepub async fn set_test_id_attribute(&self, name: impl Into<String>)
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"]Sourcepub async fn test_id_attribute(&self) -> String
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
impl BrowserContext
Sourcepub fn tracing(&self) -> Tracing
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
impl BrowserContext
Sourcepub async fn on_weberror<F, Fut>(&self, handler: F)
pub async fn on_weberror<F, Fut>(&self, handler: F)
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;Sourcepub async fn off_weberror(&self)
pub async fn off_weberror(&self)
Remove the web error handler.
Source§impl BrowserContext
impl BrowserContext
Sourcepub async fn new_page(&self) -> Result<Page, ContextError>
pub async fn new_page(&self) -> Result<Page, ContextError>
Sourcepub fn set_geolocation(
&self,
latitude: f64,
longitude: f64,
) -> SetGeolocationBuilder<'_>
pub fn set_geolocation( &self, latitude: f64, longitude: f64, ) -> SetGeolocationBuilder<'_>
Sourcepub fn set_default_timeout(&mut self, timeout: Duration)
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.
Sourcepub fn default_timeout(&self) -> Duration
pub fn default_timeout(&self) -> Duration
Get the default timeout for actions.
Set the default navigation timeout.
This timeout is used for navigation operations like goto, reload, etc.
Get the default navigation timeout.
Sourcepub async fn close(&mut self) -> Result<(), ContextError>
pub async fn close(&mut self) -> Result<(), ContextError>
Sourcepub fn connection(&self) -> &Arc<CdpConnection>
pub fn connection(&self) -> &Arc<CdpConnection>
Get a reference to the CDP connection.
Sourcepub fn context_id(&self) -> &str
pub fn context_id(&self) -> &str
Get the context ID.