View Source Playwright.BrowserContext (playwright v1.44.0-alpha.4)

Playwright.BrowserContext provides 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 creation of "incognito" browser contexts with the Playwright.Browser.new_context/1 function.

Example

# create a new "incognito" browser context:
context = Playwright.Browser.new_context(browser)

# create and use a new page within that context:
page = Playwright.BrowserContext.new_page(context)
resp =  = Playwright.Page.goto(page, "https://example.com")

# dispose the context once it's no longer needed:
Playwright.BrowserContext.close(context)

Regarding expect_event/5 and on/3

The first argument given to on/3 and expect_event/5 functions is the "owner" on which to bind the event.

The second argument is the event type.

The third argument is a callback function that will be executed when the event fires, and is passed an instance of Playwright.SDK.Channel.Event.

Details for expect_event/5

Calls to expect_event/5 are blocking. These functions take a "trigger", execution of which is expected to result in the event being fired.

If the event does not fire within the timeout window, the call to expect_event/5 will timeout.

An optional "predicate" function may be provided, in which case the fired event will be sent to the predicate, which must return a "truthy" result in order for the expectation to be fulfilled.

e = BrowserContext.expect_event(context, :close, fn ->
  Page.close(page)
end)
assert %BrowserContext{} = e.target

Details for on/3

Calls to on/3 are non-blocking and register callbacks for the lifetime of the binding target.

BrowserContext.on(context, :close, fn e ->
  assert %BrowserContext{} = e.target
end)

Event types

The expect_event/5 and on/3 functions support the following event types:

  • :background_page

    Emitted when a new background page is created in the context. The event target is a Playwright.Page.

    ...

    NOTE:

    • Only works with Chromium browser's persistent context.
  • :close

    Emitted when the Playwright.BrowserContext is closed. The event target is a Playwright.BrowserContext. This might happen because of any of the following:

  • :page

    Emitted when a new Playwright.Page is created within the context. The page may still be loading. The event target is a Playwright.Page.

    The event will also fire for popup pages.

    The earliest moment that a 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.

    BrowserContext.expect_event(context, :page, fn ->
      Page.click(page, "a[target=_blank]")
    end)

    NOTE:

  • :request

    Emitted when a request is issued from any pages created through this context. The event target is a Playwright.Request.

    To only listen for requests from a particular page, use Playwright.Page.on/3 (for :request).

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

  • :request_failed

    Emitted when a request fails, for example by timing out. The event target is a Playwright.Request.

    To only listen for failed requests from a particular page, use Playwright.Page.on/3 (for :request_failed).

    NOTE:

    • HTTP error responses, such as 404 or 503, are still successful responses from HTTP standpoint. So, the request will complete with a :request_finished event and not with :request_failed.
  • :request_finished

    Emitted when a request finishes successfully after downloading the response body. The event target is a Playwright.Request.

    For a successful response, the sequence of events is :request, :response and :request_finished. To listen for successful requests from a particular page, use Playwright.Page.on/3 (for :request_finished).

  • :response

    Emitted when response status and headers are received for a request. The event target is a Playwright.Response.

    For a successful response, the sequence of events is :request, :response and :request_finished. To listen for response events from a particular page, use Playwright.Page.on/3 (for :response).

  • :service_worker

    Emitted when new service worker is created in the context. The event target is a Playwright.Worker.

    NOTE:

    • Service workers are only supported on Chromium-based browsers.

Summary

Types

Recognized cookie fields

Supported events

An optional (maybe nil) function or option

A map/struct providing call options

t()

%Playwright.BrowserContext{}

A string URL

Functions

Adds a script to be evaluated before other scripts.

Closes the Playwright.BrowserContext. All pages that belong to the Playwright.BrowserContext will be closed.

Waits for an event to fire (i.e., is blocking) and passes its value into the predicate function.

Executes trigger and waits for a new Playwright.Page to be created within the Playwright.BrowserContext.

Adds a function called param:name on the window object of every frame in every page in the context.

