viewpoint_core/page/popup/mod.rs
1//! Popup window handling.
2//!
3//! This module provides functionality for detecting and handling popup windows
4//! that are opened by JavaScript code (e.g., via `window.open()`).
5
6// Allow dead code for popup scaffolding (spec: page-operations)
7
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11use std::time::Duration;
12
13use tokio::sync::{oneshot, RwLock};
14use tracing::debug;
15
16use viewpoint_cdp::CdpConnection;
17
18use crate::error::PageError;
19use crate::page::Page;
20
21/// Type alias for the popup event handler function.
22pub type PopupEventHandler = Box<
23 dyn Fn(Page) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
24>;
25
26/// Manager for page-level popup events.
27pub struct PopupManager {
28 /// Popup event handler.
29 handler: RwLock<Option<PopupEventHandler>>,
30 /// Target ID of the owning page.
31 target_id: String,
32 /// CDP connection for subscribing to events.
33 connection: Arc<CdpConnection>,
34 /// Session ID of the owning page.
35 session_id: String,
36}
37
38impl PopupManager {
39 /// Create a new popup manager for a page.
40 pub fn new(connection: Arc<CdpConnection>, session_id: String, target_id: String) -> Self {
41 Self {
42 handler: RwLock::new(None),
43 target_id,
44 connection,
45 session_id,
46 }
47 }
48
49 /// Set a handler for popup events.
50 pub async fn set_handler<F, Fut>(&self, handler: F)
51 where
52 F: Fn(Page) -> Fut + Send + Sync + 'static,
53 Fut: Future<Output = ()> + Send + 'static,
54 {
55 let boxed_handler: PopupEventHandler = Box::new(move |page| {
56 Box::pin(handler(page))
57 });
58 let mut h = self.handler.write().await;
59 *h = Some(boxed_handler);
60 }
61
62 /// Remove the popup handler.
63 pub async fn remove_handler(&self) {
64 let mut h = self.handler.write().await;
65 *h = None;
66 }
67
68 /// Emit a popup event to the handler.
69 pub async fn emit(&self, popup: Page) {
70 let handler = self.handler.read().await;
71 if let Some(ref h) = *handler {
72 h(popup).await;
73 }
74 }
75
76 /// Check if this popup was opened by the page with the given `target_id`.
77 pub fn is_opener(&self, opener_id: &str) -> bool {
78 self.target_id == opener_id
79 }
80}
81
82/// Builder for waiting for a popup during an action.
83pub struct WaitForPopupBuilder<'a, F, Fut>
84where
85 F: FnOnce() -> Fut,
86 Fut: Future<Output = Result<(), crate::error::LocatorError>>,
87{
88 page: &'a Page,
89 action: Option<F>,
90 timeout: Duration,
91}
92
93// =========================================================================
94// Page impl - Popup Handling Methods
95// =========================================================================
96
97impl Page {
98 /// Set a handler for popup window events.
99 ///
100 /// The handler will be called whenever a popup window is opened
101 /// from this page (e.g., via `window.open()` or `target="_blank"` links).
102 ///
103 /// # Example
104 ///
105 /// ```ignore
106 /// page.on_popup(|popup| async move {
107 /// println!("Popup opened: {}", popup.url().await.unwrap_or_default());
108 /// // Work with the popup
109 /// popup.close().await?;
110 /// Ok(())
111 /// }).await;
112 /// ```
113 pub async fn on_popup<F, Fut>(&self, handler: F)
114 where
115 F: Fn(Page) -> Fut + Send + Sync + 'static,
116 Fut: Future<Output = ()> + Send + 'static,
117 {
118 self.popup_manager.set_handler(handler).await;
119 }
120
121 /// Remove the popup handler.
122 pub async fn off_popup(&self) {
123 self.popup_manager.remove_handler().await;
124 }
125
126 /// Wait for a popup to be opened during an action.
127 ///
128 /// This is useful for handling popups that are opened by clicking links
129 /// or buttons that open new windows.
130 ///
131 /// # Example
132 ///
133 /// ```ignore
134 /// let popup = page.wait_for_popup(|| async {
135 /// page.locator("a[target=_blank]").click().await
136 /// }).await?;
137 ///
138 /// // Now work with the popup page
139 /// println!("Popup URL: {}", popup.url().await?);
140 /// popup.close().await?;
141 /// ```
142 ///
143 /// # Errors
144 ///
145 /// Returns an error if:
146 /// - The action fails
147 /// - No popup is opened within the timeout (30 seconds by default)
148 pub fn wait_for_popup<F, Fut>(
149 &self,
150 action: F,
151 ) -> WaitForPopupBuilder<'_, F, Fut>
152 where
153 F: FnOnce() -> Fut,
154 Fut: Future<Output = Result<(), crate::error::LocatorError>>,
155 {
156 WaitForPopupBuilder::new(self, action)
157 }
158
159 /// Get the opener page that opened this popup.
160 ///
161 /// Returns `None` if this page is not a popup (was created via `context.new_page()`).
162 ///
163 /// Note: This method currently returns `None` because tracking opener pages
164 /// requires context-level state management. For now, you can check if a page
165 /// is a popup by examining whether it was returned from `wait_for_popup()`.
166 pub fn opener(&self) -> Option<&str> {
167 self.opener_target_id.as_deref()
168 }
169}
170
171impl<'a, F, Fut> WaitForPopupBuilder<'a, F, Fut>
172where
173 F: FnOnce() -> Fut,
174 Fut: Future<Output = Result<(), crate::error::LocatorError>>,
175{
176 /// Create a new builder.
177 pub fn new(page: &'a Page, action: F) -> Self {
178 Self {
179 page,
180 action: Some(action),
181 timeout: Duration::from_secs(30),
182 }
183 }
184
185 /// Set the timeout for waiting for the popup.
186 #[must_use]
187 pub fn timeout(mut self, timeout: Duration) -> Self {
188 self.timeout = timeout;
189 self
190 }
191
192 /// Execute the action and wait for a popup.
193 ///
194 /// Returns the popup page that was opened during the action.
195 pub async fn wait(mut self) -> Result<Page, PageError> {
196 use viewpoint_cdp::protocol::target_domain::{AttachToTargetParams, AttachToTargetResult, TargetCreatedEvent};
197
198 let connection = self.page.connection().clone();
199 let target_id = self.page.target_id().to_string();
200 let _session_id = self.page.session_id().to_string();
201
202 // Create a channel to receive the popup
203 let (tx, rx) = oneshot::channel::<Page>();
204 let tx = Arc::new(tokio::sync::Mutex::new(Some(tx)));
205
206 // Subscribe to target events
207 let mut events = connection.subscribe_events();
208 let tx_clone = tx.clone();
209 let connection_clone = connection.clone();
210 let target_id_clone = target_id.clone();
211
212 // Spawn a task to listen for popup events
213 let popup_listener = tokio::spawn(async move {
214 while let Ok(event) = events.recv().await {
215 if event.method == "Target.targetCreated" {
216 if let Some(params) = &event.params {
217 if let Ok(created_event) = serde_json::from_value::<TargetCreatedEvent>(params.clone()) {
218 let info = &created_event.target_info;
219
220 // Check if this is a popup opened by our page
221 if info.target_type == "page"
222 && info.opener_id.as_deref() == Some(&target_id_clone)
223 {
224 debug!("Popup detected: {}", info.target_id);
225
226 // Attach to the popup target
227 let attach_result: Result<AttachToTargetResult, _> = connection_clone
228 .send_command(
229 "Target.attachToTarget",
230 Some(AttachToTargetParams {
231 target_id: info.target_id.clone(),
232 flatten: Some(true),
233 }),
234 None,
235 )
236 .await;
237
238 if let Ok(attach) = attach_result {
239 // Enable required domains on the popup
240 let popup_session = &attach.session_id;
241
242 let _ = connection_clone
243 .send_command::<(), serde_json::Value>("Page.enable", None, Some(popup_session))
244 .await;
245 let _ = connection_clone
246 .send_command::<(), serde_json::Value>("Network.enable", None, Some(popup_session))
247 .await;
248 let _ = connection_clone
249 .send_command::<(), serde_json::Value>("Runtime.enable", None, Some(popup_session))
250 .await;
251
252 // Get the main frame ID
253 let frame_tree: Result<viewpoint_cdp::protocol::page::GetFrameTreeResult, _> = connection_clone
254 .send_command("Page.getFrameTree", None::<()>, Some(popup_session))
255 .await;
256
257 if let Ok(tree) = frame_tree {
258 let frame_id = tree.frame_tree.frame.id;
259
260 // Create the popup Page
261 let popup = Page::new(
262 connection_clone.clone(),
263 info.target_id.clone(),
264 attach.session_id.clone(),
265 frame_id,
266 );
267
268 // Send the popup
269 let mut guard = tx_clone.lock().await;
270 if let Some(sender) = guard.take() {
271 let _ = sender.send(popup);
272 return;
273 }
274 }
275 }
276 }
277 }
278 }
279 }
280 }
281 });
282
283 // Execute the action
284 let action = self.action.take().expect("action already consumed");
285 let action_result = action().await;
286
287 // Wait for the popup or timeout
288 let result = match action_result {
289 Ok(()) => {
290 match tokio::time::timeout(self.timeout, rx).await {
291 Ok(Ok(popup)) => Ok(popup),
292 Ok(Err(_)) => Err(PageError::EvaluationFailed(
293 "Popup channel closed unexpectedly".to_string(),
294 )),
295 Err(_) => Err(PageError::EvaluationFailed(
296 format!("wait_for_popup timed out after {:?}", self.timeout),
297 )),
298 }
299 }
300 Err(e) => Err(PageError::EvaluationFailed(e.to_string())),
301 };
302
303 // Clean up the listener
304 popup_listener.abort();
305
306 result
307 }
308}