Skip to content

The headless browser for AI agents and web scraping

fix(cdp): build child frames before the DomContentLoaded return

xripb5fa41bbcd81
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 6ab2163b..bc7a58d9 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -2849,6 +2849,13 @@ impl Page {
self.lifecycle = LifecycleState::DomContentLoaded;
+ // Before any `wait_until` can return, because the frames belong to the
+ // document rather than to one readiness level. Puppeteer and Playwright
+ // send `Page.navigate` with no `waitUntil`, which lands here and returns
+ // on the next line, so building frames further down left every real CDP
+ // client seeing a page with no frames at all.
+ self.build_document_frames().await;
+
if wait_until == crate::lifecycle::WaitUntil::DomContentLoaded {
return Ok(());
}
@@ -2927,8 +2934,6 @@ impl Page {
self.lifecycle = LifecycleState::NetworkIdle;
}
- self.build_document_frames().await;
-
Ok(())
}
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index e06a6308..03bc5075 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -603,16 +603,27 @@ pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {
// after every dispatch, reports a frame whenever it actually appears instead
// of only at navigation, and is the same drain point binding calls use.
pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
- let page_to_session: HashMap<String, String> = ctx
- .sessions
- .iter()
- .map(|(sid, pid)| (pid.clone(), sid.clone()))
- .collect();
+ // Every session on the page, not just one: a client that reaches a page the
+ // ordinary way holds two of them, because Target.createTarget opens a
+ // session and the Target.attachToTarget that follows opens another. A
+ // client drops any event whose sessionId is not the one it attached with,
+ // so announcing to an arbitrary session is the same as not announcing.
+ let mut page_to_sessions: HashMap<String, Vec<String>> = HashMap::new();
+ for (session_id, page_id) in &ctx.sessions {
+ page_to_sessions
+ .entry(page_id.clone())
+ .or_default()
+ .push(session_id.clone());
+ }
+ // ctx.sessions is a HashMap, so fix an order the events can be asserted in.
+ for sessions in page_to_sessions.values_mut() {
+ sessions.sort();
+ }
let mut events: Vec<CdpEvent> = Vec::new();
let mut announced: HashMap<String, Vec<String>> = HashMap::new();
for page in &ctx.pages {
- let Some(session_id) = page_to_session.get(&page.id).cloned() else {
+ let Some(session_ids) = page_to_sessions.get(&page.id) else {
continue;
};
let live = crate::domains::page::child_frame_values(page);
@@ -627,39 +638,43 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
if known.is_some_and(|ids| ids.iter().any(|seen| seen == id)) {
continue;
}
- // Attach before navigate: a client builds its frame from the attach
- // event and treats a navigation of a frame it has never seen as a
- // protocol error.
- events.push(CdpEvent {
- method: "Page.frameAttached".into(),
- params: json!({
- "frameId": id,
- "parentFrameId": frame["parentId"].as_str().unwrap_or_default(),
- }),
- session_id: Some(session_id.clone()),
- });
- events.push(CdpEvent {
- method: "Page.frameNavigated".into(),
- params: json!({ "frame": frame, "type": "Navigation" }),
- session_id: Some(session_id.clone()),
- });
- // The frame's document scripts have already run by the time it is
- // in this list, so it is not still loading.
- events.push(CdpEvent {
- method: "Page.frameStoppedLoading".into(),
- params: json!({ "frameId": id }),
- session_id: Some(session_id.clone()),
- });
+ for session_id in session_ids {
+ // Attach before navigate: a client builds its frame from the
+ // attach event and treats a navigation of a frame it has never
+ // seen as a protocol error.
+ events.push(CdpEvent {
+ method: "Page.frameAttached".into(),
+ params: json!({
+ "frameId": id,
+ "parentFrameId": frame["parentId"].as_str().unwrap_or_default(),
+ }),
+ session_id: Some(session_id.clone()),
+ });
+ events.push(CdpEvent {
+ method: "Page.frameNavigated".into(),
+ params: json!({ "frame": frame, "type": "Navigation" }),
+ session_id: Some(session_id.clone()),
+ });
+ // The frame's document scripts have already run by the time it
+ // is in this list, so it is not still loading.
+ events.push(CdpEvent {
+ method: "Page.frameStoppedLoading".into(),
+ params: json!({ "frameId": id }),
+ session_id: Some(session_id.clone()),
+ });
+ }
}
if let Some(known) = known {
for id in known {
if !live_ids.contains(id) {
- events.push(CdpEvent {
- method: "Page.frameDetached".into(),
- params: json!({ "frameId": id, "reason": "remove" }),
- session_id: Some(session_id.clone()),
- });
+ for session_id in session_ids {
+ events.push(CdpEvent {
+ method: "Page.frameDetached".into(),
+ params: json!({ "frameId": id, "reason": "remove" }),
+ session_id: Some(session_id.clone()),
+ });
+ }
}
}
}
diff --git a/crates/obscura-cdp/tests/child_frame_tree.rs b/crates/obscura-cdp/tests/child_frame_tree.rs
index 53479914..5214865c 100644
--- a/crates/obscura-cdp/tests/child_frame_tree.rs
+++ b/crates/obscura-cdp/tests/child_frame_tree.rs
@@ -53,23 +53,55 @@ async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, session
resp.result.unwrap_or_else(|| json!({}))
}
+/// Gets a page and a session the way a real client does, rather than by
+/// inserting a session for a hand-made page: `Target.createTarget` then
+/// `Target.attachToTarget`, which is the only route Puppeteer and Playwright
+/// can take and therefore the only one worth asserting against.
+async fn attached_session(ctx: &mut CdpContext) -> String {
+ let created = dispatch(
+ &CdpRequest {
+ id: 900,
+ method: "Target.createTarget".to_string(),
+ params: json!({"url": "about:blank"}),
+ session_id: None,
+ },
+ ctx,
+ )
+ .await
+ .result
+ .expect("Target.createTarget produced no result");
+ let target_id = created["targetId"].as_str().expect("no targetId").to_string();
+
+ let attached = dispatch(
+ &CdpRequest {
+ id: 901,
+ method: "Target.attachToTarget".to_string(),
+ params: json!({"targetId": target_id, "flatten": true}),
+ session_id: None,
+ },
+ ctx,
+ )
+ .await
+ .result
+ .expect("Target.attachToTarget produced no result");
+ attached["sessionId"]
+ .as_str()
+ .expect("no sessionId")
+ .to_string()
+}
+
#[tokio::test(flavor = "current_thread")]
async fn get_frame_tree_reports_nested_child_frames() {
std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
let url = serve().await;
let mut ctx = CdpContext::new();
- let page_id = ctx.create_page();
- let session = "session-1";
- ctx.sessions.insert(session.to_string(), page_id);
+ let session = &attached_session(&mut ctx).await;
- cdp(
- &mut ctx,
- 1,
- "Page.navigate",
- json!({"url": url, "waitUntil": "load"}),
- session,
- )
- .await;
+ // Deliberately no `waitUntil`: that is what Puppeteer and Playwright send,
+ // and it resolves to DomContentLoaded rather than to load. Passing
+ // "load" here hid the frame build behind a readiness level no real client
+ // asks for, so the tree came back empty for every one of them.
+ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url}), session).await;
// Frames are built when the page settles, which is not part of the
// navigation itself.
cdp(&mut ctx, 2, "Runtime.evaluate", json!({"expression": "1"}), session).await;
@@ -100,18 +132,43 @@ async fn get_frame_tree_reports_nested_child_frames() {
assert_eq!(grandchild["frame"]["parentId"], child["frame"]["id"]);
// A client builds its frame list from the events, so the tree alone is not
- // enough. Attach must precede the navigation of the same frame.
+ // enough. They have to carry the session the client attached with, because
+ // a client discards anything addressed to a session it does not hold, and
+ // Target.createTarget leaves a second session on the same page.
let child_id = child["frame"]["id"].as_str().unwrap().to_string();
+ let page_id = ctx.sessions.get(session.as_str()).cloned().unwrap();
+ // Announcing to one arbitrary session of the page is what the ordering of a
+ // HashMap decides, so require every session on the page to be told. That
+ // makes the client's own session covered whichever one it is.
+ for (candidate, owner) in &ctx.sessions {
+ if owner != &page_id {
+ continue;
+ }
+ assert!(
+ ctx.pending_events.iter().any(|e| {
+ e.method == "Page.frameAttached"
+ && e.params["frameId"] == child_id
+ && e.session_id.as_deref() == Some(candidate.as_str())
+ }),
+ "session {candidate} on the page was never told the child frame attached"
+ );
+ }
+
+ let mine = |e: &obscura_cdp::types::CdpEvent| e.session_id.as_deref() == Some(session.as_str());
let attached = ctx
.pending_events
.iter()
- .position(|e| e.method == "Page.frameAttached" && e.params["frameId"] == child_id)
- .expect("no Page.frameAttached for the child frame");
+ .position(|e| {
+ e.method == "Page.frameAttached" && e.params["frameId"] == child_id && mine(e)
+ })
+ .expect("no Page.frameAttached for the child frame on the client's own session");
let navigated = ctx
.pending_events
.iter()
- .position(|e| e.method == "Page.frameNavigated" && e.params["frame"]["id"] == child_id)
- .expect("no Page.frameNavigated for the child frame");
+ .position(|e| {
+ e.method == "Page.frameNavigated" && e.params["frame"]["id"] == child_id && mine(e)
+ })
+ .expect("no Page.frameNavigated for the child frame on the client's own session");
assert!(
attached < navigated,
"frameAttached must come before frameNavigated"