Playwright.BrowserContext (Playwright v1.65.0-rc.3)

Copy Markdown View Source

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.

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

: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 event handler argument.

Usage

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 waiting for the dialog, and actions like click will never finish.

Usage

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

Note

When no Page.on(:dialog) or BrowserContext.on(: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 instance. See also Page.on(: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) 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) 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) 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) 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) respectively instead of similar methods on the Page.

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

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) to receive events about a specific page.

:page_load

Since Playwright 1.60. Emitted when the JavaScript load event is dispatched in any page belonging to this context. See also Page.on(: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) instead.

:request

Since Playwright 1.12. Emitted when a request is issued from any pages created through this context. The Request object is read-only. To only listen for requests from a particular page, use Page.on(: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).

Note

HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with BrowserContext.on(:request_finished) event and not with BrowserContext.on(: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).

:response

Since Playwright 1.12. Emitted when 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).

:service_worker

Since Playwright 1.11.

Note

Service workers are only supported on Chromium-based browsers.

Emitted when new service worker is created in the context.

Summary

Types

Options of add_init_script/4, see its docs.

Options of clear_cookies/2, see its docs.

Options of close/2, see its docs.

An event name, see the module docs.

Options of expect_event/4, see its docs.

Options of expect_page/3, see its docs.

Options of route_from_har/3, see its docs.

Options of route/4, see its docs.

Options of storage_state/2, see its docs.

t()

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

Options of unroute_all/2, see its docs.

Options of wait_for_event/3, see its docs.

Functions

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.

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

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

Returns an empty list.

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

Removes cookies from context. Accepts optional filter.

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

Clears all permission overrides for the browser context.

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

Playwright has ability to mock clock and passage of time.

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

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

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

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

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

Debugger allows to pause and resume the execution.

Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes 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) event is fired.

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.

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

Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes 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 is created.

Like expect_page/3, but returns the value and raises on 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.

Like expose_binding/3, but returns the value and raises on 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.

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

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

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

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

Creates a new page in the browser context.

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

Returns all open pages in the context.

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.

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

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.

Like route/4, but returns the value and raises on 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.

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

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

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

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

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

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.

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

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

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

Sets the credentials for HTTP authentication for this browser context.

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

Like set_offline/2, but returns the value and raises on 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.

Like set_storage_state/2, but returns the value and raises on 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.

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

Since Playwright 1.12.

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

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

Like unroute_all/2, but returns the value and raises on 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.

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

Events

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

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

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

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

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

Types

add_init_script_options()

@type add_init_script_options() ::
  [{:expose_functions, boolean()}] | %{optional(:expose_functions) => boolean()}

Options of add_init_script/4, see its docs.

clear_cookies_options()

@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) => String.t() | Regex.t() | Playwright.RegExp.t(),
      optional(:name) => String.t() | Regex.t() | Playwright.RegExp.t(),
      optional(:path) => String.t() | Regex.t() | Playwright.RegExp.t()
    }

Options of clear_cookies/2, see its docs.

close_options()

@type close_options() :: [{:reason, String.t()}] | %{optional(:reason) => String.t()}

Options of close/2, see its docs.

event()

@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()

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

Options of expect_console_message/3, see its docs.

expect_event_options()

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

Options of expect_event/4, see its docs.

expect_page_options()

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

Options of expect_page/3, see its docs.

grant_permissions_options()

@type grant_permissions_options() ::
  [{:origin, String.t()}] | %{optional(:origin) => String.t()}

Options of grant_permissions/3, see its docs.

remove_all_listeners_options()

@type remove_all_listeners_options() ::
  [{:behavior, :wait | :ignore_errors | :default}]
  | %{optional(:behavior) => :wait | :ignore_errors | :default}

Options of remove_all_listeners/3, see its docs.

route_from_har_options()

@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) => :abort | :fallback,
      optional(:update) => boolean(),
      optional(:update_content) => :embed | :attach,
      optional(:update_mode) => :full | :minimal,
      optional(:url) => String.t() | Regex.t() | Playwright.RegExp.t()
    }

Options of route_from_har/3, see its docs.

route_options()

@type route_options() :: [{:times, integer()}] | %{optional(:times) => integer()}

Options of route/4, see its docs.

storage_state_options()

@type storage_state_options() ::
  [
    credentials: boolean(),
    indexed_db: boolean(),
    opfs: boolean(),
    path: String.t()
  ]
  | %{
      optional(:credentials) => boolean(),
      optional(:indexed_db) => boolean(),
      optional(:opfs) => boolean(),
      optional(:path) => String.t()
    }

Options of storage_state/2, see its docs.

