Skip to main content

WebSocketRoute

每当使用 [Page.RouteWebSocketAsync()](/api/class-page.mdx#page-route-web-socket) 或 [BrowserContext.RouteWebSocketAsync()](/api/class-browsercontext.mdx#browser-context-route-web-socket) 设置 ['WebSocket'](https://web.nodejs.cn/en-US/docs/Web/API/WebSocket) 路由时,'WebSocketRoute' 对象允许像实际服务器一样处理 WebSocket。

🌐 Whenever a WebSocket route is set up with Page.RouteWebSocketAsync() or BrowserContext.RouteWebSocketAsync(), the WebSocketRoute object allows to handle the WebSocket, like an actual server would do.

模拟

默认情况下,路由的 WebSocket 不会连接到服务器。这样,你可以模拟整个 WebSocket 通信。下面是一个示例,它用 "response" 响应 "request"

🌐 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".

await page.RouteWebSocketAsync("wss://example.com/ws", ws => {
ws.OnMessage(frame => {
if (frame.Text == "request")
ws.Send("response");
});
});

由于我们没有在 WebSocket 路由处理程序内调用 WebSocketRoute.ConnectToServer,Playwright 假定 WebSocket 会被模拟,并会自动在页面内打开 WebSocket。

🌐 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.

以下是另一个处理 JSON 消息的示例:

🌐 Here is another example that handles JSON messages:

await page.RouteWebSocketAsync("wss://example.com/ws", ws => {
ws.OnMessage(frame => {
using var jsonDoc = JsonDocument.Parse(frame.Text);
JsonElement root = jsonDoc.RootElement;
if (root.TryGetProperty("request", out JsonElement requestElement) && requestElement.GetString() == "question")
{
var response = new Dictionary<string, string> { ["response"] = "answer" };
string jsonResponse = JsonSerializer.Serialize(response);
ws.Send(jsonResponse);
}
});
});

拦截

或者,你可能想连接到实际的服务器,但在中间拦截消息并对其进行修改或阻止。调用 WebSocketRoute.ConnectToServer 会返回一个服务器端的 WebSocketRoute 实例,你可以向其发送消息,或处理传入的消息。

🌐 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.

await page.RouteWebSocketAsync("/ws", ws => {
var server = ws.ConnectToServer();
ws.OnMessage(frame => {
if (frame.Text == "request")
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.

然而,如果你在原始路由上调用 WebSocketRoute.OnMessage(),来自页面到服务器的消息将不再被转发,而应该由 handler 来处理。

🌐 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.

同样地,在服务器端 WebSocket 上调用 WebSocketRoute.OnMessage()停止将消息转发到页面,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.

以下示例阻止了双向的某些消息。由于它在两个方向都调用了 WebSocketRoute.OnMessage(),因此根本不会有自动转发。

🌐 The following example blocks some messages in both directions. Since it calls WebSocketRoute.OnMessage() in both directions, there is no automatic forwarding at all.

await page.RouteWebSocketAsync("/ws", ws => {
var server = ws.ConnectToServer();
ws.OnMessage(frame => {
if (frame.Text != "blocked-from-the-page")
server.Send(frame.Text);
});
server.OnMessage(frame => {
if (frame.Text != "blocked-from-the-server")
ws.Send(frame.Text);
});
});

方法

🌐 Methods

CloseAsync

Added in: v1.48 webSocketRoute.CloseAsync

关闭 WebSocket 连接的一侧。

🌐 Closes one side of the WebSocket connection.

用法

await WebSocketRoute.CloseAsync(options);

参数

返回


ConnectToServer

Added in: v1.48 webSocketRoute.ConnectToServer

默认情况下,已路由的 WebSocket 不会连接到服务器,因此你可以模拟整个 WebSocket 通信。此方法会连接到实际的 WebSocket 服务器,并返回服务器端的 WebSocketRoute 实例,从而能够向服务器发送和接收消息。

🌐 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.

用法

WebSocketRoute.ConnectToServer

返回


OnClose

Added in: v1.48 webSocketRoute.OnClose

允许处理 WebSocket.close

🌐 Allows to handle WebSocket.close.

默认情况下,关闭连接的一端,无论是在页面还是在服务器上,都会关闭另一端。然而,当设置了 WebSocketRoute.OnClose() 处理程序时,默认的关闭转发将被禁用,处理程序需要负责处理关闭操作。

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

用法

WebSocketRoute.OnClose(handler);

参数

  • handler Action<int?, string?>#

    处理 WebSocket 关闭的函数。接收一个可选的关闭代码和一个可选的关闭原因


OnMessage

Added in: v1.48 webSocketRoute.OnMessage

此方法允许处理 WebSocket 发送的消息,无论是从页面还是从服务器发送。

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

当在原始 WebSocket 路由上调用时,该方法处理来自页面发送的消息。你可以通过 WebSocketRoute.Send() 响应这些消息,将它们转发到由 WebSocketRoute.ConnectToServer 返回的服务器端连接,或者执行其他操作来处理这些消息。

🌐 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 WebSocketRoute.Send(), forwarding them to the server-side connection returned by WebSocketRoute.ConnectToServer or do something else.

一旦调用此方法,消息不会自动转发到服务器或页面——你需要通过调用 WebSocketRoute.Send() 手动完成。更多详细信息,请参考顶部的示例。

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

再次调用此方法将用新方法覆盖处理程序。

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

用法

WebSocketRoute.OnMessage(handler);

参数


Send

Added in: v1.48 webSocketRoute.Send

向 WebSocket 发送消息。在原始 WebSocket 上调用时,将消息发送到页面。在对 WebSocketRoute.ConnectToServer 的结果调用时,将消息发送到服务器。有关更多详细信息,请参见顶部的示例。

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

用法

WebSocketRoute.Send(message);

参数


Url

Added in: v1.48 webSocketRoute.Url

在页面中创建的 WebSocket 的 URL。

🌐 URL of the WebSocket created in the page.

用法

WebSocketRoute.Url

返回