Adds a function called param:name on the window object of every frame in every page in the context.

Optional callback implementation for Playwright.SDK.ChannelOwner.init/2.

Creates a new Playwright.Page in the context.

Register a (non-blocking) callback/handler for various types of events.

Returns all open pages in the context.

Types

@type cookie() :: %{
  name: String.t(),
  value: String.t(),
  url: String.t(),
  domain: String.t(),
  path: String.t(),
  expires: float(),
  httpOnly: boolean(),
  secure: boolean(),
  sameSite: String.t()
}

Recognized cookie fields

@type event() ::
  :background_page
  | :close
  | :page
  | :request
  | :request_failed
  | :request_finished
  | :response
  | :service_worker

Supported events

@type function_or_options() :: (... -> any()) | options() | nil

An optional (maybe nil) function or option

@type options() :: map()

A map/struct providing call options

@type t() :: %Playwright.BrowserContext{
  bindings: term(),
  browser: term(),
  guid: term(),
  initializer: term(),
  listeners: term(),
  owner_page: term(),
  parent: term(),
  routes: term(),
  session: term(),
  type: term()
}

%Playwright.BrowserContext{}

@type url() :: String.t()

A string URL

Functions

Link to this function

add_cookies(context, cookies)

View Source
@spec add_cookies(t(), [cookie()]) :: :ok

Adds cookies into this Playwright.BrowserContext.

All pages within this context will have these cookies installed. Cookies can be obtained via Playwright.BrowserContext.cookies/1.

Returns

  • :ok

Example

:ok = BrowserContext.add_cookies(context, [cookie_1, cookie_2])
keytypedescription
:namebinary()
:valuebinary()
:urlbinary()(optional) either url or domain / path are required
:domainbinary()(optional) either url or domain / path are required
:pathbinary()(optional) either url or domain / path are required
:expiresfloat()(optional) Unix time in seconds.
:httpOnlyboolean()(optional)
:secureboolean()(optional)
:sameSitebinary()(optional) one of "Strict", "Lax", "None"
Link to this function

add_init_script(context, script)

View Source
@spec add_init_script(t(), binary() | map()) :: :ok

Adds a script to be evaluated before other scripts.

The script is evaluated in 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 is created but before any of its scripts are run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

Returns

  • :ok

Arguments

key/nametypedescription
scriptparambinary() or map()As binary(): an inlined script to be evaluated; As %{path: path}: a path to a JavaScript file.

Example

Overriding Math.random before the page loads:

# preload.js
Math.random = () => 42;

BrowserContext.add_init_script(context, %{path: "preload.js"})

Notes

While the official Node.js Playwright implementation supports an optional param: arg for this function, the official Python implementation does not. This implementation matches the Python for now.

The order of evaluation of multiple scripts installed via Playwright.BrowserContext.add_init_script/2 and Playwright.Page.add_init_script/2 is not defined.

@spec clear_cookies(t()) :: :ok

Clears Playwright.BrowserContext cookies.

Link to this function

clear_permissions(context)

View Source
@spec clear_permissions(t()) :: :ok
@spec close(t()) :: :ok

Closes the Playwright.BrowserContext. All pages that belong to the Playwright.BrowserContext will be closed.

NOTE:

  • The default browser context cannot be closed.
Link to this function

cookies(context, urls \\ [])

View Source
@spec cookies(t(), url() | [url()]) :: [cookie()]

Returns cookies for the Playwright.BrowserContext.

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

Returns

Arguments

key/nametypedescription
urlsparambinary() or [binary()]List of URLs. (optional)
Link to this function

expect_event(context, event, options \\ %{}, trigger \\ nil)

View Source

Waits for an event to fire (i.e., is blocking) and passes its value into the predicate function.

Returns when the predicate returns a truthy value. Throws an error if the context closes before the event is fired. Returns a Playwright.SDK.Channel.Event.