t()

@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()

@type unroute_all_options() ::
  [{:behavior, :wait | :ignore_errors | :default}]
  | %{optional(:behavior) => :wait | :ignore_errors | :default}

Options of unroute_all/2, see its docs.

wait_for_event_options()

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

Options of wait_for_event/3, see its docs.

Functions

add_cookies(browser_context, cookies)

@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

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), the partition key. Optional.

add_cookies!(browser_context, cookies)

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

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

add_init_script(browser_context, script, arg \\ nil, options \\ [])

@spec add_init_script(
  t(),
  String.t()
  | %{optional(:path) => String.t(), optional(:content) => 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:

// preload.js
Math.random = () => 42;
# In your playwright script, assuming the preload.js file is in same directory.
BrowserContext.add_init_script!(browser_context, %{path: "preload.js"})

Note

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 (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!(browser_context, script, arg \\ nil, options \\ [])

@spec add_init_script!(
  t(),
  String.t()
  | %{optional(:path) => String.t(), optional(:content) => 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(browser_context)

This function is deprecated. Background pages have been removed from Chromium together with Manifest V2 extensions.
@spec background_pages(t()) :: [Playwright.Page.t()]

Returns an empty list.

Since Playwright 1.11.

browser(browser_context)

@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(browser_context, options \\ [])

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

Removes cookies from context. Accepts optional filter.

Usage

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

clear_cookies!(browser_context, options \\ [])

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

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

clear_permissions(browser_context)

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

Clears all permission overrides for the browser context.

Usage

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

Since Playwright 1.8.

clear_permissions!(browser_context)

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

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

clock(browser_context)

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

Playwright has ability to mock clock and passage of time.

Since Playwright 1.45.

close(browser_context, options \\ [])

@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

The default browser context cannot be closed.

Since Playwright 1.8.

Options

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

close!(browser_context, options \\ [])

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

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

cookies(browser_context, urls \\ nil)

@spec cookies(t(), String.t() | [String.t()] | nil) ::
  {:ok,
   [
     %{
       :name => String.t(),
       :value => String.t(),
       :domain => String.t(),
       :path => String.t(),
       :expires => number(),
       :httpOnly => boolean(),
       :secure => boolean(),
       :sameSite => String.t(),
       optional(:partitionKey) => 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!(browser_context, urls \\ nil)

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

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

credentials(browser_context)

@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(browser_context)

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

Debugger allows to pause and resume the execution.

Since Playwright 1.59.

expect_console_message(browser_context, action, options \\ [])

@spec expect_console_message(
  t(),
  (-> term()),
  expect_console_message_options() | fun()
) ::
  {:ok, Playwright.ConsoleMessage.t()} | {:error, Playwright.error()}

Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes 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) 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.

expect_console_message!(browser_context, action, options \\ [])

@spec expect_console_message!(
  t(),
  (-> term()),
  expect_console_message_options() | fun()
) ::
  Playwright.ConsoleMessage.t()

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

expect_event(browser_context, event, action, options \\ [])

@spec expect_event(
  t(),
  event() | String.t(),
  (-> 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

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.

expect_event!(browser_context, event, action, options \\ [])

@spec expect_event!(
  t(),
  event() | String.t(),
  (-> term()),
  expect_event_options() | fun()
) :: term()

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

expect_page(browser_context, action, options \\ [])

@spec expect_page(t(), (-> term()), expect_page_options() | fun()) ::
  {:ok, Playwright.Page.t()} | {:error, Playwright.error()}

Performs action and waits for a new Page to be created in the context. If predicate is provided, it passes 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 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.

expect_page!(browser_context, action, options \\ [])

@spec expect_page!(t(), (-> term()), expect_page_options() | fun()) ::
  Playwright.Page.t()

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

expose_binding(browser_context, name, callback)

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

# 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!(browser_context, name, callback)

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

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

expose_function(browser_context, name, callback)

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

# 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!(browser_context, name, callback)

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

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

grant_permissions(browser_context, permissions, options \\ [])

@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

    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

grant_permissions!(browser_context, permissions, options \\ [])

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

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

is_closed(browser_context)

@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(browser_context, page)

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

Note

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 or Frame type.

new_cdp_session!(browser_context, page)

@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(browser_context)

@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!(browser_context)

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

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

pages(browser_context)

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

Returns all open pages in the context.

Since Playwright 1.8.

remove_all_listeners(browser_context, event \\ nil, options \\ [])

@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!(browser_context, event \\ nil, options \\ [])

@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(browser_context)

@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(browser_context, url, handler, options \\ [])

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

Playwright.BrowserContext.route/4 will not intercept requests intercepted by Service Worker. See this 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:

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:

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:

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

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() constructor.
  • handler - handler function to route the request.

Options

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

route!(browser_context, url, handler, options \\ [])

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

route_from_har(browser_context, har, options \\ [])

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

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this 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 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 (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 (String.t/0 | Regex.t/0 | 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!(browser_context, har, options \\ [])

@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(browser_context, url, handler)

@spec route_web_socket(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -> boolean()),
  (Playwright.WebSocketRoute.t() -> 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 WebSockets 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 for more details and examples.

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!(browser_context, url, handler)

@spec route_web_socket!(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -> boolean()),
  (Playwright.WebSocketRoute.t() -> term())
) :: :ok

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

service_workers(browser_context)

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

Note

Service workers are only supported on Chromium-based browsers.

All existing service workers in the context.

Since Playwright 1.11.

set_default_navigation_timeout(browser_context, timeout)

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

Note

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(browser_context, timeout)

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

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

Note

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(browser_context, headers)

@spec set_extra_http_headers(t(), %{optional(String.t()) => 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

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!(browser_context, headers)

@spec set_extra_http_headers!(t(), %{optional(String.t()) => String.t()}) :: :ok

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

set_geolocation(browser_context, geolocation)

@spec set_geolocation(
  t(),
  :null
  | %{
      :latitude => number(),
      :longitude => number(),
      optional(:accuracy) => number()
    }
) :: :ok | {:error, Playwright.error()}

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

Usage

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

Note

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!(browser_context, geolocation)

@spec set_geolocation!(
  t(),
  :null
  | %{
      :latitude => number(),
      :longitude => number(),
      optional(:accuracy) => number()
    }
) :: :ok

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

set_http_credentials(browser_context, http_credentials)

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

Sets the credentials for HTTP authentication for this browser context.

Note

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!(browser_context, http_credentials)

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

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

set_offline(browser_context, offline)

@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

    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 RTCPeerConnections 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!(browser_context, offline)

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

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

set_storage_state(browser_context, storage_state)

@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

# 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.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!(browser_context, storage_state)

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

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

storage_state(browser_context, options \\ [])

@spec storage_state(t(), storage_state_options()) ::
  {:ok,
   %{
     :cookies => [
       %{
         :name => String.t(),
         :value => String.t(),
         :domain => String.t(),
         :path => String.t(),
         :expires => number(),
         :httpOnly => boolean(),
         :secure => boolean(),
         :sameSite => String.t(),
         optional(atom()) => term()
       }
     ],
     :origins => [
       %{
         :origin => String.t(),
         :localStorage => [
           %{
             :name => String.t(),
             :value => String.t(),
             optional(atom()) => term()
           }
         ],
         optional(atom()) => term()
       }
     ],
     optional(atom()) => 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 (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 (boolean/0) - Since Playwright 1.51. Set to true to include IndexedDB in the storage state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this.

  • :opfs (boolean/0) - Since Playwright 1.63. Set to true to include the origin private file system in the storage state snapshot.

    Note

    OPFS is currently not supported in ephemeral WebKit contexts.

  • :path (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!(browser_context, options \\ [])

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

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

tracing(browser_context)

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

Since Playwright 1.12.

unroute(browser_context, url, handler \\ nil)

@spec unroute(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -> boolean()),
  (Playwright.Route.t() -> term())
  | (Playwright.Route.t(), Playwright.Request.t() -> 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

unroute!(browser_context, url, handler \\ nil)

@spec unroute!(
  t(),
  String.t() | Regex.t() | Playwright.RegExp.t() | (URI.t() -> boolean()),
  (Playwright.Route.t() -> term())
  | (Playwright.Route.t(), Playwright.Request.t() -> term())
  | nil
) :: :ok

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

unroute_all(browser_context, options \\ [])

@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!(browser_context, options \\ [])

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

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

wait_for_event(browser_context, event, options \\ [])

@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

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

Options

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

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:

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:

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

wait_for_event!(browser_context, event, options \\ [])

@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

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:

promise = Playwright.BrowserContext.wait_for_event(browser_context, event)
Playwright.Locator.click!(button)
value = Playwright.Promise.await!(promise)
value = Playwright.BrowserContext.expect_event!(browser_context, event, fn -> Playwright.Locator.click!(button) end)

Events

add_listener(browser_context, event, listener)

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

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

off(browser_context, event, listener)

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

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

on(browser_context, event, listener)

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

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

once(browser_context, event, listener)

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

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

prepend_listener(browser_context, event, listener)

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

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

remove_listener(browser_context, event, listener)

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

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