Skip to main content

WebSocketRoute

Whenever a WebSocket route is set up with Page.routeWebSocket() or BrowserContext.routeWebSocket(), 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.routeWebSocket("wss://example.com/ws", ws -> {
ws.onMessage(frame -> {
if ("request".equals(frame.text()))
ws.send("response");
});
});

Since we do not call WebSocketRoute.connectToServer() 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.routeWebSocket("wss://example.com/ws", ws -> {
ws.onMessage(frame -> {
JsonObject json = new JsonParser().parse(frame.text()).getAsJsonObject();
if ("question".equals(json.get("request").getAsString())) {
Map<String, String> result = new HashMap();
result.put("response", "answer");
ws.send(gson.toJson(result));
}
});
});

Intercepting

Alternatively, you may want to connect to the actual server, but intercept messages in-between and modify or block them. Calling WebSocketRoute.connectToServer() 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.routeWebSocket("/ws", ws -> {
WebSocketRoute server = ws.connectToServer();
ws.onMessage(frame -> {
if ("request".equals(frame.text()))
server.send("request2");
else
server.send(frame.text());
});
});

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

However, if you call WebSocketRoute.onMessage() 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 WebSocketRoute.onMessage() 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 WebSocketRoute.onMessage() in both directions, there is no automatic forwarding at all.

page.routeWebSocket("/ws", ws -> {
WebSocketRoute server = ws.connectToServer();
ws.onMessage(