BrowserContext

Struct BrowserContext 

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

BrowserContext represents an isolated browser session.

Contexts are isolated environments within a browser instance. Each context has its own cookies, cache, and local storage, enabling independent sessions without interference.

§Example

use playwright_rs::protocol::Playwright;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let playwright = Playwright::launch().await?;
    let browser = playwright.chromium().launch().await?;

    // Create isolated contexts
    let context1 = browser.new_context().await?;
    let context2 = browser.new_context().await?;

    // Create pages in each context
    let page1 = context1.new_page().await?;
    let page2 = context2.new_page().await?;

    // Access all pages in a context
    let pages = context1.pages();
    assert_eq!(pages.len(), 1);

    // Access the browser from a context
    let ctx_browser = context1.browser().unwrap();
    assert_eq!(ctx_browser.name(), browser.name());

    // App mode: access initial page created automatically
    let chromium = playwright.chromium();
    let app_context = chromium
        .launch_persistent_context_with_options(
            "/tmp/app-data",
            playwright_rs::protocol::BrowserContextOptions::builder()
                .args(vec!["--app=https://example.com".to_string()])
                .headless(true)
                .build()
        )
        .await?;

    // Get the initial page (don't create a new one!)
    let app_pages = app_context.pages();
    if !app_pages.is_empty() {
        let initial_page = &app_pages[0];
        // Use the initial page...
    }

    // Cleanup
    context1.close().await?;
    context2.close().await?;
    app_context.close().await?;
    browser.close().await?;
    Ok(())
}

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

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

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