Whenever a network route is set up with Playwright.Page.route/4 or Playwright.BrowserContext.route/4, the Route object
allows to handle the route.
Learn more about networking.
Since Playwright 1.8.
The examples alias the modules they use (alias Playwright.{Locator, Page}).
Summary
Types
Options of continue/2, see its docs.
Options of fallback/2, see its docs.
Options of fetch/2, see its docs.
Options of fulfill/2, see its docs.
A Route handle. Compare handles with ==, their fields are internal.
Functions
Aborts the route's request.
Like abort/2, but returns the value and raises on error.
Sends route's request to the network with optional overrides.
Like continue/2, but returns the value and raises on error.
Continues route's request with optional overrides. The method is similar to Playwright.Route.continue/2 with the difference that other matching handlers will be invoked before sending the request.
Like fallback/2, but returns the value and raises on error.
Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.
Like fetch/2, but returns the value and raises on error.
Fulfills route's request with given response.
Like fulfill/2, but returns the value and raises on error.
A request to be routed.
Types
@type continue_options() :: [ headers: %{optional(String.t()) => String.t()}, method: String.t(), post_data: String.t() | {:binary, binary()} | term(), url: String.t() ] | %{ optional(:headers) => %{optional(String.t()) => String.t()}, optional(:method) => String.t(), optional(:post_data) => String.t() | {:binary, binary()} | term(), optional(:url) => String.t() }
Options of continue/2, see its docs.
@type fallback_options() :: [ headers: %{optional(String.t()) => String.t()}, method: String.t(), post_data: String.t() | {:binary, binary()} | term(), url: String.t() ] | %{ optional(:headers) => %{optional(String.t()) => String.t()}, optional(:method) => String.t(), optional(:post_data) => String.t() | {:binary, binary()} | term(), optional(:url) => String.t() }
Options of fallback/2, see its docs.
@type fetch_options() :: [ headers: %{optional(String.t()) => String.t()}, max_redirects: integer(), max_retries: integer(), method: String.t(), post_data: String.t() | {:binary, binary()} | term(), signal: Playwright.AbortSignal.t(), timeout: number() | :infinity, url: String.t() ] | %{ optional(:headers) => %{optional(String.t()) => String.t()}, optional(:max_redirects) => integer(), optional(:max_retries) => integer(), optional(:method) => String.t(), optional(:post_data) => String.t() | {:binary, binary()} | term(), optional(:signal) => Playwright.AbortSignal.t(), optional(:timeout) => number() | :infinity, optional(:url) => String.t() }
Options of fetch/2, see its docs.
@type fulfill_options() :: [ body: String.t() | {:binary, binary()}, content_type: String.t(), headers: %{optional(String.t()) => String.t()}, json: term(), path: String.t(), response: Playwright.APIResponse.t(), status: integer() ] | %{ optional(:body) => String.t() | {:binary, binary()}, optional(:content_type) => String.t(), optional(:headers) => %{optional(String.t()) => String.t()}, optional(:json) => term(), optional(:path) => String.t(), optional(:response) => Playwright.APIResponse.t(), optional(:status) => integer() }
Options of fulfill/2, see its docs.
@type t() :: %Playwright.Route{ conn: term(), guid: term(), initializer: term(), table: term(), type: term() }
A Route handle. Compare handles with ==, their fields are internal.
Functions
@spec abort(t(), String.t() | nil) :: :ok | {:error, Playwright.error()}
Aborts the route's request.
Since Playwright 1.8.
Arguments
error_code- Optional error code. Defaults tofailed, could be one of the following:'aborted'- An operation was aborted (due to user action)'accessdenied'- Permission to access a resource, other than the network, was denied'addressunreachable'- The IP address is unreachable. This usually means that there is no route to the specified host or network.'blockedbyclient'- The client chose to block the request.'blockedbyresponse'- The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).'connectionaborted'- A connection timed out as a result of not receiving an ACK for data sent.'connectionclosed'- A connection was closed (corresponding to a TCP FIN).'connectionfailed'- A connection attempt failed.'connectionrefused'- A connection attempt was refused.'connectionreset'- A connection was reset (corresponding to a TCP RST).'internetdisconnected'- The Internet connection has been lost.'namenotresolved'- The host name could not be resolved.'timedout'- An operation timed out.'failed'- A generic failure occurred.
Like abort/2, but returns the value and raises on error.
@spec continue(t(), continue_options()) :: :ok | {:error, Playwright.error()}
Sends route's request to the network with optional overrides.
Usage
Page.route!(page, "**/*", fn route, request ->
# Override headers
headers =
Request.headers(request)
# set "foo" header
|> Map.put("foo", "foo-value")
# remove "bar" header
|> Map.delete("bar")
Route.continue!(route, headers: headers)
end)Details
The :headers option applies to both the routed request and any redirects it initiates. However, :url, :method, and :post_data only apply to the original request and are not carried over to redirected requests.
Playwright.Route.continue/2 will immediately send the request to the network, other matching handlers won't be invoked. Use Playwright.Route.fallback/2 If you want next matching handler in the chain to be invoked.
Warning
Some request headers are forbidden and cannot be overridden (for example, Cookie, Host, Content-Length and others, see this MDN page for full list).
If an override is provided for a forbidden header, it will be ignored and the original request header will be used.
To set custom cookies, use Playwright.BrowserContext.add_cookies/2.
Since Playwright 1.8.
Options
:headers(%{optional(String.t()) => String.t()}) - If set changes the request HTTP headers. Header values will be converted to a string.:method(String.t/0) - If set changes the request method (e.g. GET or POST).:post_data(String.t/0|{:binary, binary()}|term/0) - If set changes the post data of request.:url(String.t/0) - If set changes the request URL. New URL must have same protocol as original one.
@spec continue!(t(), continue_options()) :: :ok
Like continue/2, but returns the value and raises on error.
@spec fallback(t(), fallback_options()) :: :ok | {:error, Playwright.error()}
Continues route's request with optional overrides. The method is similar to Playwright.Route.continue/2 with the difference that other matching handlers will be invoked before sending the request.
Usage
When several routes match the given pattern, they run in the order opposite to their registration. That way the last registered route can always override all the previous ones. In the example below, request will be handled by the bottom-most handler first, then it'll fall back to the previous one and in the end will be aborted by the first registered route.
Page.route!(page, "**/*", fn route ->
# Runs last.
Route.abort!(route)
end)
Page.route!(page, "**/*", fn route ->
# Runs second.
Route.fallback!(route)
end)
Page.route!(page, "**/*", fn route ->
# Runs first.
Route.fallback!(route)
end)Registering multiple routes is useful when you want separate handlers to handle different kinds of requests, for example API calls vs page resources or GET requests vs POST requests as in the example below.
# Handle GET requests.
Page.route!(page, "**/*", fn route ->
if Request.method(Route.request(route)) != "GET" do
Route.fallback!(route)
else
# Handling GET only.
# ...
end
end)
# Handle POST requests.
Page.route!(page, "**/*", fn route ->
if Request.method(Route.request(route)) != "POST" do
Route.fallback!(route)
else
# Handling POST only.
# ...
end
end)One can also modify request while falling back to the subsequent handler, that way intermediate route handler can modify url, method, headers and postData of the request.
Page.route!(page, "**/*", fn route, request ->
# Override headers
headers =
Request.headers(request)
# set "foo" header
|> Map.put("foo", "foo-value")
# remove "bar" header
|> Map.delete("bar")
Route.fallback!(route, headers: headers)
end)Use Playwright.Route.continue/2 to immediately send the request to the network, other matching handlers won't be invoked in that case.
Since Playwright 1.23.
Options
:headers(%{optional(String.t()) => String.t()}) - If set changes the request HTTP headers. Header values will be converted to a string.:method(String.t/0) - If set changes the request method (e.g. GET or POST).:post_data(String.t/0|{:binary, binary()}|term/0) - If set changes the post data of request.:url(String.t/0) - If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't affect the route matching, all the routes are matched using the original request URL.
@spec fallback!(t(), fallback_options()) :: :ok
Like fallback/2, but returns the value and raises on error.
@spec fetch(t(), fetch_options()) :: {:ok, Playwright.APIResponse.t()} | {:error, Playwright.error()}
Performs the request and fetches result without fulfilling it, so that the response could be modified and then fulfilled.
Usage
Page.route!(page, "https://dog.ceo/api/breeds/list/all", fn route ->
response = Route.fetch!(route)
json = APIResponse.json!(response)
json = put_in(json["message"]["big_red_dog"], [])
Route.fulfill!(route, response: response, json: json)
end)Details
Note that :headers option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply :headers to the original request, but not to redirects, look into Playwright.Route.continue/2 instead.
Since Playwright 1.29.
Options
:headers(%{optional(String.t()) => String.t()}) - If set changes the request HTTP headers. Header values will be converted to a string.:max_redirects(integer/0) - Since Playwright 1.31. Maximum number of request redirects that will be followed automatically. The call fails if the number is exceeded. Defaults to20. Pass0to not follow redirects.:max_retries(integer/0) - Since Playwright 1.46. Maximum number of times network errors should be retried. Currently onlyECONNRESETerror is retried. Does not retry based on HTTP response codes. The call fails if the limit is exceeded. Defaults to0- no retries.:method(String.t/0) - If set changes the request method (e.g. GET or POST).:post_data(String.t/0|{:binary, binary()}|term/0) - Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string andcontent-typeheader will be set toapplication/jsonif not explicitly set. Otherwise thecontent-typeheader will be set toapplication/octet-streamif not explicitly set.:signal(Playwright.AbortSignal.t/0) - Since Playwright 1.62. Allows to cancel the operation using anAbortSignal. If the signal is aborted, the operation will be aborted and fail. Note that providing a signal does not disable the default timeout, which can be changed usingPlaywright.BrowserContext.set_default_timeout/2orPlaywright.Page.set_default_timeout/2; passtimeout: 0to disable the timeout entirely.In Elixir, a
Playwright.AbortSignal(Playwright.AbortController.signal/1).:timeout(number/0|:infinity) - Since Playwright 1.33. Request timeout in milliseconds. Defaults to30000(30 seconds). Pass0to disable timeout.In Elixir,
:infinityis the same as0: no timeout.:url(String.t/0) - If set changes the request URL. New URL must have same protocol as original one.
@spec fetch!(t(), fetch_options()) :: Playwright.APIResponse.t()
Like fetch/2, but returns the value and raises on error.
@spec fulfill(t(), fulfill_options()) :: :ok | {:error, Playwright.error()}
Fulfills route's request with given response.
Usage
An example of fulfilling all requests with 404 responses:
Page.route!(page, "**/*", fn route ->
Route.fulfill!(route, status: 404, content_type: "text/plain", body: "Not Found!")
end)An example of serving static file:
Page.route!(page, "**/xhr_endpoint", &Route.fulfill!(&1, path: "mock_data.json"))Since Playwright 1.8.
Options
:body(String.t/0|{:binary, binary()}) - Response body.:content_type(String.t/0) - If set, equals to settingContent-Typeresponse header.:headers(%{optional(String.t()) => String.t()}) - Response headers. Header values will be converted to a string.:json(term/0) - Since Playwright 1.29. JSON response. This method will set the content type toapplication/jsonif not set.:path(String.t/0) - File path to respond with. The content type will be inferred from file extension. If:pathis a relative path, then it is resolved relative to the current working directory.:response(Playwright.APIResponse.t/0) - Since Playwright 1.15.APIResponseto fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.:status(integer/0) - Response status code, defaults to200.
@spec fulfill!(t(), fulfill_options()) :: :ok
Like fulfill/2, but returns the value and raises on error.
@spec request(t()) :: Playwright.Request.t()
A request to be routed.
Since Playwright 1.8.