1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! WebSocketRoute protocol object — represents an intercepted WebSocket connection.
//!
//! `WebSocketRoute` is created by the Playwright server when a WebSocket connection
//! matches a pattern registered via [`crate::protocol::Page::route_web_socket`] or
//! [`crate::protocol::BrowserContext::route_web_socket`].
//!
//! # Example
//!
//! ```no_run
//! use playwright_rs::protocol::Playwright;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let playwright = Playwright::launch().await?;
//! let browser = playwright.chromium().launch().await?;
//! let page = browser.new_page().await?;
//!
//! // Intercept all WebSocket connections and proxy them to the real server
//! page.route_web_socket("ws://**", |route| {
//! Box::pin(async move {
//! route.connect_to_server().await?;
//! Ok(())
//! })
//! })
//! .await?;
//!
//! browser.close().await?;
//! Ok(())
//! }
//! ```
//!
//! See: <https://playwright.dev/docs/api/class-websocketroute>
use crate::error::Result;
use crate::server::channel::Channel;
use crate::server::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
use serde_json::Value;
use std::any::Any;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
/// Represents an intercepted WebSocket connection.
///
/// `WebSocketRoute` is passed to handlers registered via
/// [`crate::protocol::Page::route_web_socket`] or [`crate::protocol::BrowserContext::route_web_socket`].
/// The handler must call [`connect_to_server`](WebSocketRoute::connect_to_server)
/// to forward the connection to the real server, or [`close`](WebSocketRoute::close)
/// to terminate it.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute>
#[derive(Clone)]
pub struct WebSocketRoute {
base: ChannelOwnerImpl,
/// The WebSocket URL being intercepted.
url: String,
/// Message handlers registered via on_message().
message_handlers: Arc<Mutex<Vec<WebSocketRouteMessageHandler>>>,
/// Close handlers registered via on_close().
close_handlers: Arc<Mutex<Vec<WebSocketRouteCloseHandler>>>,
}
/// Type alias for boxed WebSocketRoute message handler future.
type WebSocketRouteHandlerFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
/// Message handler type.
type WebSocketRouteMessageHandler =
Arc<dyn Fn(String) -> WebSocketRouteHandlerFuture + Send + Sync>;
/// Close handler type.
type WebSocketRouteCloseHandler = Arc<dyn Fn() -> WebSocketRouteHandlerFuture + Send + Sync>;
impl WebSocketRoute {
/// Creates a new `WebSocketRoute` object.
pub fn new(
parent: Arc<dyn ChannelOwner>,
type_name: String,
guid: Arc<str>,
initializer: Value,
) -> Result<Self> {
let url = initializer["url"].as_str().unwrap_or("").to_string();
let base = ChannelOwnerImpl::new(
ParentOrConnection::Parent(parent),
type_name,
guid,
initializer,
);
Ok(Self {
base,
url,
message_handlers: Arc::new(Mutex::new(Vec::new())),
close_handlers: Arc::new(Mutex::new(Vec::new())),
})
}
/// Returns the URL of the intercepted WebSocket connection.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-url>
pub fn url(&self) -> &str {
&self.url
}
/// Returns the WebSocket subprotocols the page requested (the
/// `Sec-WebSocket-Protocol` values) when opening this socket. Empty if none
/// were requested.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-protocols>
pub fn protocols(&self) -> Vec<String> {
self.base
.initializer()
.get("protocols")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect()
})
.unwrap_or_default()
}
/// Connects this WebSocket to the actual server.
///
/// After calling this method, all messages sent by the page are forwarded to
/// the server, and all messages sent by the server are forwarded to the page.
///
/// # Errors
///
/// Returns an error if the RPC call fails.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-connect-to-server>
pub async fn connect_to_server(&self) -> Result<()> {
self.base
.channel()
.send_no_result("connectToServer", serde_json::json!({}))
.await
}
/// Closes the WebSocket connection.
///
/// # Arguments
///
/// * `options` — Optional close code and reason.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-close>
pub async fn close(&self, options: Option<WebSocketRouteCloseOptions>) -> Result<()> {
let opts = options.unwrap_or_default();
let mut params = serde_json::Map::new();
if let Some(code) = opts.code {
params.insert("code".to_string(), serde_json::json!(code));
}
if let Some(reason) = opts.reason {
params.insert("reason".to_string(), serde_json::json!(reason));
}
self.base
.channel()
.send_no_result("close", Value::Object(params))
.await
}
/// Sends a text message to the page.
///
/// # Arguments
///
/// * `message` — The text message to send.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-send>
pub async fn send(&self, message: &str) -> Result<()> {
self.base
.channel()
.send_no_result(
"sendToPage",
serde_json::json!({ "message": message, "isBase64": false }),
)
.await
}
/// Registers a handler for messages sent from the page.
///
/// # Arguments
///
/// * `handler` — Async closure that receives the message payload as a `String`.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-on-message>
pub async fn on_message<F>(&self, handler: F) -> Result<()>
where
F: Fn(String) -> WebSocketRouteHandlerFuture + Send + Sync + 'static,
{
let handler_arc = Arc::new(handler);
self.message_handlers.lock().unwrap().push(handler_arc);
Ok(())
}
/// Registers a handler for when the WebSocket is closed by the page.
///
/// See: <https://playwright.dev/docs/api/class-websocketroute#web-socket-route-on-close>
pub async fn on_close<F>(&self, handler: F) -> Result<()>
where
F: Fn() -> WebSocketRouteHandlerFuture + Send + Sync + 'static,
{
let handler_arc = Arc::new(handler);
self.close_handlers.lock().unwrap().push(handler_arc);
Ok(())
}
/// Dispatches an incoming server-side event to registered handlers.
pub(crate) fn handle_event(&self, event: &str, params: &Value) {
match event {
"messageFromPage" => {
let payload = params["message"].as_str().unwrap_or("").to_string();
let handlers = self.message_handlers.lock().unwrap().clone();
for handler in handlers {
let p = payload.clone();
tokio::spawn(async move {
let _ = handler(p).await;
});
}
}
"close" => {
let handlers = self.close_handlers.lock().unwrap().clone();
for handler in handlers {
tokio::spawn(async move {
let _ = handler().await;
});
}
}
_ => {}
}
}
}
/// Options for [`WebSocketRoute::close`].
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct WebSocketRouteCloseOptions {
/// WebSocket close code (e.g. 1000 for normal closure).
pub code: Option<u16>,
/// Human-readable close reason.
pub reason: Option<String>,
}
impl ChannelOwner for WebSocketRoute {
fn guid(&self) -> &str {
self.base.guid()
}
fn type_name(&self) -> &str {
self.base.type_name()
}
fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
self.base.parent()
}
fn connection(&self) -> Arc<dyn crate::server::connection::ConnectionLike> {
self.base.connection()
}
fn initializer(&self) -> &Value {
self.base.initializer()
}
fn channel(&self) -> &Channel {
self.base.channel()
}
fn dispose(&self, reason: crate::server::channel_owner::DisposeReason) {
self.base.dispose(reason)
}
fn adopt(&self, child: Arc<dyn ChannelOwner>) {
self.base.adopt(child)
}
fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
self.base.add_child(guid, child)
}
fn remove_child(&self, guid: &str) {
self.base.remove_child(guid)
}
fn on_event(&self, method: &str, params: Value) {
self.handle_event(method, ¶ms);
self.base.on_event(method, params)
}
fn was_collected(&self) -> bool {
self.base.was_collected()
}
fn as_any(&self) -> &dyn Any {
self
}
}