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

Copy Markdown View Source

Whenever a WebSocket route is set up with Playwright.Page.route_web_socket/3 or Playwright.BrowserContext.route_web_socket/3, the WebSocketRoute object allows to handle the WebSocket, like an actual server would do.

Mocking

By default, the routed WebSocket will not connect to the server. This way, you can mock entire communication over the WebSocket. Here is an example that responds to a "request" with a "response".

Page.route_web_socket!(page, "wss://example.com/ws", fn ws ->
  WebSocketRoute.on_message(ws, fn message ->
    if message == "request", do: WebSocketRoute.send(ws, "response")
  end)
end)

Since we do not call Playwright.WebSocketRoute.connect_to_server/1 inside the WebSocket route handler, Playwright assumes that WebSocket will be mocked, and opens the WebSocket inside the page automatically.

Here is another example that handles JSON messages:

Page.route_web_socket!(page, "wss://example.com/ws", fn ws ->
  WebSocketRoute.on_message(ws, fn message ->
    json = JSON.decode!(message)
    if json["request"] == "question", do: WebSocketRoute.send(ws, JSON.encode!(%{response: "answer"}))
  end)
end)

Intercepting

Alternatively, you may want to connect to the actual server, but intercept messages in-between and modify or block them. Calling Playwright.WebSocketRoute.connect_to_server/1 returns a server-side WebSocketRoute instance that you can send messages to, or handle incoming messages.

Below is an example that modifies some messages sent by the page to the server. Messages sent from the server to the page are left intact, relying on the default forwarding.

Page.route_web_socket!(page, "/ws", fn ws ->
  server = WebSocketRoute.connect_to_server(ws)

  WebSocketRoute.on_message(ws, fn message ->
    if message == "request",
      do: WebSocketRoute.send(server, "request2"),
      else: WebSocketRoute.send(server, message)
  end)
end)

After connecting to the server, all messages are forwarded between the page and the server by default.

However, if you call Playwright.WebSocketRoute.on_message/2 on the original route, messages from the page to the server will not be forwarded anymore, but should instead be handled by the handler.

Similarly, calling Playwright.WebSocketRoute.on_message/2 on the server-side WebSocket will stop forwarding messages from the server to the page, and handler should take care of them.

The following example blocks some messages in both directions. Since it calls Playwright.WebSocketRoute.on_message/2 in both directions, there is no automatic forwarding at all.

Page.route_web_socket!(page, "/ws", fn ws ->
  server = WebSocketRoute.connect_to_server(ws)

  WebSocketRoute.on_message(ws, fn message ->
    if message != "blocked-from-the-page", do: WebSocketRoute.send(server, message)
  end)

  WebSocketRoute.on_message(server, fn message ->
    if message != "blocked-from-the-server", do: WebSocketRoute.send(ws, message)
  end)
end)

Since Playwright 1.48.

The examples alias the modules they use (alias Playwright.{Locator, Page}).

Summary

Types

Options of close/2, see its docs.

t()

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

Functions

Closes one side of the WebSocket connection.

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

By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This method connects to the actual WebSocket server, and returns the server-side WebSocketRoute instance, giving the ability to send and receive messages from the server.

This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.

The list of WebSocket subprotocols requested by the page, as passed via the second argument to the WebSocket constructor. Corresponds to the Sec-WebSocket-Protocol request header.

Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on the result of Playwright.WebSocketRoute.connect_to_server/1, sends the message to the server. See examples at the top for more details.

URL of the WebSocket created in the page.

Types

close_options()

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

Options of close/2, see its docs.

t()

@type t() :: %Playwright.WebSocketRoute{
  conn: term(),
  guid: term(),
  initializer: term(),
  table: term(),
  type: term()
}

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

Functions

close(web_socket_route, options \\ [])

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

Closes one side of the WebSocket connection.

Since Playwright 1.48.

Options

close!(web_socket_route, options \\ [])

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

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

connect_to_server(web_socket_route)

@spec connect_to_server(t()) :: t()

By default, routed WebSocket does not connect to the server, so you can mock entire WebSocket communication. This method connects to the actual WebSocket server, and returns the server-side WebSocketRoute instance, giving the ability to send and receive messages from the server.

Once connected to the server:

See examples at the top for more details.

Since Playwright 1.48.

on_close(web_socket_route, handler)

@spec on_close(t(), (integer() | nil, String.t() | nil -> term())) :: :ok

Allows to handle WebSocket.close.

By default, closing one side of the connection, either in the page or on the server, will close the other side. However, when Playwright.WebSocketRoute.on_close/2 handler is set up, the default forwarding of closure is disabled, and handler should take care of it.

Since Playwright 1.48.

Arguments

  • handler - Function that will handle WebSocket closure. Received an optional close code and an optional close reason.

on_message(web_socket_route, handler)

@spec on_message(t(), (String.t() | {:binary, binary()} -> term())) :: :ok

This method allows to handle messages that are sent by the WebSocket, either from the page or from the server.

When called on the original WebSocket route, this method handles messages sent from the page. You can handle this messages by responding to them with Playwright.WebSocketRoute.send/2, forwarding them to the server-side connection returned by Playwright.WebSocketRoute.connect_to_server/1 or do something else.

Once this method is called, messages are not automatically forwarded to the server or to the page - you should do that manually by calling Playwright.WebSocketRoute.send/2. See examples at the top for more details.

Calling this method again will override the handler with a new one.

Since Playwright 1.48.

Arguments

  • handler - Function that will handle messages.

protocols(web_socket_route)

@spec protocols(t()) :: [String.t()]

The list of WebSocket subprotocols requested by the page, as passed via the second argument to the WebSocket constructor. Corresponds to the Sec-WebSocket-Protocol request header.

Returns an empty array if no protocols were specified.

Usage

Page.route_web_socket!(page, "wss://example.com/ws", fn ws ->
  if "chat.v2" in WebSocketRoute.protocols(ws) do
    WebSocketRoute.on_message(ws, &WebSocketRoute.send(ws, JSON.encode!(%{version: 2, echo: &1})))
  else
    WebSocketRoute.close!(ws, code: 1002, reason: "Unsupported protocol")
  end
end)

Since Playwright 1.60.

send(web_socket_route, message)

@spec send(t(), String.t() | {:binary, binary()}) :: :ok

Sends a message to the WebSocket. When called on the original WebSocket, sends the message to the page. When called on the result of Playwright.WebSocketRoute.connect_to_server/1, sends the message to the server. See examples at the top for more details.

Since Playwright 1.48.

Arguments

  • message - Message to send.

url(web_socket_route)

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

URL of the WebSocket created in the page.

Since Playwright 1.48.