# `Playwright.BrowserContext`
[🔗](https://github.com/ftes/playwright_ex/blob/v1.65.0-rc.3/lib/playwright/api/browser_context.ex#L7)

BrowserContexts provide a way to operate multiple independent browser sessions.

If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser
context.

Playwright allows creating isolated non-persistent browser contexts with `Playwright.Browser.new_context/2` method. Non-persistent browser
contexts don't write any browsing data to disk.

```elixir
# Create a new incognito browser context
context = Browser.new_context!(browser)
# Create a new page inside context.
page = BrowserContext.new_page!(context)
Page.goto!(page, "https://example.com")
# Dispose context once it's no longer needed.
BrowserContext.close!(context)
```

*Since Playwright 1.8.*

The examples alias the modules they use (`alias Playwright.{Locator, Page}`).

## Events

### `:background_page`

*Since Playwright 1.11.* This event is not emitted.

### `:close`

Emitted when Browser context gets closed. This might happen because of one of the following:

* Browser context is closed.
* Browser application is closed or crashed.
* The `Playwright.Browser.close/2` method was called.

### `:console`

*Since Playwright 1.34.* Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.

The arguments passed into `console.log` and the page are available on the [`ConsoleMessage`](`Playwright.ConsoleMessage`) event handler argument.

**Usage**

```elixir
BrowserContext.on(context, :console, fn msg ->
  values = for arg <- ConsoleMessage.args(msg), do: JSHandle.json_value!(arg)
  IO.puts(inspect(values))
end)

Page.evaluate!(page, "() => console.log('hello', 5, { foo: 'bar' })")
```

### `:dialog`

*Since Playwright 1.34.* Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must** either `Playwright.Dialog.accept/2` or `Playwright.Dialog.dismiss/1` the dialog - otherwise the page will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog, and actions like click will never finish.

**Usage**

```elixir
BrowserContext.on(context, :dialog, fn dialog ->
  Dialog.accept!(dialog)
end)
```

> #### Note {: .info}
>
> When no [`Page.on(:dialog)`](Playwright.Page.html#module-dialog) or [`BrowserContext.on(:dialog)`](Playwright.BrowserContext.html#module-dialog) listeners are present, all dialogs are automatically dismissed.

### `:dialog_closed`

*Since Playwright 1.63.* Emitted when a JavaScript dialog in any page belonging to this context has been closed, either by `Playwright.Dialog.accept/2`, by `Playwright.Dialog.dismiss/1`, or manually by the user in the headed browser.

### `:download`

*Since Playwright 1.60.* Emitted when attachment download started in any page belonging to this context. User can access basic file operations on downloaded content via the passed [`Download`](`Playwright.Download`) instance. See also [`Page.on(:download)`](Playwright.Page.html#module-download) to receive events about a specific page.

### `:frame_attached`

*Since Playwright 1.60.* Emitted when a frame is attached in any page belonging to this context. See also [`Page.on(:frame_attached)`](Playwright.Page.html#module-frame_attached) to receive events about a specific page.

### `:frame_detached`

*Since Playwright 1.60.* Emitted when a frame is detached in any page belonging to this context. See also [`Page.on(:frame_detached)`](Playwright.Page.html#module-frame_detached) to receive events about a specific page.

### `:frame_navigated`

*Since Playwright 1.60.* Emitted when a frame is navigated to a new url in any page belonging to this context. See also [`Page.on(:frame_navigated)`](Playwright.Page.html#module-frame_navigated) to receive events about navigations in a specific page.

### `:page`

The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will
also fire for popup pages. See also [`Page.on(:popup)`](Playwright.Page.html#module-popup) to receive events about popups relevant to a specific page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
popup with `window.open('http://example.com')`, this event will fire when the network request to "http://example.com" is
done and its response has started loading in the popup. If you would like to route/listen to this network request, use `Playwright.BrowserContext.route/4` and [`BrowserContext.on(:request)`](Playwright.BrowserContext.html#module-request) respectively instead of similar methods on the [`Page`](`Playwright.Page`).

```elixir
new_page_promise = BrowserContext.wait_for_event(context, :page)
Page.get_by_text(page, "open new page") |> Locator.click!()
new_page = Promise.await!(new_page_promise)
IO.puts(Page.evaluate!(new_page, "location.href"))
```

> #### Note {: .info}
>
> Use `Playwright.Page.wait_for_load_state/3` to wait until the page gets to a particular state (you should not need it in most
> cases).

### `:page_close`

*Since Playwright 1.60.* Emitted when a page in this context is closed. See also [`Page.on(:close)`](Playwright.Page.html#module-close) to receive events about a specific page.

### `:page_load`

*Since Playwright 1.60.* Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched in any page belonging to this context. See also [`Page.on(:load)`](Playwright.Page.html#module-load) to receive events about a specific page.

### `:web_error`

*Since Playwright 1.38.* Emitted when exception is unhandled in any of the pages in this
context. To listen for errors from a particular page, use [`Page.on(:page_error)`](Playwright.Page.html#module-page_error) instead.

### `:request`

*Since Playwright 1.12.* Emitted when a request is issued from any pages created through this context.
The [`Request`](`Playwright.Request`) object is read-only. To only listen for requests from a particular
page, use [`Page.on(:request)`](Playwright.Page.html#module-request).

In order to intercept and mutate requests, see `Playwright.BrowserContext.route/4`
or `Playwright.Page.route/4`.

### `:request_failed`

*Since Playwright 1.12.* Emitted when a request fails, for example by timing out. To only listen for
failed requests from a particular page, use [`Page.on(:request_failed)`](Playwright.Page.html#module-request_failed).

> #### Note {: .info}
>
> HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete
> with [`BrowserContext.on(:request_finished)`](Playwright.BrowserContext.html#module-request_finished) event and not with [`BrowserContext.on(:request_failed)`](Playwright.BrowserContext.html#module-request_failed).

### `:request_finished`

*Since Playwright 1.12.* Emitted when a request finishes successfully after downloading the response body. For a successful response, the
sequence of events is `request`, `response` and `requestfinished`. To listen for
successful requests from a particular page, use [`Page.on(:request_finished)`](Playwright.Page.html#module-request_finished).

### `:response`

*Since Playwright 1.12.* Emitted when [`Response`](`Playwright.Response`) status and headers are received for a request. For a successful response, the sequence of events
is `request`, `response` and `requestfinished`. To listen for response events
from a particular page, use [`Page.on(:response)`](Playwright.Page.html#module-response).

### `:service_worker`

*Since Playwright 1.11.*

> #### Note {: .info}
>
> Service workers are only supported on Chromium-based browsers.

Emitted when new service worker is created in the context.

# `add_init_script_options`

```elixir
@type add_init_script_options() ::
  [{:expose_functions, boolean()}] | %{optional(:expose_functions) =&gt; boolean()}
```

Options of `add_init_script/4`, see its docs.

# `clear_cookies_options`

```elixir
@type clear_cookies_options() ::
  [
    domain: String.t() | Regex.t() | Playwright.RegExp.t(),
    name: String.t() | Regex.t() | Playwright.RegExp.t(),
    path: String.t() | Regex.t() | Playwright.RegExp.t()
  ]
  | %{
      optional(:domain) =&gt; String.t() | Regex.t() | Playwright.RegExp.t(),
      optional(:name) =&gt; String.t() | Regex.t() | Playwright.RegExp.t(),
      optional(:path) =&gt; String.t() | Regex.t() | Playwright.RegExp.t()
    }
```

Options of `clear_cookies/2`, see its docs.

# `close_options`

```elixir
@type close_options() :: [{:reason, String.t()}] | %{optional(:reason) =&gt; String.t()}
```

Options of `close/2`, see its docs.

# `event`

```elixir
@type event() ::
  :background_page
  | :close
  | :console
  | :dialog
  | :dialog_closed
  | :download
  | :frame_attached
  | :frame_detached
  | :frame_navigated
  | :page
  | :page_close
  | :page_load
  | :web_error
  | :request
  | :request_failed
  | :request_finished
  | :response
  | :service_worker
```

An event name, see the module docs.

# `expect_console_message_options`

```elixir
@type expect_console_message_options() ::
  [
    predicate: (Playwright.ConsoleMessage.t() -&gt; boolean()),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; (Playwright.ConsoleMessage.t() -&gt; boolean()),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `expect_console_message/3`, see its docs.

# `expect_event_options`

```elixir
@type expect_event_options() ::
  [
    predicate: fun(),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; fun(),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `expect_event/4`, see its docs.

# `expect_page_options`

```elixir
@type expect_page_options() ::
  [
    predicate: (Playwright.Page.t() -&gt; boolean()),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; (Playwright.Page.t() -&gt; boolean()),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `expect_page/3`, see its docs.

# `grant_permissions_options`

```elixir
@type grant_permissions_options() ::
  [{:origin, String.t()}] | %{optional(:origin) =&gt; String.t()}
```

Options of `grant_permissions/3`, see its docs.

# `remove_all_listeners_options`

```elixir
@type remove_all_listeners_options() ::
  [{:behavior, :wait | :ignore_errors | :default}]
  | %{optional(:behavior) =&gt; :wait | :ignore_errors | :default}
```

Options of `remove_all_listeners/3`, see its docs.

# `route_from_har_options`

```elixir
@type route_from_har_options() ::
  [
    not_found: :abort | :fallback,
    update: boolean(),
    update_content: :embed | :attach,
    update_mode: :full | :minimal,
    url: String.t() | Regex.t() | Playwright.RegExp.t()
  ]
  | %{
      optional(:not_found) =&gt; :abort | :fallback,
      optional(:update) =&gt; boolean(),
      optional(:update_content) =&gt; :embed | :attach,
      optional(:update_mode) =&gt; :full | :minimal,
      optional(:url) =&gt; String.t() | Regex.t() | Playwright.RegExp.t()
    }
```

Options of `route_from_har/3`, see its docs.

# `route_options`

```elixir
@type route_options() :: [{:times, integer()}] | %{optional(:times) =&gt; integer()}
```

Options of `route/4`, see its docs.

# `storage_state_options`

```elixir
@type storage_state_options() ::
  [
    credentials: boolean(),
    indexed_db: boolean(),
    opfs: boolean(),
    path: String.t()
  ]
  | %{
      optional(:credentials) =&gt; boolean(),
      optional(:indexed_db) =&gt; boolean(),
      optional(:opfs) =&gt; boolean(),
      optional(:path) =&gt; String.t()
    }
```

Options of `storage_state/2`, see its docs.

# `t`

```elixir
@type t() :: %Playwright.BrowserContext{
  conn: term(),
  guid: term(),
  initializer: term(),
  table: term(),
  type: term()
}
```

A `BrowserContext` handle. Compare handles with `==`, their fields are internal.

# `unroute_all_options`

```elixir
@type unroute_all_options() ::
  [{:behavior, :wait | :ignore_errors | :default}]
  | %{optional(:behavior) =&gt; :wait | :ignore_errors | :default}
```

Options of `unroute_all/2`, see its docs.

# `wait_for_event_options`

```elixir
@type wait_for_event_options() ::
  [
    predicate: fun(),
    timeout: number() | :infinity,
    signal: Playwright.AbortSignal.t()
  ]
  | %{
      optional(:predicate) =&gt; fun(),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:signal) =&gt; Playwright.AbortSignal.t()
    }
```

Options of `wait_for_event/3`, see its docs.

# `add_cookies`

```elixir
@spec add_cookies(t(), [map()]) :: :ok | {:error, Playwright.error()}
```

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be
obtained via `Playwright.BrowserContext.cookies/2`.

**Usage**

```elixir
BrowserContext.add_cookies!(browser_context, [cookie_object1, cookie_object2])
```

*Since Playwright 1.8.*

## Arguments

* `cookies`
  * `:name`
  * `:value`
  * `:url` - Either `url` or both `domain` and `path` are required. Optional.
  * `:domain` - For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either `url` or both `domain` and `path` are required. Optional.
  * `:path` - Either `url` or both `domain` and `path` are required. Optional.
  * `:expires` - Unix time in seconds. Optional.
  * `:httpOnly` - Optional.
  * `:secure` - Optional.
  * `:sameSite` - Optional.
  * `:partitionKey` - For partitioned third-party cookies (aka [CHIPS](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Privacy_sandbox/Partitioned_cookies)), the partition key. Optional.

# `add_cookies!`

```elixir
@spec add_cookies!(t(), [map()]) :: :ok
```

Like `add_cookies/2`, but returns the value and raises on error.

# `add_init_script`

```elixir
@spec add_init_script(
  t(),
  String.t()
  | %{optional(:path) =&gt; String.t(), optional(:content) =&gt; String.t()},
  term() | nil,
  add_init_script_options()
) :: {:ok, Playwright.Disposable.t()} | {:error, Playwright.error()}
```

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. In this case, the script is
  evaluated in the context of the newly attached frame.

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

**Usage**

An example of overriding `Math.random` before the page loads:

```js
// preload.js
Math.random = () => 42;
```

```elixir
# In your playwright script, assuming the preload.js file is in same directory.
BrowserContext.add_init_script!(browser_context, %{path: "preload.js"})
```

> #### Note {: .info}
>
> The order of evaluation of multiple scripts installed via `Playwright.BrowserContext.add_init_script/4` and
> `Playwright.Page.add_init_script/4` is not defined.

*Since Playwright 1.8.*

## Arguments

* `script` - Script to be evaluated in all pages in the browser context.
  * `:path` - Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the
    current working directory. Optional.
  * `:content` - Raw script content. Optional.
* `arg` - Optional argument to pass to `script` (only supported when passing a function).

## Options

* `:expose_functions` (`t:boolean/0`) - *Since Playwright 1.62.* When set to `true`, functions passed inside `arg` are exposed in the page and can be called from the init script. Calling one returns a `Promise` of its result. Under the hood, each function is exposed via `Playwright.Page.expose_function/3`, so it is technically accessible from all frames of the page. Unlike functions passed to `Playwright.Page.evaluate/4`, functions passed to an init script are exposed in every new document, so they survive navigations. Defaults to `false`, in which case functions are not serializable and are silently dropped.

# `add_init_script!`

```elixir
@spec add_init_script!(
  t(),
  String.t()
  | %{optional(:path) =&gt; String.t(), optional(:content) =&gt; String.t()},
  term() | nil,
  add_init_script_options()
) :: Playwright.Disposable.t()
```

Like `add_init_script/4`, but returns the value and raises on error.

# `background_pages`

> This function is deprecated. Background pages have been removed from Chromium together with Manifest V2 extensions.

```elixir
@spec background_pages(t()) :: [Playwright.Page.t()]
```

Returns an empty list.

*Since Playwright 1.11.*

# `browser`

```elixir
@spec browser(t()) :: nil | Playwright.Browser.t()
```

Gets the browser instance that owns the context. Returns `nil` if the context is created outside of normal browser, e.g. Android or Electron.

*Since Playwright 1.8.*

# `clear_cookies`

```elixir
@spec clear_cookies(t(), clear_cookies_options()) ::
  :ok | {:error, Playwright.error()}
```

Removes cookies from context. Accepts optional filter.

**Usage**

```elixir
BrowserContext.clear_cookies!(context)
BrowserContext.clear_cookies!(context, name: "session-id")
BrowserContext.clear_cookies!(context, domain: "my-origin.com")
BrowserContext.clear_cookies!(context, domain: ~r/.*my-origin\.com/)
BrowserContext.clear_cookies!(context, path: "/api/v1")
BrowserContext.clear_cookies!(context, name: "session-id", domain: "my-origin.com")
```

*Since Playwright 1.8.*

## Options

* `:domain` (`t:String.t/0` | `t:Regex.t/0` | `t:Playwright.RegExp.t/0`) - *Since Playwright 1.43.* Only removes cookies with the given domain.
* `:name` (`t:String.t/0` | `t:Regex.t/0` | `t:Playwright.RegExp.t/0`) - *Since Playwright 1.43.* Only removes cookies with the given name.
* `:path` (`t:String.t/0` | `t:Regex.t/0` | `t:Playwright.RegExp.t/0`) - *Since Playwright 1.43.* Only removes cookies with the given path.

# `clear_cookies!`

```elixir
@spec clear_cookies!(t(), clear_cookies_options()) :: :ok
```

Like `clear_cookies/2`, but returns the value and raises on error.

# `clear_permissions`

```elixir
@spec clear_permissions(t()) :: :ok | {:error, Playwright.error()}
```

Clears all permission overrides for the browser context.

**Usage**

```elixir
context = Browser.new_context!(browser)
BrowserContext.grant_permissions!(context, ["clipboard-read"])
# do stuff ..
BrowserContext.clear_permissions(context)
```

*Since Playwright 1.8.*

# `clear_permissions!`

```elixir
@spec clear_permissions!(t()) :: :ok
```

Like `clear_permissions/1`, but returns the value and raises on error.

# `clock`

```elixir
@spec clock(t()) :: Playwright.Clock.t()
```

Playwright has ability to mock clock and passage of time.

*Since Playwright 1.45.*

# `close`

```elixir
@spec close(t(), close_options()) :: :ok | {:error, Playwright.error()}
```

Closes the browser context. All the pages that belong to the browser context will be closed.

> #### Note {: .info}
>
> The default browser context cannot be closed.

*Since Playwright 1.8.*

## Options

* `:reason` (`t:String.t/0`) - *Since Playwright 1.40.* The reason to be reported to the operations interrupted by the context closure.

# `close!`

```elixir
@spec close!(t(), close_options()) :: :ok
```

Like `close/2`, but returns the value and raises on error.

# `cookies`

```elixir
@spec cookies(t(), String.t() | [String.t()] | nil) ::
  {:ok,
   [
     %{
       :name =&gt; String.t(),
       :value =&gt; String.t(),
       :domain =&gt; String.t(),
       :path =&gt; String.t(),
       :expires =&gt; number(),
       :httpOnly =&gt; boolean(),
       :secure =&gt; boolean(),
       :sameSite =&gt; String.t(),
       optional(:partitionKey) =&gt; String.t()
     }
   ]}
  | {:error, Playwright.error()}
```

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs
are returned.

*Since Playwright 1.8.*

## Arguments

* `urls` - Optional list of URLs.

# `cookies!`

```elixir
@spec cookies!(t(), String.t() | [String.t()] | nil) :: [
  %{
    :name =&gt; String.t(),
    :value =&gt; String.t(),
    :domain =&gt; String.t(),
    :path =&gt; String.t(),
    :expires =&gt; number(),
    :httpOnly =&gt; boolean(),
    :secure =&gt; boolean(),
    :sameSite =&gt; String.t(),
    optional(:partitionKey) =&gt; String.t()
  }
]
```

Like `cookies/2`, but returns the value and raises on error.

# `credentials`

```elixir
@spec credentials(t()) :: Playwright.Credentials.t()
```

Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept
`navigator.credentials.create()` / `navigator.credentials.get()` ceremonies.

*Since Playwright 1.61.*

# `debugger`

```elixir
@spec debugger(t()) :: Playwright.Debugger.t()
```

Debugger allows to pause and resume the execution.

*Since Playwright 1.59.*

# `expect_console_message`

```elixir
@spec expect_console_message(
  t(),
  (-&gt; term()),
  expect_console_message_options() | fun()
) ::
  {:ok, Playwright.ConsoleMessage.t()} | {:error, Playwright.error()}
```

Performs action and waits for a [`ConsoleMessage`](`Playwright.ConsoleMessage`) to be logged by in the pages in the context. If predicate is provided, it passes
[`ConsoleMessage`](`Playwright.ConsoleMessage`) value into the `:predicate` function and waits for `predicate(message)` to return a truthy value.
Will fail if the page is closed before the [`BrowserContext.on(:console)`](Playwright.BrowserContext.html#module-console) event is fired.

*Since Playwright 1.34.*

## Arguments

* `action` - A function that performs the action triggering the wait. It runs once the wait is set up; its result is ignored and what it raises propagates.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`(Playwright.ConsoleMessage.t() -> boolean())`) - Receives the [`ConsoleMessage`](`Playwright.ConsoleMessage`) object and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed by using the `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

# `expect_console_message!`

```elixir
@spec expect_console_message!(
  t(),
  (-&gt; term()),
  expect_console_message_options() | fun()
) ::
  Playwright.ConsoleMessage.t()
```

Like `expect_console_message/3`, but returns the value and raises on error.

# `expect_event`

```elixir
@spec expect_event(
  t(),
  event() | String.t(),
  (-&gt; term()),
  expect_event_options() | fun()
) ::
  {:ok, term()} | {:error, Playwright.error()}
```

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
value. Will fail if the context closes before the event is fired. Returns the event data value.

**Usage**

```elixir
page_promise = BrowserContext.wait_for_event(context, :page)
Page.get_by_role(page, :button) |> Locator.click!()
page = Promise.await!(page_promise)
```

*Since Playwright 1.8.*

## Arguments

* `event` - Event name, same one would pass into `Playwright.BrowserContext.on/3`.
* `action` - A function that performs the action triggering the wait. It runs once the wait is set up; its result is ignored and what it raises propagates.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`t:fun/0`) - Receives the event data and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed by using the `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

# `expect_event!`

```elixir
@spec expect_event!(
  t(),
  event() | String.t(),
  (-&gt; term()),
  expect_event_options() | fun()
) :: term()
```

Like `expect_event/4`, but returns the value and raises on error.

# `expect_page`

```elixir
@spec expect_page(t(), (-&gt; term()), expect_page_options() | fun()) ::
  {:ok, Playwright.Page.t()} | {:error, Playwright.error()}
```

Performs action and waits for a new [`Page`](`Playwright.Page`) to be created in the context. If predicate is provided, it passes
[`Page`](`Playwright.Page`) value into the `:predicate` function and waits for `predicate(event)` to return a truthy value.
Will fail if the context closes before new [`Page`](`Playwright.Page`) is created.

*Since Playwright 1.9.*

## Arguments

* `action` - A function that performs the action triggering the wait. It runs once the wait is set up; its result is ignored and what it raises propagates.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`(Playwright.Page.t() -> boolean())`) - Receives the [`Page`](`Playwright.Page`) object and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed by using the `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

# `expect_page!`

```elixir
@spec expect_page!(t(), (-&gt; term()), expect_page_options() | fun()) ::
  Playwright.Page.t()
```

Like `expect_page/3`, but returns the value and raises on error.

# `expose_binding`

```elixir
@spec expose_binding(t(), String.t(), fun()) ::
  {:ok, Playwright.Disposable.t()} | {:error, Playwright.error()}
```

The method adds a function called `name` on the `window` object of every frame in every page in the context.
When called, the function executes `callback` and returns a `Promise` which resolves to the return value of
`callback`. If `callback` returns a `Playwright.Promise`, it is awaited.

The first argument of the `callback` function contains information about the caller: `{ browserContext:
BrowserContext, page: Page, frame: Frame }`.

See `Playwright.Page.expose_binding/3` for page-only version.

**Usage**

An example of exposing page URL to all frames in all pages in the context:

```elixir
# Or Playwright.chromium/1 or Playwright.firefox/1.
browser = BrowserType.launch!(Playwright.webkit(playwright))
context = Browser.new_context!(browser)
BrowserContext.expose_binding!(context, "pageURL", fn %{page: page} -> Page.url(page) end)
page = BrowserContext.new_page!(context)

Page.set_content!(page, """
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.pageURL();
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")

Page.get_by_role(page, :button) |> Locator.click!()
```

*Since Playwright 1.8.*

## Arguments

* `name` - Name of the function on the window object.
* `callback` - Callback function that will be called in the Playwright's context.

# `expose_binding!`

```elixir
@spec expose_binding!(t(), String.t(), fun()) :: Playwright.Disposable.t()
```

Like `expose_binding/3`, but returns the value and raises on error.

# `expose_function`

```elixir
@spec expose_function(t(), String.t(), fun()) ::
  {:ok, Playwright.Disposable.t()} | {:error, Playwright.error()}
```

The method adds a function called `name` on the `window` object of every frame in every page in the context.
When called, the function executes `callback` and returns a `Promise` which resolves to the return value of
`callback`.

If `callback` returns a `Playwright.Promise`, it is awaited.

See `Playwright.Page.expose_function/3` for page-only version.

**Usage**

An example of adding a `sha256` function to all pages in the context:

```elixir
# Or Playwright.chromium/1 or Playwright.firefox/1.
browser = BrowserType.launch!(Playwright.webkit(playwright))
context = Browser.new_context!(browser)

BrowserContext.expose_function!(context, "sha256", fn text ->
  :crypto.hash(:sha256, text) |> Base.encode16(case: :lower)
end)

page = BrowserContext.new_page!(context)

Page.set_content!(page, """
<script>
  async function onClick() {
    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
  }
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")

Page.get_by_role(page, :button) |> Locator.click!()
```

*Since Playwright 1.8.*

## Arguments

* `name` - Name of the function on the window object.
* `callback` - Callback function that will be called in the Playwright's context.

# `expose_function!`

```elixir
@spec expose_function!(t(), String.t(), fun()) :: Playwright.Disposable.t()
```

Like `expose_function/3`, but returns the value and raises on error.

# `grant_permissions`

```elixir
@spec grant_permissions(t(), [String.t()], grant_permissions_options()) ::
  :ok | {:error, Playwright.error()}
```

Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
specified.

*Since Playwright 1.8.*

## Arguments

* `permissions` - A list of permissions to grant.

  > #### Danger {: .error}
  >
  > Supported permissions differ between browsers, and even between different versions of the same browser. Any permission may stop working after an update.

  Here are some permissions that may be supported by some browsers:

  * `'accelerometer'`
  * `'ambient-light-sensor'`
  * `'background-sync'`
  * `'camera'`
  * `'clipboard-read'`
  * `'clipboard-write'`
  * `'geolocation'`
  * `'gyroscope'`
  * `'local-fonts'`
  * `'local-network-access'`
  * `'magnetometer'`
  * `'microphone'`
  * `'midi-sysex'` (system-exclusive midi)
  * `'midi'`
  * `'notifications'`
  * `'payment-handler'`
  * `'storage-access'`
  * `'screen-wake-lock'`

## Options

* `:origin` (`t:String.t/0`) - The [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) to grant permissions to, e.g. "https://example.com".

# `grant_permissions!`

```elixir
@spec grant_permissions!(t(), [String.t()], grant_permissions_options()) :: :ok
```

Like `grant_permissions/3`, but returns the value and raises on error.

# `is_closed`

```elixir
@spec is_closed(t()) :: boolean()
```

Indicates that the browser context is in the process of closing or has already been closed.

*Since Playwright 1.59.*

# `new_cdp_session`

```elixir
@spec new_cdp_session(t(), Playwright.Page.t() | Playwright.Frame.t()) ::
  {:ok, Playwright.CDPSession.t()} | {:error, Playwright.error()}
```

> #### Note {: .info}
>
> CDP sessions are only supported on Chromium-based browsers.

Returns the newly created session.

*Since Playwright 1.11.*

## Arguments

* `page` - Target to create new session for. For backwards-compatibility, this parameter is
  named `page`, but it can be a [`Page`](`Playwright.Page`) or [`Frame`](`Playwright.Frame`) type.

# `new_cdp_session!`

```elixir
@spec new_cdp_session!(t(), Playwright.Page.t() | Playwright.Frame.t()) ::
  Playwright.CDPSession.t()
```

Like `new_cdp_session/2`, but returns the value and raises on error.

# `new_page`

```elixir
@spec new_page(t()) :: {:ok, Playwright.Page.t()} | {:error, Playwright.error()}
```

Creates a new page in the browser context.

*Since Playwright 1.8.*

# `new_page!`

```elixir
@spec new_page!(t()) :: Playwright.Page.t()
```

Like `new_page/1`, but returns the value and raises on error.

# `pages`

```elixir
@spec pages(t()) :: [Playwright.Page.t()]
```

Returns all open pages in the context.

*Since Playwright 1.8.*

# `remove_all_listeners`

```elixir
@spec remove_all_listeners(
  t(),
  event() | String.t() | nil,
  remove_all_listeners_options()
) ::
  :ok | {:error, Playwright.error()}
```

Removes all the listeners of the given type (or all registered listeners if no type given).
Allows to wait for running listeners to complete or to ignore subsequent errors from these listeners.

*Since Playwright 1.47.*

## Options

The options may take the place of `event`, which is then `nil`.

* `:behavior` (`:wait` | `:ignore_errors` | `:default`) - Specifies whether to wait for already running listeners and what to do if they raise:

  * `:default` - do not wait for current listener calls (if any) to finish, if the listener raises, it may result in unhandled error
  * `:wait` - wait for current listener calls (if any) to finish
  * `:ignore_errors` - do not wait for current listener calls (if any) to finish, all errors raised by the listeners after removal are silently caught

# `remove_all_listeners!`

```elixir
@spec remove_all_listeners!(
  t(),
  event() | String.t() | nil,
  remove_all_listeners_options()
) :: :ok
```

Like `remove_all_listeners/3`, but returns the value and raises on error.

# `request`

```elixir
@spec request(t()) :: Playwright.APIRequestContext.t()
```

API testing helper associated with this context. Requests made with this API will use context cookies.

*Since Playwright 1.16.*

# `route`

```elixir
@spec route(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.Route.t() -&gt; term())
  | (Playwright.Route.t(), Playwright.Request.t() -&gt; term()),
  route_options()
) :: {:ok, Playwright.Disposable.t()} | {:error, Playwright.error()}
```

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route
is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

> #### Note {: .info}
>
> `Playwright.BrowserContext.route/4` will not intercept requests intercepted by Service Worker. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting `:service_workers` to `:block`.

**Usage**

An example of a naive handler that aborts all image requests:

```elixir
context = Browser.new_context!(browser)
BrowserContext.route!(context, "**/*.{png,jpg,jpeg}", &Route.abort!/1)
page = BrowserContext.new_page!(context)
Page.goto!(page, "https://example.com")
Browser.close!(browser)
```

or the same snippet using a regex pattern instead:

```elixir
context = Browser.new_context!(browser)
BrowserContext.route!(context, ~r/(\.png$)|(\.jpg$)/, &Route.abort!/1)
page = BrowserContext.new_page!(context)
Page.goto!(page, "https://example.com")
Browser.close!(browser)
```

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

```elixir
BrowserContext.route!(context, "/api/**", fn route ->
  if Route.request(route) |> Request.post_data() |> String.contains?("my-string") do
    Route.fulfill!(route, body: "mocked-data")
  else
    Route.continue!(route)
  end
end)
```

Page routes (set up with `Playwright.Page.route/4`) take precedence over browser context routes when request matches both
handlers.

To remove a route with its handler you can use `Playwright.BrowserContext.unroute/3`.

> #### Note {: .info}
>
> Enabling routing disables http cache.

*Since Playwright 1.8.*

## Arguments

* `url` - A glob pattern, regex pattern, URL pattern, or predicate that receives a `URI` to match during routing. If `:base_url` is set in the context options and the provided URL is a string that does not start with `*`, it is resolved using the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
* `handler` - handler function to route the request.

## Options

* `:times` (`t:integer/0`) - *Since Playwright 1.15.* How often a route should be used. By default it will be used every time.

# `route!`

```elixir
@spec route!(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.Route.t() -&gt; term())
  | (Playwright.Route.t(), Playwright.Request.t() -&gt; term()),
  route_options()
) :: Playwright.Disposable.t()
```

Like `route/4`, but returns the value and raises on error.

# `route_from_har`

```elixir
@spec route_from_har(t(), String.t(), route_from_har_options()) ::
  :ok | {:error, Playwright.error()}
```

If specified the network requests that are made in the context will be served from the HAR file. Read more about [Replaying from HAR](https://playwright.dev/docs/mock#replaying-from-har).

Playwright will not serve requests intercepted by Service Worker from the HAR file. See [this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting `:service_workers` to `:block`.

*Since Playwright 1.23.*

## Arguments

* `har` - Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a relative path, then it is resolved relative to the current working directory.

## Options

* `:not_found` (`:abort` | `:fallback`)

  * If set to 'abort' any request not found in the HAR file will be aborted.
  * If set to 'fallback' falls through to the next route handler in the handler chain.

  Defaults to abort.
* `:update` (`t:boolean/0`) - If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when `Playwright.BrowserContext.close/2` is called.
* `:update_content` (`:embed` | `:attach`) - *Since Playwright 1.32.* Optional setting to control resource content management. If `attach` is specified, resources are persisted as separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
* `:update_mode` (`:full` | `:minimal`) - *Since Playwright 1.32.* When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to `:minimal`.
* `:url` (`t:String.t/0` | `t:Regex.t/0` | `t:Playwright.RegExp.t/0`) - A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.

# `route_from_har!`

```elixir
@spec route_from_har!(t(), String.t(), route_from_har_options()) :: :ok
```

Like `route_from_har/3`, but returns the value and raises on error.

# `route_web_socket`

```elixir
@spec route_web_socket(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.WebSocketRoute.t() -&gt; term())
) :: :ok | {:error, Playwright.error()}
```

This method allows to modify websocket connections that are made by any page in the browser context.

Note that only [`WebSocket`](`Playwright.WebSocket`)s created after this method was called will be routed. It is recommended to call this method before creating any pages.

**Usage**

Below is an example of a simple handler that blocks some websocket messages.
See [`WebSocketRoute`](`Playwright.WebSocketRoute`) for more details and examples.

```elixir
BrowserContext.route_web_socket!(context, "/ws", fn ws ->
  server = WebSocketRoute.connect_to_server(ws)

  WebSocketRoute.on_message(ws, fn message ->
    if message != "to-be-blocked", do: WebSocketRoute.send(server, message)
  end)
end)
```

*Since Playwright 1.48.*

## Arguments

* `url` - Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the `:base_url` context option.
* `handler` - Handler function to route the WebSocket.

# `route_web_socket!`

```elixir
@spec route_web_socket!(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.WebSocketRoute.t() -&gt; term())
) :: :ok
```

Like `route_web_socket/3`, but returns the value and raises on error.

# `service_workers`

```elixir
@spec service_workers(t()) :: [Playwright.Worker.t()]
```

> #### Note {: .info}
>
> Service workers are only supported on Chromium-based browsers.

All existing service workers in the context.

*Since Playwright 1.11.*

# `set_default_navigation_timeout`

```elixir
@spec set_default_navigation_timeout(t(), number() | :infinity) :: :ok
```

This setting will change the default maximum navigation time for the following methods and related shortcuts:

* `Playwright.Page.go_back/2`
* `Playwright.Page.go_forward/2`
* `Playwright.Page.goto/3`
* `Playwright.Page.reload/2`
* `Playwright.Page.set_content/3`
* `Playwright.Page.wait_for_navigation/2`

> #### Note {: .info}
>
> `Playwright.Page.set_default_navigation_timeout/2` and `Playwright.Page.set_default_timeout/2` take priority over
> `Playwright.BrowserContext.set_default_navigation_timeout/2`.

*Since Playwright 1.8.*

## Arguments

* `timeout` - Maximum navigation time in milliseconds

  In Elixir, `:infinity` is the same as `0`: no timeout.

# `set_default_timeout`

```elixir
@spec set_default_timeout(t(), number() | :infinity) :: :ok
```

This setting will change the default maximum time for all the methods accepting `timeout` option.

> #### Note {: .info}
>
> `Playwright.Page.set_default_navigation_timeout/2`, `Playwright.Page.set_default_timeout/2` and
> `Playwright.BrowserContext.set_default_navigation_timeout/2` take priority over `Playwright.BrowserContext.set_default_timeout/2`.

*Since Playwright 1.8.*

## Arguments

* `timeout` - Maximum time in milliseconds. Pass `0` to disable timeout.

  In Elixir, `:infinity` is the same as `0`: no timeout.

# `set_extra_http_headers`

```elixir
@spec set_extra_http_headers(t(), %{optional(String.t()) =&gt; String.t()}) ::
  :ok | {:error, Playwright.error()}
```

The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged
with page-specific extra HTTP headers set with `Playwright.Page.set_extra_http_headers/2`. If page overrides a particular
header, page-specific header value will be used instead of the browser context header value.

> #### Note {: .info}
>
> `Playwright.BrowserContext.set_extra_http_headers/2` does not guarantee the order of headers in the outgoing requests.

*Since Playwright 1.8.*

## Arguments

* `headers` - An object containing additional HTTP headers to be sent with every request. All header values must be strings.

# `set_extra_http_headers!`

```elixir
@spec set_extra_http_headers!(t(), %{optional(String.t()) =&gt; String.t()}) :: :ok
```

Like `set_extra_http_headers/2`, but returns the value and raises on error.

# `set_geolocation`

```elixir
@spec set_geolocation(
  t(),
  :null
  | %{
      :latitude =&gt; number(),
      :longitude =&gt; number(),
      optional(:accuracy) =&gt; number()
    }
) :: :ok | {:error, Playwright.error()}
```

Sets the context's geolocation. Passing `:null` emulates position unavailable.

**Usage**

```elixir
BrowserContext.set_geolocation!(browser_context, %{latitude: 59.95, longitude: 30.31667})
```

> #### Note {: .info}
>
> Consider using `Playwright.BrowserContext.grant_permissions/3` to grant permissions for the browser context pages to read
> its geolocation.

*Since Playwright 1.8.*

## Arguments

* `geolocation`
  * `:latitude` - Latitude between -90 and 90.
  * `:longitude` - Longitude between -180 and 180.
  * `:accuracy` - Non-negative accuracy value. Defaults to `0`.

# `set_geolocation!`

```elixir
@spec set_geolocation!(
  t(),
  :null
  | %{
      :latitude =&gt; number(),
      :longitude =&gt; number(),
      optional(:accuracy) =&gt; number()
    }
) :: :ok
```

Like `set_geolocation/2`, but returns the value and raises on error.

# `set_http_credentials`

```elixir
@spec set_http_credentials(
  t(),
  :null
  | %{
      :username =&gt; String.t(),
      :password =&gt; String.t(),
      optional(:origin) =&gt; String.t()
    }
  | [
      %{
        :username =&gt; String.t(),
        :password =&gt; String.t(),
        optional(:origin) =&gt; String.t()
      }
    ]
) :: :ok | {:error, Playwright.error()}
```

Sets the credentials for HTTP authentication for this browser context.

> #### Note {: .info}
>
> Browsers may cache credentials per origin after a successful authentication, so changing credentials for an origin that has already been authenticated may have no effect.

*Since Playwright 1.8.*

## Arguments

* `http_credentials` - Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request.
  * `:username`
  * `:password`
  * `:origin` - Restrain sending http credentials on specific origin (scheme://host:port).

# `set_http_credentials!`

```elixir
@spec set_http_credentials!(
  t(),
  :null
  | %{
      :username =&gt; String.t(),
      :password =&gt; String.t(),
      optional(:origin) =&gt; String.t()
    }
  | [
      %{
        :username =&gt; String.t(),
        :password =&gt; String.t(),
        optional(:origin) =&gt; String.t()
      }
    ]
) :: :ok
```

Like `set_http_credentials/2`, but returns the value and raises on error.

# `set_offline`

```elixir
@spec set_offline(t(), boolean()) :: :ok | {:error, Playwright.error()}
```

*Since Playwright 1.8.*

## Arguments

* `offline` - Whether to emulate network being offline for the browser context.

  > #### Note {: .info}
  >
  > Offline emulation only affects requests that go through the browser's regular network stack, such as page navigations, `fetch()`, `XMLHttpRequest` and WebSockets. It does not affect WebRTC traffic: established `RTCPeerConnection`s keep sending and receiving media over UDP. To test WebRTC connection loss, interrupt the connection outside the browser, for example by stopping the TURN server or using an OS-level firewall.

# `set_offline!`

```elixir
@spec set_offline!(t(), boolean()) :: :ok
```

Like `set_offline/2`, but returns the value and raises on error.

# `set_storage_state`

```elixir
@spec set_storage_state(t(), String.t() | map()) :: :ok | {:error, Playwright.error()}
```

Clears the existing cookies, local storage, IndexedDB entries, origin private file system entries and virtual WebAuthn credentials, and sets the new storage
state. When the storage state contains credentials, the virtual WebAuthn authenticator is installed (equivalent to
`Playwright.Credentials.install/1`), preventing all real authenticators from working in this context.

**Usage**

```elixir
# Load storage state from a file and apply it to the context.
BrowserContext.set_storage_state!(context, "state.json")
```

*Since Playwright 1.59.*

## Arguments

* `storage_state` - Learn more about [storage state and auth](https://playwright.dev/docs/auth).

  Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via `Playwright.BrowserContext.storage_state/2`.

  * `:cookies` - Cookies to set for context
    * `:name`
    * `:value`
    * `:domain` - Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"
    * `:path` - Domain and path are required
    * `:expires` - Unix time in seconds.
    * `:httpOnly`
    * `:secure`
    * `:sameSite` - sameSite flag
  * `:origins`
    * `:origin`
    * `:localStorage` - localStorage to set for context
      * `:name`
      * `:value`

# `set_storage_state!`

```elixir
@spec set_storage_state!(t(), String.t() | map()) :: :ok
```

Like `set_storage_state/2`, but returns the value and raises on error.

# `storage_state`

```elixir
@spec storage_state(t(), storage_state_options()) ::
  {:ok,
   %{
     :cookies =&gt; [
       %{
         :name =&gt; String.t(),
         :value =&gt; String.t(),
         :domain =&gt; String.t(),
         :path =&gt; String.t(),
         :expires =&gt; number(),
         :httpOnly =&gt; boolean(),
         :secure =&gt; boolean(),
         :sameSite =&gt; String.t(),
         optional(atom()) =&gt; term()
       }
     ],
     :origins =&gt; [
       %{
         :origin =&gt; String.t(),
         :localStorage =&gt; [
           %{
             :name =&gt; String.t(),
             :value =&gt; String.t(),
             optional(atom()) =&gt; term()
           }
         ],
         optional(atom()) =&gt; term()
       }
     ],
     optional(atom()) =&gt; term()
   }}
  | {:error, Playwright.error()}
```

Returns storage state for this browser context, contains current cookies, local storage snapshot, IndexedDB snapshot, origin private file system snapshot and virtual WebAuthn credentials.

*Since Playwright 1.8.*

## Options

* `:credentials` (`t:boolean/0`) - *Since Playwright 1.62.* Set to `true` to include the context's virtual WebAuthn `Playwright.BrowserContext.credentials/1` (passkeys) in the storage
  state snapshot. The captured credentials carry their private keys and signature counters, so they can be re-seeded into a later context via the
  `:storage_state` option or `Playwright.BrowserContext.set_storage_state/2`.
  Note that restoring the storage state that contains credentials will automatically install the virtual WebAuthn authenticator (see `Playwright.Credentials.install/1`), and prevent all real authenticators from working in this context.
* `:indexed_db` (`t:boolean/0`) - *Since Playwright 1.51.* Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage state snapshot.
  If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this.
* `:opfs` (`t:boolean/0`) - *Since Playwright 1.63.* Set to `true` to include the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system)
  in the storage state snapshot.

  > #### Note {: .info}
  >
  > OPFS is currently not supported in ephemeral WebKit contexts.
* `:path` (`t:String.t/0`) - The file path to save the storage state to. If `:path` is a relative path, then it is resolved relative to
  current working directory. If no path is provided, storage
  state is still returned, but won't be saved to the disk.

# `storage_state!`

```elixir
@spec storage_state!(t(), storage_state_options()) :: %{
  :cookies =&gt; [
    %{
      :name =&gt; String.t(),
      :value =&gt; String.t(),
      :domain =&gt; String.t(),
      :path =&gt; String.t(),
      :expires =&gt; number(),
      :httpOnly =&gt; boolean(),
      :secure =&gt; boolean(),
      :sameSite =&gt; String.t(),
      optional(atom()) =&gt; term()
    }
  ],
  :origins =&gt; [
    %{
      :origin =&gt; String.t(),
      :localStorage =&gt; [
        %{:name =&gt; String.t(), :value =&gt; String.t(), optional(atom()) =&gt; term()}
      ],
      optional(atom()) =&gt; term()
    }
  ],
  optional(atom()) =&gt; term()
}
```

Like `storage_state/2`, but returns the value and raises on error.

# `tracing`

```elixir
@spec tracing(t()) :: Playwright.Tracing.t()
```

*Since Playwright 1.12.*

# `unroute`

```elixir
@spec unroute(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.Route.t() -&gt; term())
  | (Playwright.Route.t(), Playwright.Request.t() -&gt; term())
  | nil
) :: :ok | {:error, Playwright.error()}
```

Removes a route created with `Playwright.BrowserContext.route/4`. When `handler` is not specified, removes all
routes for the `url`.

*Since Playwright 1.8.*

## Arguments

* `url` - A glob pattern, regex pattern, URL pattern, or predicate receiving `URI` used to register a routing with
  `Playwright.BrowserContext.route/4`.
* `handler` - Optional handler function used to register a routing with `Playwright.BrowserContext.route/4`.

# `unroute!`

```elixir
@spec unroute!(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -&gt; boolean()),
  (Playwright.Route.t() -&gt; term())
  | (Playwright.Route.t(), Playwright.Request.t() -&gt; term())
  | nil
) :: :ok
```

Like `unroute/3`, but returns the value and raises on error.

# `unroute_all`

```elixir
@spec unroute_all(t(), unroute_all_options()) :: :ok | {:error, Playwright.error()}
```

Removes all routes created with `Playwright.BrowserContext.route/4` and `Playwright.BrowserContext.route_from_har/3`.

*Since Playwright 1.41.*

## Options

* `:behavior` (`:wait` | `:ignore_errors` | `:default`) - Specifies whether to wait for already running handlers and what to do if they raise:

  * `:default` - do not wait for current handler calls (if any) to finish, if unrouted handler raises, it may result in unhandled error
  * `:wait` - wait for current handler calls (if any) to finish
  * `:ignore_errors` - do not wait for current handler calls (if any) to finish, all errors raised by the handlers after unrouting are silently caught

# `unroute_all!`

```elixir
@spec unroute_all!(t(), unroute_all_options()) :: :ok
```

Like `unroute_all/2`, but returns the value and raises on error.

# `wait_for_event`

```elixir
@spec wait_for_event(t(), event() | String.t(), wait_for_event_options() | fun()) ::
  Playwright.Promise.t()
```

Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy
value. Will fail if the context closes before the event is fired. Returns the event data value.

**Usage**

```elixir
page_promise = BrowserContext.wait_for_event(context, :page)
Page.get_by_role(page, :button) |> Locator.click!()
page = Promise.await!(page_promise)
```

*Since Playwright 1.8.*

## Arguments

* `event` - Event name, same one would pass into `Playwright.BrowserContext.on/3`.

## Options

A function in place of the options is the `:predicate` option.

* `:predicate` (`t:fun/0`) - Receives the event data and returns a truthy value when the waiting should resolve.
* `:timeout` (`t:number/0` | `:infinity`) - Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
  The default value can be changed by using the `Playwright.BrowserContext.set_default_timeout/2`.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the waiting using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the waiting will be aborted and the operation will fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).

Returns a `Playwright.Promise` at once, with the wait already set up. Start it before the action that triggers it and await it after with `Playwright.Promise.await/1`:

```elixir
promise = Playwright.BrowserContext.wait_for_event(browser_context, event)
Playwright.Locator.click!(button)
value = Playwright.Promise.await!(promise)
```

The callback form `expect_event/4` runs the action:

```elixir
value = Playwright.BrowserContext.expect_event!(browser_context, event, fn -> Playwright.Locator.click!(button) end)
```

# `wait_for_event!`

```elixir
@spec wait_for_event!(t(), event() | String.t(), wait_for_event_options() | fun()) ::
  term()
```

Like `wait_for_event/3`, but awaits the promise: `Playwright.Promise.await!(wait_for_event(...))`, the value or a raise.

> #### Start waiting before the action {: .warning}
>
> This waits from the time it is called, so it misses what the code before it triggered. Start the wait with `wait_for_event/3` before the action and await it after, or use the callback form `expect_event!/4`:
>
> ```elixir
> promise = Playwright.BrowserContext.wait_for_event(browser_context, event)
> Playwright.Locator.click!(button)
> value = Playwright.Promise.await!(promise)
> ```
>
> ```elixir
> value = Playwright.BrowserContext.expect_event!(browser_context, event, fn -> Playwright.Locator.click!(button) end)
> ```

# `add_listener`

```elixir
@spec add_listener(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec add_listener(t(), :close, (t() -&gt; term())) :: t()
@spec add_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec add_listener(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec add_listener(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec add_listener(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec add_listener(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec add_listener(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec add_listener(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec add_listener(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec add_listener(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec add_listener(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec add_listener(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec add_listener(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec add_listener(t(), :request_failed, (Playwright.Request.t() -&gt; term())) :: t()
@spec add_listener(t(), :request_finished, (Playwright.Request.t() -&gt; term())) :: t()
@spec add_listener(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec add_listener(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec add_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `off`

```elixir
@spec off(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec off(t(), :close, (t() -&gt; term())) :: t()
@spec off(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec off(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec off(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec off(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec off(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec off(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec off(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec off(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec off(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec off(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec off(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec off(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec off(t(), :request_failed, (Playwright.Request.t() -&gt; term())) :: t()
@spec off(t(), :request_finished, (Playwright.Request.t() -&gt; term())) :: t()
@spec off(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec off(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec off(t(), String.t(), (term() -&gt; term())) :: t()
```

Removes an event listener added by `on/3` or `add_listener/3`.

# `on`

```elixir
@spec on(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec on(t(), :close, (t() -&gt; term())) :: t()
@spec on(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec on(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec on(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec on(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec on(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec on(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec on(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec on(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec on(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec on(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec on(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec on(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec on(t(), :request_failed, (Playwright.Request.t() -&gt; term())) :: t()
@spec on(t(), :request_finished, (Playwright.Request.t() -&gt; term())) :: t()
@spec on(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec on(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec on(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `once`

```elixir
@spec once(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec once(t(), :close, (t() -&gt; term())) :: t()
@spec once(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec once(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec once(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec once(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec once(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec once(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec once(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec once(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec once(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec once(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec once(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec once(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec once(t(), :request_failed, (Playwright.Request.t() -&gt; term())) :: t()
@spec once(t(), :request_finished, (Playwright.Request.t() -&gt; term())) :: t()
@spec once(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec once(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec once(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener that is removed after it is triggered once. See `on/3`.

# `prepend_listener`

```elixir
@spec prepend_listener(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :close, (t() -&gt; term())) :: t()
@spec prepend_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) ::
  t()
@spec prepend_listener(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :request_failed, (Playwright.Request.t() -&gt; term())) ::
  t()
@spec prepend_listener(t(), :request_finished, (Playwright.Request.t() -&gt; term())) ::
  t()
@spec prepend_listener(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec prepend_listener(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec prepend_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Adds an event listener for `event`, see the module docs for the events.

# `remove_listener`

```elixir
@spec remove_listener(t(), :background_page, (Playwright.Page.t() -&gt; term())) :: t()
@spec remove_listener(t(), :close, (t() -&gt; term())) :: t()
@spec remove_listener(t(), :console, (Playwright.ConsoleMessage.t() -&gt; term())) :: t()
@spec remove_listener(t(), :dialog, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec remove_listener(t(), :dialog_closed, (Playwright.Dialog.t() -&gt; term())) :: t()
@spec remove_listener(t(), :download, (Playwright.Download.t() -&gt; term())) :: t()
@spec remove_listener(t(), :frame_attached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec remove_listener(t(), :frame_detached, (Playwright.Frame.t() -&gt; term())) :: t()
@spec remove_listener(t(), :frame_navigated, (Playwright.Frame.t() -&gt; term())) :: t()
@spec remove_listener(t(), :page, (Playwright.Page.t() -&gt; term())) :: t()
@spec remove_listener(t(), :page_close, (Playwright.Page.t() -&gt; term())) :: t()
@spec remove_listener(t(), :page_load, (Playwright.Page.t() -&gt; term())) :: t()
@spec remove_listener(t(), :web_error, (Playwright.WebError.t() -&gt; term())) :: t()
@spec remove_listener(t(), :request, (Playwright.Request.t() -&gt; term())) :: t()
@spec remove_listener(t(), :request_failed, (Playwright.Request.t() -&gt; term())) :: t()
@spec remove_listener(t(), :request_finished, (Playwright.Request.t() -&gt; term())) ::
  t()
@spec remove_listener(t(), :response, (Playwright.Response.t() -&gt; term())) :: t()
@spec remove_listener(t(), :service_worker, (Playwright.Worker.t() -&gt; term())) :: t()
@spec remove_listener(t(), String.t(), (term() -&gt; term())) :: t()
```

Removes an event listener added by `on/3` or `add_listener/3`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