Arguments

  • event: Event name; the same as those passed to Playwright.BrowserContext.on/3
  • predicate: Receives the Playwright.SDK.Channel.Event and resolves to a "truthy" value when the waiting should resolve.
  • options:
    • predicate: ...
    • timeout: The maximum time to wait in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed via Playwright.BrowserContext.set_default_timeout/2.

Example

event_info = BrowserContext.expect_event(context, :page, fn ->
  BrowserContext.new_page(context)
end)
Link to this function

expect_page(context, options \\ %{}, trigger \\ nil)

View Source

Executes trigger and waits for a new Playwright.Page to be created within the Playwright.BrowserContext.

If predicate is provided, it passes the Playwright.Page value into the predicate function, wrapped in Playwright.SDK.Channel.Event, and waits for predicate/1 to return a "truthy" value. Throws an error if the context closes before new Playwright.Page is created.

Arguments

  • predicate: Receives the Playwright.Page and resolves to truthy value when the waiting should resolve.
  • options:
    • predicate: ...
    • timeout: The maximum time to wait in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed via Playwright.BrowserContext.set_default_timeout/2.
Link to this function

expose_binding(context, name, callback, options \\ %{})

View Source
@spec expose_binding(t(), String.t(), function(), options()) :: t()

Adds a function called param:name on the window object of every frame in every page in the context.

When called, the function executes param:callback and resolves to the return value of the callback.

The first argument to the callback function includes the following details about the caller:

%{
  context: %Playwright.BrowserContext{},
  frame:   %Playwright.Frame{},
  page:    %Playwright.Page{}
}

See Playwright.Page.expose_binding/4 for a similar, page-scoped version.

Link to this function

expose_function(context, name, callback)

View Source
@spec expose_function(t(), String.t(), function()) :: t()

Adds a function called param:name on the window object of every frame in every page in the context.

When called, the function executes param:callback and resolves to the return value of the callback.

See Playwright.Page.expose_function/3 for a similar, Page-scoped version.

Link to this function

grant_permissions(context, permissions, options \\ %{})

View Source
@spec grant_permissions(t(), [String.t()], options()) ::
  :ok | {:error, Playwright.SDK.Channel.Error.t()}
Link to this function

init(owner, initializer)

View Source
@spec init(
  struct(),
  map()
) :: {atom(), struct()}

Optional callback implementation for Playwright.SDK.ChannelOwner.init/2.

If implemented, the callback will receive:

  1. The newly created "channel owner" struct.
  2. The :initializer received from the Playwright browser server.

The implementation has the option of "patching" the struct as stored in the catalog, and/or binding event handlers.

Example

def init(%{session: session} = owner, _initializer) do
  Channel.bind(session, {:guid, owner.guid}, :close, fn event ->
    Logger.warning("Closing #{inspect(event.target)}")
  end)

  {:ok, %{owner | version: "1.2.3"}}
end

Returns

  • {:ok, struct()}

Arguments

key/nametypedescription
ownerparamstruct()The newly created channel owner (resource).
initializerparamstruct()The initializer received from with the channel owner instance was derived.
Link to this function

new_cdp_session(context, owner)

View Source
@spec new_cdp_session(t(), Playwright.Frame.t() | Playwright.Page.t()) ::
  Playwright.CDPSession.t()
@spec new_page(t()) :: Playwright.Page.t()

Creates a new Playwright.Page in the context.

If the context is already "owned" by a Playwright.Page (i.e., was created as a side effect of Playwright.Browser.new_page/1), will raise an error because there should be a 1-to-1 mapping in that case.

Link to this function

on(context, event, callback)

View Source
@spec on(t(), event(), function()) :: :ok

Register a (non-blocking) callback/handler for various types of events.

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

Returns all open pages in the context.

Returns

  • [Page.t()]
Link to this function

route(context, pattern, handler, options \\ %{})

View Source
@spec route(t(), binary(), function(), map()) :: :ok
Link to this function

set_offline(context, offline)

View Source
@spec set_offline(t(), boolean()) :: :ok
Link to this function

unroute(context, pattern, callback \\ nil)

View Source
@spec unroute(t(), binary(), function() | nil) :: :ok