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 aPlaywright.BrowserContext
. This might happen because of any of the following:- Browser context is closed.
- Browser application is closed or crashed.
Playwright.Browser.close/1
is called.Playwright.Page.close/1
is with the "owner page" for this context.
:page
Emitted when a new
Playwright.Page
is created within the context. The page may still be loading. The event target is aPlaywright.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:
- 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).
- Use
: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
orPlaywright.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
.
- HTTP error responses, such as 404 or 503, are still successful
responses from HTTP standpoint. So, the request will complete with
a
: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, usePlaywright.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, usePlaywright.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
%Playwright.BrowserContext{}
A string URL
Functions
Adds cookies into this Playwright.BrowserContext
.
Adds a script to be evaluated before other scripts.
Clears Playwright.BrowserContext
cookies.
Closes the Playwright.BrowserContext
. All pages that belong to the
Playwright.BrowserContext
will be closed.
Returns cookies for the Playwright.BrowserContext
.
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
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
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])
Cookie fields
key | type | description |
---|---|---|
:name | binary() | |
:value | binary() | |
:url | binary() | (optional) either url or domain / path are required |
:domain | binary() | (optional) either url or domain / path are required |
:path | binary() | (optional) either url or domain / path are required |
:expires | float() | (optional) Unix time in seconds. |
:httpOnly | boolean() | (optional) |
:secure | boolean() | (optional) |
:sameSite | binary() | (optional) one of "Strict", "Lax", "None" |
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/name | type | description | |
---|---|---|---|
script | param | binary() 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
andPlaywright.Page.add_init_script/2
is not defined.
@spec clear_cookies(t()) :: :ok
Clears Playwright.BrowserContext
cookies.
@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.
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
[cookie()]
Seeadd_cookies/2
for cookie field details.
Arguments
key/name | type | description | |
---|---|---|---|
urls | param | binary() or [binary()] | List of URLs. (optional) |
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 toPlaywright.BrowserContext.on/3
predicate
: Receives thePlaywright.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 viaPlaywright.BrowserContext.set_default_timeout/2
.
Example
event_info = BrowserContext.expect_event(context, :page, fn ->
BrowserContext.new_page(context)
end)
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 thePlaywright.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 viaPlaywright.BrowserContext.set_default_timeout/2
.
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.
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.
Optional callback implementation for Playwright.SDK.ChannelOwner.init/2
.
If implemented, the callback will receive:
- The newly created "channel owner" struct.
- 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/name | type | description | |
---|---|---|---|
owner | param | struct() | The newly created channel owner (resource). |
initializer | param | struct() | The initializer received from with the channel owner instance was derived. |
@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.
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()]