The API is generated from Playwright's docs, so playwright.dev describes every function here, and
the function docs are upstream's. This page shows how a JS call reads in Elixir. The
Python docs are the closest read: their
names, keyword options and expect_* helpers are ours.
Snippets here and in the function docs alias the modules they use:
alias Playwright.{Browser, BrowserContext, Expect, Locator, Page, ...}.
Names
A JS class is a module, a method is a function that takes the object first, and calls chain with pipes:
# await page.getByRole('button', { name: 'Save' }).click();
Page.get_by_role(page, :button, name: "Save") |> Locator.click!()Objects are structs (%Playwright.Page{}, typed Playwright.Page.t()). Names are snakecase.
Where a JS name is no Elixir name, Python's is used: $eval is
Page.eval_on_selector/4, and/or are
[`Locator.and/2](Playwright.Locator.and/2) and [Locator.or/2](Playwright.Locator.or/2),notisnot_to*(see [Assertions](#assertions)). Properties are functions too:page.keyboardisPage.keyboard(page),request.url()isRequest.url(request)`.
Predicates keep Python's names, Locator.is_visible/2 and
Browser.is_connected/1, not visible?: a ? function
returns a plain boolean, and most of these are calls with a tuple and a bang form ({:ok, true} = Locator.is_visible(locator), true = Locator.is_visible!(locator)).
Results: tuple or bang
Each call that JS awaits has two forms. name/n returns {:ok, value} or
{:error, exception} (:ok when JS returns nothing), name!/n returns the value or raises.
exception is one of the errors a JS promise rejects with (Playwright.error/0, see
Errors), including the client's own argument checks (path and content both given),
which JS rejects with too. Anything else raises in both forms: a bug, an exception from your own
handler, or an Elixir-side check such as an unknown option (ArgumentError). The line is JS's, so
a tuple form returns what a JS .catch() would get, and Playwright's docs tell you what a call can
fail with. Calls JS doesn't await (page.url(), page.locator(), locator.filter()) return plain
values.
title = Page.title!(page)
case Page.goto(page, "/admin") do
{:ok, response} -> Response.status(response)
{:error, %Playwright.TimeoutError{}} -> :timeout
endUse the bang forms in scripts and tests, the tuple forms where a failure is an expected outcome.
Where JS docs say a call throws, the function docs say it fails (with a TimeoutError, say):
the tuple form returns the error, the bang form raises it.
The library's own functions, those with no JS counterpart (the runner's Playwright.Test,
Playwright.Test.BrowserPool, Playwright.Driver, Playwright.device/1), are plain Elixir:
one form, without a bang, that takes its options as a keyword list (Test.use/1 and
Test.parameters/1 a map too) and raises on failure. Bad input raises ArgumentError, a call
outside its scope (Playwright.Test.info/0 outside a test) RuntimeError, with a message
<Module.function/arity or config path>: <problem>, expected ..., got: ... when the problem
doesn't name the value. Keys and values read as the facade's errors
(Playwright.Test.use/1: unknown option slow_mo, expected one of trace, ...,
invalid value 0 for workers, expected a positive integer).
Options
The JS options object is the last argument: a keyword list (or a map) with snake_case keys.
# await page.screenshot({ path: 'shot.png', fullPage: true });
Page.screenshot!(page, path: "shot.png", full_page: true)Unknown keys and enum values raise ArgumentError before anything is sent. Nested objects are
maps with the JS keys, the shape results come back in, so a result can be passed back as is.
Header maps have string keys.
context = Browser.new_context!(browser, viewport: %{width: 1280, height: 720})
BrowserContext.add_cookies!(context, [
%{name: "session", value: "abc", url: "https://example.com", sameSite: "Lax"}
])
[%{name: "session", sameSite: "Lax"}] = BrowserContext.cookies!(context)
Page.set_extra_http_headers!(page, %{"x-request-id" => "42"})For no timeout, pass timeout: :infinity
Unlike Elixir's receive ... after 0, timeout: 0 here means no timeout, as in Playwright
JS: it waits forever. Don't use it for an immediate check.
Enums, nil and :null
String enums are atoms, snake_case: 'button' is :button, 'no-preference' is
:no_preference. Event names are atoms the same way: 'requestfailed' is :request_failed,
'websocket' is :web_socket. An unknown atom raises; strings pass as they are
("requestfailed"), unchecked, as JS takes any (an event that never fires: a wait for it times
out). JS undefined is nil, so nil means "not given"; JS null is
:null:
Page.emulate_media!(page, color_scheme: :dark)
# page.emulateMedia({ colorScheme: null }): back to the browser's default
Page.emulate_media!(page, color_scheme: :null)evaluate and json results follow the same rule. A call that returns X | null in JS returns
nil for none: Locator.get_attribute!/2 of a missing attribute, Locator.text_content!/2.
JSON.encode!/1 turns :null into the string "null", so pass such values to the page as an
evaluate argument, which sends :null as null at any depth, and stringify them there if the
page needs JSON:
Page.evaluate!(page, "x => JSON.stringify(x)", %{"z" => :null})
# "{\"z\":null}"Optional arguments
Optional positional arguments stay positional, options come last. The options may take the place of an optional argument before them:
Page.wait_for_load_state!(page, :networkidle)
Page.wait_for_load_state!(page, timeout: 1_000)
Expect.to_have_attribute!(locator, "disabled", timeout: 1_000)Waiting for events: promises and expect_*
JS starts a wait, acts, then awaits the wait. wait_for_* returns a Playwright.Promise for
this, and expect_*, Python's with page.expect_popup(), takes the action as a callback and
exists where Python has one. A predicate, JS waitForEvent(event, predicate), goes in place of the
options or as predicate:. A bang wait_for_*! awaits at once, so it can miss what the code
before it triggered. Events and waiting covers both forms.
# const popupPromise = page.waitForEvent('popup');
# await page.getByText('Open').click();
# const popup = await popupPromise;
promise = Page.wait_for_event(page, :popup)
Page.get_by_text(page, "Open") |> Locator.click!()
popup = Promise.await!(promise)
ready = Page.wait_for_event(page, :console, &(ConsoleMessage.text(&1) == "ready"))Events
on/3, once/3 and off/3 take a listener function, as in JS. A listener runs in a process of its
own and may call Playwright, as a :dialog listener calls
Dialog.accept!/2. The Concurrency guide
covers ordering, blocking listeners and promise lifetimes.
Assertions
expect(x).toY(...) is Expect.to_y(x, ...), and expect(x).not.toY(...) is
Expect.not_to_y(x, ...) or x |> Expect.not_() |> Expect.to_y(...):
# await expect(page.getByText('Saved')).toBeVisible();
Expect.to_be_visible!(Page.get_by_text(page, "Saved"))
# await expect(locator).not.toHaveText('Error');
Expect.not_to_have_text!(locator, "Error")
locator |> Expect.not_() |> Expect.to_have_text!("Error")Matchers retry until they pass or time out (5 seconds, config :playwright, :expect). They
return :ok (to_pass {:ok, value}, its callback's) or {:error, %Playwright.ExpectError{}};
the bang forms raise the Playwright.ExpectError, which fails an ExUnit test as any exception
does. Unknown keys in the :expect config raise ArgumentError.
Errors
Errors are exceptions named after the JS classes: Playwright.PlaywrightError (JS Error),
Playwright.TimeoutError, Playwright.TargetClosedError, Playwright.AbortError and
Playwright.ExpectError. Where the JS client throws a plain new Error(message) itself, it is
a RuntimeError; local file errors are File.Error. Playwright.error/0 lists them all;
Playwright.Promise.any/1 rejects with a Playwright.AggregateError of them.
The message is JS's, starting with the API name, and log holds the call log:
{:error, %TimeoutError{message: "locator.click: Timeout 100ms exceeded" <> _, log: log}} =
Page.locator(page, "#missing") |> Locator.click(timeout: 100)Regular expressions
Where JS takes a RegExp, pass a Regex; it is sent to the browser as a JS regex. Strings are
always literal text (or globs, for URLs), never patterns:
Page.get_by_role(page, :button, name: ~r/submit/i)
Expect.to_have_url!(page, ~r"/dashboard$")PCRE-only syntax JS cannot run (\A, possessive quantifiers, inline (?i), ...) raises
ArgumentError. For JS-only syntax, pass a Playwright.RegExp:
Page.get_by_text(page, Playwright.RegExp.new("a[^]b", "v"))evaluate takes JS source
The script is a JS string: an expression, or a function that gets the optional argument.
Page.evaluate!(page, "document.title")
Page.evaluate!(page, "([a, b]) => a + b", [1, 2])
Page.locator(page, "button") |> Locator.evaluate!("el => el.textContent")Values cross as Elixir terms: JS objects come back as maps with string keys, Date is
DateTime, RegExp is Playwright.RegExp, NaN, Infinity and -Infinity are :nan,
:infinity and :neg_infinity, -0 is -0.0, undefined is nil and null is :null.