# `Playwright.WebSocketRoute`
[🔗](https://github.com/ftes/playwright_ex/blob/v1.65.0-rc.3/lib/playwright/api/web_socket_route.ex#L7)

Whenever a [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) route is set up with `Playwright.Page.route_web_socket/3` or `Playwright.BrowserContext.route_web_socket/3`, the [`WebSocketRoute`](`Playwright.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"`.

```elixir
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:

```elixir
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`](`Playwright.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.

```elixir
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.

```elixir
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}`).

# `close_options`

```elixir
@type close_options() ::
  [code: integer(), reason: String.t()]
  | %{optional(:code) =&gt; integer(), optional(:reason) =&gt; String.t()}
```

Options of `close/2`, see its docs.

# `t`

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

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

# `close`

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

Closes one side of the WebSocket connection.

*Since Playwright 1.48.*

## Options

* `:code` (`t:integer/0`) - Optional [close code](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code).
* `:reason` (`t:String.t/0`) - Optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).

# `close!`

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

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

# `connect_to_server`

```elixir
@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`](`Playwright.WebSocketRoute`) instance, giving the ability to send and receive messages from the server.

Once connected to the server:

* Messages received from the server will be **automatically forwarded** to the WebSocket in the page, unless `Playwright.WebSocketRoute.on_message/2` is called on the server-side [`WebSocketRoute`](`Playwright.WebSocketRoute`).
* Messages sent by the [`WebSocket.send()`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) call in the page will be **automatically forwarded** to the server, unless `Playwright.WebSocketRoute.on_message/2` is called on the original [`WebSocketRoute`](`Playwright.WebSocketRoute`).

See examples at the top for more details.

*Since Playwright 1.48.*

# `on_close`

```elixir
@spec on_close(t(), (integer() | nil, String.t() | nil -&gt; term())) :: :ok
```

Allows to handle [`WebSocket.close`](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#code) and an optional [close reason](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close#reason).

# `on_message`

```elixir
@spec on_message(t(), (String.t() | {:binary, binary()} -&gt; 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`

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

The list of WebSocket subprotocols requested by the page, as passed via the second argument to the [`WebSocket` constructor](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket). Corresponds to the `Sec-WebSocket-Protocol` request header.

Returns an empty array if no protocols were specified.

**Usage**

```elixir
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`

```elixir
@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`

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

URL of the WebSocket created in the page.

*Since Playwright 1.48.*

---

*Consult [api-reference.md](api-reference.md) for complete listing*
