Skip to content

The headless browser for AI agents and web scraping

fix(cdp): implement Page.close and Page.stopLoading

yvv4gite5bcd7556404
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rs
index eec221a1..6525d882 100644
--- a/crates/obscura-cdp/src/domains/page.rs
+++ b/crates/obscura-cdp/src/domains/page.rs
@@ -1444,6 +1444,26 @@ pub async fn handle(
});
do_navigate(&current_url, &reload_params, ctx, session_id).await
}
+ "close" => {
+ // go-rod closes a tab with `Page.close` and then blocks until it
+ // receives `Target.targetDestroyed` for that target (rod/page.go
+ // `Close`). Returning "Unknown Page method" left every crawled page
+ // stuck in rod's session map. Chromium supports Page.close, so
+ // share the teardown with `Target.closeTarget`.
+ let target_id = ctx
+ .get_session_page(session_id)
+ .ok_or("No page for session")?
+ .id
+ .clone();
+ crate::domains::target::close_target(ctx, &target_id);
+ Ok(json!({}))
+ }
+ "stopLoading" => {
+ // Chromium answers `{}` here; go-rod calls it before each navigate.
+ // It only has to look like a success - the in-flight navigation is
+ // cancelled by the navigate that follows.
+ Ok(json!({}))
+ }
"getFrameTree" => {
let page = ctx
.get_session_page(session_id)
diff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rs
index a22371a1..554d178d 100644
--- a/crates/obscura-cdp/src/domains/target.rs
+++ b/crates/obscura-cdp/src/domains/target.rs
@@ -218,26 +218,7 @@ pub async fn handle(
.get("targetId")
.and_then(|v| v.as_str())
.ok_or("targetId required")?;
- let mut sessions = ctx.sessions.iter()
- .filter(|(_, page_id)| page_id.as_str() == target_id)
- .map(|(session_id, _)| session_id.clone())
- .collect::<Vec<_>>();
- sessions.sort_unstable();
- for session_id in sessions {
- ctx.pending_events.push(CdpEvent::new(
- "Target.detachedFromTarget",
- json!({
- "sessionId": session_id,
- "targetId": target_id,
- }),
- ));
- }
- ctx.pending_events.push(CdpEvent::new(
- "Target.targetDestroyed",
- json!({ "targetId": target_id }),
- ));
-
- ctx.remove_page(target_id);
+ close_target(ctx, target_id);
Ok(json!({ "success": true }))
}
"setAutoAttach" => Ok(json!({})),
@@ -337,6 +318,35 @@ pub async fn handle(
}
}
+/// Detach every session attached to `target_id`, announce the destruction to
+/// subscribers and drop the page. Shared by `Target.closeTarget` and
+/// `Page.close`: go-rod closes tabs with `Page.close` and then blocks until it
+/// sees `Target.targetDestroyed` (rod/page.go `Close`), so both paths must emit
+/// the same lifecycle events.
+pub(crate) fn close_target(ctx: &mut CdpContext, target_id: &str) {
+ let mut sessions = ctx.sessions
+ .iter()
+ .filter(|(_, page_id)| page_id.as_str() == target_id)
+ .map(|(session_id, _)| session_id.clone())
+ .collect::<Vec<_>>();
+ sessions.sort_unstable();
+ for session_id in sessions {
+ ctx.pending_events.push(CdpEvent::new(
+ "Target.detachedFromTarget",
+ json!({
+ "sessionId": session_id,
+ "targetId": target_id,
+ }),
+ ));
+ }
+ ctx.pending_events.push(CdpEvent::new(
+ "Target.targetDestroyed",
+ json!({ "targetId": target_id }),
+ ));
+
+ ctx.remove_page(target_id);
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/obscura-cdp/tests/integration.rs b/crates/obscura-cdp/tests/integration.rs
index 4ae204ee..3b886ec2 100644
--- a/crates/obscura-cdp/tests/integration.rs
+++ b/crates/obscura-cdp/tests/integration.rs
@@ -49,6 +49,7 @@ integration_tests!(
js_fetch_emits_network_events,
max_connections_cap,
nodefilter_constants,
+ page_close_destroys_target,
page_frame_contract,
runtime_by_value_undefined,
runtime_console_events,
diff --git a/crates/obscura-cdp/tests/page_close_destroys_target.rs b/crates/obscura-cdp/tests/page_close_destroys_target.rs
new file mode 100644
index 00000000..6a668ef2
--- /dev/null
+++ b/crates/obscura-cdp/tests/page_close_destroys_target.rs
@@ -0,0 +1,82 @@
+//! `Page.close` closed nothing: obscura fell through to its
+//! `Unknown Page method` catch-all, so a go-rod client that closed a tab got an
+//! error back and - worse - no `Target.targetDestroyed` event. rod's `Page.Close`
+//! sends `Page.close` and then sits in a `for msg := range messages` loop until
+//! that event arrives (rod/page.go), so every crawled URL ended with
+//! `Failed close page: Unknown Page method: close` and the page stayed in the
+//! browser's page map.
+//!
+//! The teardown is the one `Target.closeTarget` already performs: detach each
+//! attached session, announce the destruction, drop the page. Chromium answers
+//! `{}` to `Page.close` too, so both methods share that helper.
+
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+
+async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, session_id: &str) -> Value {
+ let resp = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: Some(session_id.to_string()),
+ },
+ ctx,
+ )
+ .await;
+ assert!(resp.error.is_none(), "CDP {method} failed: {:?}", resp.error);
+ resp.result.unwrap_or_else(|| json!({}))
+}
+
+fn emitted(ctx: &CdpContext, event: &str) -> Vec<Value> {
+ ctx.pending_events
+ .iter()
+ .filter(|e| e.method == event)
+ .map(|e| e.params.clone())
+ .collect()
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn page_close_destroys_the_target_and_emits_target_destroyed() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session_id = "session-1";
+ ctx.sessions.insert(session_id.to_string(), page_id.clone());
+
+ cdp(&mut ctx, 1, "Page.close", json!({}), session_id).await;
+
+ assert!(
+ ctx.pages.iter().all(|p| p.id != page_id),
+ "Page.close must drop the page, pages left: {:?}",
+ ctx.pages.iter().map(|p| &p.id).collect::<Vec<_>>()
+ );
+
+ let destroyed = emitted(&ctx, "Target.targetDestroyed");
+ assert!(
+ destroyed
+ .iter()
+ .any(|p| p.get("targetId").and_then(|v| v.as_str()) == Some(page_id.as_str())),
+ "rod waits for Target.targetDestroyed before Close returns; events: {destroyed:#?}"
+ );
+
+ let detached = emitted(&ctx, "Target.detachedFromTarget");
+ assert!(
+ detached
+ .iter()
+ .any(|p| p.get("sessionId").and_then(|v| v.as_str()) == Some(session_id)),
+ "the attached session must be detached too; events: {detached:#?}"
+ );
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn stop_loading_answers_success_like_chromium() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session_id = "session-1";
+ ctx.sessions.insert(session_id.to_string(), page_id.clone());
+
+ let result = cdp(&mut ctx, 1, "Page.stopLoading", json!({}), session_id).await;
+
+ assert_eq!(result, json!({}), "go-rod calls this before every navigate");
+}