The headless browser for AI agents and web scraping
fix(cdp): cancel pending loads and honor beforeunload
SGavrl361f15d68d44
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex bfa1d00f..c3ef9002 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -4774,6 +4774,14 @@ impl Page {.is_some_and(|js| js.has_pending_navigation())}+ /// Discard a queued document navigation and cancel retained resource loads.+ /// The CDP processor separately cancels its borrowed navigation future.+ pub fn stop_loading(&mut self) {+ self.take_pending_navigation();+ #[cfg(feature = "render")]+ if let Some(js) = &mut self.js { js.stop_render_resource_loading(); }+ }+pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {if let Some(js) = &self.js {js.take_pending_binding_calls()diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex f36649e6..ba2bc7f4 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -64,6 +64,7 @@ pub struct CdpContext {/// is announced once and a frame that goes away can be retracted.pub announced_frames: HashMap<String, Vec<String>>,pub pending_events: Vec<CdpEvent>,+ pub(crate) pending_beforeunload_close: HashMap<String, Option<String>>,#[cfg(feature = "render")]pub(crate) screencasts: HashMap<String, ScreencastState>,#[cfg(feature = "render")]@@ -178,6 +179,7 @@ impl CdpContext {nav_events_emitted: std::collections::HashSet::new(),announced_frames: HashMap::new(),pending_events: Vec::new(),+ pending_beforeunload_close: HashMap::new(),#[cfg(feature = "render")]screencasts: HashMap::new(),#[cfg(feature = "render")]@@ -331,6 +333,7 @@ impl CdpContext {}pub fn remove_page(&mut self, id: &str) {+ self.pending_beforeunload_close.remove(id);let removed_sessions: Vec<String> = self.sessions.iter()diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 54c1cab9..b969a826 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -1058,7 +1058,9 @@ pub fn emit_navigation_events(tracing::warn!("could not produce navigation screencast frame: {error}");}}- let mut phase3 = vec![+ let mut phase3 = if ctx.get_page(page_id).is_some_and(|page| page.lifecycle == obscura_browser::LifecycleState::Failed) {+ Vec::new()+ } else { vec![CdpEvent {method: "Page.lifecycleEvent".into(),params: json!({"frameId": frame_id, "loaderId": loader_id, "name": "DOMContentLoaded", "timestamp": ts}),@@ -1079,8 +1081,8 @@ pub fn emit_navigation_events(params: json!({"timestamp": ts}),session_id: es.clone(),},- ];- if reached_network_idle || matches!(wait_until, WaitUntil::Load | WaitUntil::DomContentLoaded) {+ ] };+ if !phase3.is_empty() && (reached_network_idle || matches!(wait_until, WaitUntil::Load | WaitUntil::DomContentLoaded)) {let idle_ts = timestamp();phase3.push(CdpEvent { method: "Page.lifecycleEvent".into(), params: json!({"frameId": frame_id, "loaderId": loader_id, "name": "networkIdle", "timestamp": idle_ts}), session_id: es.clone() });}@@ -1271,6 +1273,30 @@ fn network_loading_failed(}}+pub(crate) fn emit_aborted_navigation(+ ctx: &mut CdpContext, session_id: &Option<String>, frame_id: &str,+ loader_id: &str, url: &str, method: &str, page_id: &str,+) {+ let start = ctx.pending_events.len();+ let ts = timestamp();+ ctx.pending_events.push(CdpEvent {+ method: "Network.requestWillBeSent".into(), session_id: session_id.clone(),+ params: json!({"requestId": loader_id, "loaderId": loader_id, "documentURL": url,+ "request": {"url": url, "method": method, "headers": {}}, "timestamp": ts,+ "wallTime": ts, "initiator": {"type": "other"}, "type": "Document", "frameId": frame_id}),+ });+ ctx.pending_events.push(CdpEvent {+ method: "Network.loadingFailed".into(), session_id: session_id.clone(),+ params: json!({"requestId": loader_id, "timestamp": ts, "type": "Document",+ "errorText": "net::ERR_ABORTED", "canceled": true}),+ });+ ctx.pending_events.push(CdpEvent {+ method: "Page.frameStoppedLoading".into(), session_id: session_id.clone(),+ params: json!({"frameId": frame_id}),+ });+ fan_out_network_events(ctx, page_id, session_id, start);+}+/// Parse the `waitUntil` argument that Puppeteer/Playwright pass on/// `Page.navigate`.pub fn parse_wait_until(params: &Value) -> WaitUntil {@@ -1461,23 +1487,40 @@ pub async fn handle(do_navigate(¤t_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();+ let page = ctx.get_session_page(session_id).ok_or("No page for session")?;+ let target_id = page.id.clone();+ if ctx.pending_beforeunload_close.contains_key(&target_id) { return Ok(json!({})); }+ let confirmation = if page.has_js() {+ ctx.get_session_page_mut(session_id).ok_or("No page for session")?+ .evaluate("globalThis.__obscura_fireBeforeUnload()")+ .as_bool().ok_or("Could not run beforeunload handlers")?+ } else { false };+ if confirmation {+ let url = ctx.get_page(&target_id).ok_or("No page")?.url_string();+ ctx.pending_beforeunload_close.insert(target_id, session_id.clone());+ ctx.pending_events.push(CdpEvent {+ method: "Page.javascriptDialogOpening".into(), session_id: session_id.clone(),+ params: json!({"url": url, "type": "beforeunload", "message": "",+ "hasBrowserHandler": true, "defaultPrompt": ""}),+ });+ return Ok(json!({}));+ }crate::domains::target::close_target(ctx, &target_id);Ok(json!({}))}+ "handleJavaScriptDialog" => {+ let target_id = ctx.get_session_page(session_id).ok_or("No page for session")?.id.clone();+ let accept = params.get("accept").and_then(|value| value.as_bool()).ok_or("accept required")?;+ let owner = ctx.pending_beforeunload_close.remove(&target_id).ok_or("No dialog is showing")?;+ ctx.pending_events.push(CdpEvent {+ method: "Page.javascriptDialogClosed".into(), session_id: owner,+ params: json!({"result": accept, "userInput": ""}),+ });+ if accept { 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.+ ctx.get_session_page_mut(session_id).ok_or("No page for session")?.stop_loading();Ok(json!({}))}"getFrameTree" => {diff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rsindex 554d178d..28fda2b8 100644--- a/crates/obscura-cdp/src/domains/target.rs+++ b/crates/obscura-cdp/src/domains/target.rs@@ -318,11 +318,7 @@ 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.+/// Detach the target's sessions, announce destruction, and release its state.pub(crate) fn close_target(ctx: &mut CdpContext, target_id: &str) {let mut sessions = ctx.sessions.iter()diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex b1382a58..509c6ecd 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -1877,7 +1877,13 @@ async fn process_with_interception(let frame_id = page.frame_id.clone();let loader_id = format!("loader-{}", uuid::Uuid::new_v4());- let (nav_done_tx, mut nav_done_rx) = mpsc::channel::<(obscura_browser::Page, Result<(), String>)>(1);+ let previous_url = page.url.clone();+ let previous_lifecycle = page.lifecycle;+ let navigation_url = url_owned.clone();+ let navigation_method = nav_method.clone();+ let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();+ let mut cancel_tx = Some(cancel_tx);+ let (nav_done_tx, mut nav_done_rx) = mpsc::channel::<(obscura_browser::Page, Result<(), String>, bool)>(1);let nav_v8_lock = ctx.v8_lock.clone();tokio::task::spawn_local(async move {@@ -1891,20 +1897,25 @@ async fn process_with_interception(// must run BEFORE the page's own scripts (CDP contract). Hand them// to the page so navigate_single can inject them at the right point.page.set_preload_scripts(preload_scripts);- let result = if !send_command_response {- page.navigate_from_document(&url_owned, &nav_method, &nav_body).await- } else if nav_method == "POST" && !nav_body.is_empty() {- page.navigate_with_wait_post(&url_owned, wait_until, &nav_method, &nav_body).await- } else {- page.navigate_with_wait(&url_owned, wait_until).await- }- .map_err(|e| e.to_string());+ let (result, cancelled) = tokio::select! {+ result = async {+ if !send_command_response {+ page.navigate_from_document(&url_owned, &nav_method, &nav_body).await+ } else if nav_method == "POST" && !nav_body.is_empty() {+ page.navigate_with_wait_post(&url_owned, wait_until, &nav_method, &nav_body).await+ } else {+ page.navigate_with_wait(&url_owned, wait_until).await+ }+ } => (result.map_err(|e| e.to_string()), false),+ _ = cancel_rx => (Err("net::ERR_ABORTED".into()), true),+ };drop(_v8_guard);- let _ = nav_done_tx.send((page, result)).await;+ let _ = nav_done_tx.send((page, result, cancelled)).await;});let navigate_result: Result<(), String>;let page_back: Option<obscura_browser::Page>;+ let cancelled: bool;// Issue #19 follow-up (PR #36 maintainer's fetch-intercept repro):// While the spawned nav task is executing V8 (potentially parked on@@ -1930,9 +1941,10 @@ async fn process_with_interception(let has_irx = intercept_rx.is_some();tokio::select! {- Some((returned_page, result)) = nav_done_rx.recv() => {+ Some((returned_page, result, was_cancelled)) = nav_done_rx.recv() => {page_back = Some(returned_page);navigate_result = result;+ cancelled = was_cancelled;break;}Some(intercepted) = async {@@ -1961,6 +1973,22 @@ async fn process_with_interception(let _ = new_tx.send(json!({"__init": true, "pageId": pid, "sessionId": sid}).to_string());}ServerMessage::Cdp(msg) => {+ if let Ok(command) = serde_json::from_str::<CdpRequest>(&msg.text) {+ let same_page = command.session_id.as_ref()+ .and_then(|session| ctx.sessions.get(session)) == Some(&page_id);+ let stop = command.method == "Page.stopLoading" && same_page;+ let close = (command.method == "Page.close" && same_page)+ || (command.method == "Target.closeTarget"+ && command.params.get("targetId").and_then(|id| id.as_str()) == Some(page_id.as_str()));+ if stop || close {+ if let Some(cancel) = cancel_tx.take() { let _ = cancel.send(()); }+ if stop {+ let response = crate::types::CdpResponse::success(command.id, json!({}), command.session_id);+ if let Ok(json) = serde_json::to_string(&response) { let _ = msg.reply_tx.send(json); }+ continue;+ }+ }+ }if msg.text.contains("Fetch.continueRequest")|| msg.text.contains("Fetch.fulfillRequest")|| msg.text.contains("Fetch.failRequest")@@ -2005,6 +2033,19 @@ async fn process_with_interception(// (it drains `deferred` before pulling the next message off `rx`).let mut page = page_back.expect("navigation task should return the page");+ let committed = page.network_events.iter().any(|event| event.resource_type == "Document")+ || page.js.as_ref().is_some_and(|js| previous_url.as_ref().is_some_and(|url| js.document_url() != url.as_str()));+ if cancelled {+ page.stop_loading();+ if committed {+ page.lifecycle = obscura_browser::LifecycleState::Failed;+ page.push_history(page.url_string());+ } else {+ page.url = previous_url;+ page.lifecycle = previous_lifecycle;+ }+ intercepted_paused.retain(|_, resolver| !resolver.is_closed());+ }// Fold in network events for script-initiated requests (fetch/XHR/dynamic// resource) so they emit as Network.requestWillBeSent / responseReceived@@ -2017,14 +2058,19 @@ async fn process_with_interception(ctx.pages.push(page);- let response = match navigate_result {+ let response = if cancelled {+ crate::types::CdpResponse::success(req.id,+ if is_reload { json!({}) } else if committed { json!({"frameId": frame_id, "loaderId": loader_id}) }+ else { json!({"frameId": frame_id, "loaderId": loader_id, "errorText": "net::ERR_ABORTED"}) },+ req.session_id.clone())+ } else { match navigate_result {Ok(()) => crate::types::CdpResponse::success(req.id,if is_reload { json!({}) } else { json!({"frameId": frame_id, "loaderId": loader_id}) },req.session_id.clone(),),Err(e) => crate::types::CdpResponse::error(req.id, -32000, e, req.session_id.clone()),- };+ }};if send_command_response {if let Ok(json) = serde_json::to_string(&response) {@@ -2037,17 +2083,22 @@ async fn process_with_interception(// makes `page.goto()` resolve to a Response, and the #192 per-isolated-// world fresh context ids. Pushes to `ctx.pending_events`; we then drain// to the WS reply channel.- crate::domains::page::emit_navigation_events(- ctx,- &session_for_events,- &frame_id,- &loader_id,- &page_url,- &page_id_for_events,- &network_events,- wait_until,- reached_network_idle,- );+ if cancelled && !committed {+ crate::domains::page::emit_aborted_navigation(ctx, &session_for_events, &frame_id,+ &loader_id, &navigation_url, &navigation_method, &page_id_for_events);+ } else {+ crate::domains::page::emit_navigation_events(+ ctx,+ &session_for_events,+ &frame_id,+ &loader_id,+ &page_url,+ &page_id_for_events,+ &network_events,+ wait_until,+ reached_network_idle,+ );+ }for event in ctx.pending_events.drain(..) {if let Ok(json) = serde_json::to_string(&event) {let _ = reply_tx.send(json);@@ -3497,6 +3548,122 @@ mod tests {assert_navigation_intercept_reply_without_timer("continueRequest").await;}+ async fn assert_stop_loading_cancels_navigation(script: bool, method: &str) {+ use super::{process_cdp_message, process_with_interception, CdpMessage, ServerMessage};+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ tokio::task::LocalSet::new().run_until(async {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let (requested_tx, requested_rx) = tokio::sync::oneshot::channel();+ let fixture = tokio::task::spawn_local(async move {+ if script {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut buffer = [0; 2048];+ stream.read(&mut buffer).await.unwrap();+ let body = "<!doctype html><title>Partial</title><script src='/held.js'></script>";+ let response = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());+ stream.write_all(response.as_bytes()).await.unwrap();+ }+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut buffer = [0; 2048];+ assert!(stream.read(&mut buffer).await.unwrap() > 0);+ requested_tx.send(()).unwrap();+ // No response: cancellation must drop the pending HTTP request.+ assert_eq!(stream.read(&mut buffer).await.unwrap(), 0);+ });+ let context = obscura_browser::context::BrowserContext::with_storage_and_network(+ "stop-loading-test".into(), None, false, None, None, true,+ );+ let mut ctx = crate::dispatch::CdpContext::new_with_shared_context(std::sync::Arc::new(context));+ let page_id = ctx.create_page();+ let other_page = ctx.create_page();+ let session = format!("{page_id}-session");+ ctx.sessions.insert(session.clone(), page_id.clone());+ ctx.sessions.insert("raw-session".into(), page_id.clone());+ ctx.sessions.insert("other-session".into(), other_page.clone());+ ctx.get_page_mut(&page_id).unwrap().resume_js();+ let original_url = ctx.pages[0].url_string();+ let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();+ let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();+ let navigation_reply = reply_tx.clone();+ let url = format!("http://{address}/");+ let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session,+ "params": {"url": url, "waitUntil": "load"}}).to_string();+ let navigation = tokio::task::spawn_local(async move {+ let mut paused = HashMap::new();+ let mut deferred = std::collections::VecDeque::new();+ process_with_interception(&command, &mut ctx, &navigation_reply,+ &mut server_rx, &mut None, &mut paused, &mut deferred, true).await;+ (ctx, paused, deferred)+ });+ tokio::time::timeout(std::time::Duration::from_secs(5), requested_rx)+ .await.expect("fixture request").unwrap();+ for (id, session) in [(2, "other-session"), (3, "raw-session")] {+ server_tx.send(ServerMessage::Cdp(CdpMessage {+ text: json!({"id": id, "method": if id == 2 { "Page.stopLoading" } else { method },+ "sessionId": session, "params": {"targetId": page_id}}).to_string(),+ reply_tx: reply_tx.clone(),+ })).unwrap();+ }+ let (mut ctx, paused, deferred) = tokio::time::timeout(std::time::Duration::from_secs(2), navigation)+ .await.expect("Page.stopLoading must cancel without waiting for the HTTP timeout").unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(2), fixture)+ .await.expect("pending request socket must close").unwrap();+ assert!(paused.is_empty());+ assert_eq!(deferred.len(), if method == "Page.stopLoading" { 1 } else { 2 },+ "another target's stop must not cancel this navigation");+ for message in deferred {+ if let ServerMessage::Cdp(message) = message {+ process_cdp_message(&message.text, &mut ctx, &message.reply_tx).await;+ }+ }+ let replies: Vec<serde_json::Value> = std::iter::from_fn(|| reply_rx.try_recv().ok())+ .map(|text| serde_json::from_str(&text).unwrap()).collect();+ assert_eq!(replies.iter().filter(|reply| reply["id"] == 3).count(), 1);+ let stopped = replies.iter().find(|reply| reply["id"] == 3).unwrap();+ assert!(stopped.get("error").is_none(), "{stopped}");+ let aborted = replies.iter().find(|reply| reply["id"] == 1).unwrap();+ assert!(aborted.get("error").is_none(), "{aborted}");+ if !script {+ assert_eq!(aborted["result"]["errorText"], "net::ERR_ABORTED", "{aborted}");+ }+ assert!(!replies.iter().any(|reply| reply["method"] == "Page.loadEventFired"));+ assert!(replies.iter().any(|reply| reply["method"] == "Page.frameStoppedLoading"));+ assert!(ctx.get_page(&other_page).is_some());+ if method != "Page.stopLoading" {+ assert!(ctx.get_page(&page_id).is_none());+ assert_eq!(replies.iter().filter(|reply| reply["method"] == "Target.targetDestroyed").count(), 1);+ return;+ }+ assert_eq!(ctx.get_page(&page_id).unwrap().url_string(), if script { url } else { original_url });+ assert_eq!(ctx.get_page_mut(&page_id).unwrap().evaluate("1 + 2").as_f64(), Some(3.0));+ process_cdp_message(&json!({"id": 4, "method": "Page.navigate", "sessionId": session,+ "params": {"url": "about:blank"}}).to_string(), &mut ctx, &reply_tx).await;+ assert_eq!(ctx.get_page(&page_id).unwrap().url_string(), "about:blank");+ }).await;+ }++ #[tokio::test(flavor = "current_thread")]+ async fn stop_loading_cancels_a_held_document_request() {+ assert_stop_loading_cancels_navigation(false, "Page.stopLoading").await;+ }++ #[tokio::test(flavor = "current_thread")]+ async fn stop_loading_cancels_a_held_parser_script_request() {+ assert_stop_loading_cancels_navigation(true, "Page.stopLoading").await;+ }++ #[tokio::test(flavor = "current_thread")]+ async fn stop_loading_cancels_for_page_close() {+ assert_stop_loading_cancels_navigation(false, "Page.close").await;+ }++ #[tokio::test(flavor = "current_thread")]+ async fn stop_loading_cancels_for_target_close() {+ assert_stop_loading_cancels_navigation(false, "Target.closeTarget").await;+ }+#[tokio::test(flavor = "current_thread")]async fn navigation_intercept_fulfill_has_no_timer_delay() {assert_navigation_intercept_reply_without_timer("fulfillRequest").await;diff --git a/crates/obscura-cdp/tests/page_close_destroys_target.rs b/crates/obscura-cdp/tests/page_close_destroys_target.rsindex 6a668ef2..de524687 100644--- a/crates/obscura-cdp/tests/page_close_destroys_target.rs+++ b/crates/obscura-cdp/tests/page_close_destroys_target.rs@@ -80,3 +80,137 @@ async fn stop_loading_answers_success_like_chromium() {assert_eq!(result, json!({}), "go-rod calls this before every navigate");}++#[tokio::test(flavor = "current_thread")]+async fn page_close_runs_beforeunload_and_waits_for_dialog_resolution() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session = "close-confirmation";+ ctx.sessions.insert(session.into(), page_id.clone());+ cdp(&mut ctx, 1, "Runtime.evaluate", json!({"expression":+ "globalThis.closeAttempts = 0; addEventListener('beforeunload', e => { closeAttempts++; e.preventDefault(); });"}), session).await;+ cdp(&mut ctx, 6, "Input.dispatchKeyEvent", json!({"type": "keyDown", "key": "a", "code": "KeyA"}), session).await;+ cdp(&mut ctx, 2, "Page.close", json!({}), session).await;+ let page = ctx.get_page_mut(&page_id).expect("a confirmation must not destroy the target");+ assert_eq!(page.evaluate("closeAttempts").as_f64(), Some(1.0));+ let opening = emitted(&ctx, "Page.javascriptDialogOpening");+ assert_eq!(opening.len(), 1);+ assert_eq!(opening[0]["type"], "beforeunload");+ assert!(emitted(&ctx, "Target.targetDestroyed").is_empty());++ cdp(&mut ctx, 3, "Page.handleJavaScriptDialog", json!({"accept": false}), session).await;+ assert!(ctx.get_page(&page_id).is_some(), "dismissing must keep the page");+ assert_eq!(emitted(&ctx, "Page.javascriptDialogClosed")[0]["result"], false);+ cdp(&mut ctx, 4, "Page.close", json!({}), session).await;+ assert_eq!(ctx.get_page_mut(&page_id).unwrap().evaluate("closeAttempts").as_f64(), Some(2.0));+ cdp(&mut ctx, 5, "Page.handleJavaScriptDialog", json!({"accept": true}), session).await;+ assert!(ctx.get_page(&page_id).is_none());+ assert_eq!(emitted(&ctx, "Target.targetDestroyed").len(), 1);+ assert_eq!(emitted(&ctx, "Page.javascriptDialogClosed")[1]["result"], true);+}++#[tokio::test(flavor = "current_thread")]+async fn page_close_does_not_prompt_without_user_activation() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session = "close-no-activation";+ ctx.sessions.insert(session.into(), page_id.clone());+ cdp(&mut ctx, 1, "Runtime.evaluate", json!({"expression":+ "addEventListener('beforeunload', e => e.preventDefault());"}), session).await;+ cdp(&mut ctx, 2, "Page.close", json!({}), session).await;+ assert!(ctx.get_page(&page_id).is_none());+ assert!(emitted(&ctx, "Page.javascriptDialogOpening").is_empty());+}++#[tokio::test(flavor = "current_thread")]+async fn page_close_honors_the_beforeunload_handler_return_value() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session = "close-handler-return";+ ctx.sessions.insert(session.into(), page_id.clone());+ cdp(&mut ctx, 1, "Runtime.evaluate", json!({"expression":+ "onbeforeunload = e => { if (!e.isTrusted || !e.cancelable) throw new Error('not native'); return 'Unsaved'; };"}), session).await;+ cdp(&mut ctx, 2, "Input.dispatchMouseEvent", json!({"type": "mousePressed", "x": 1, "y": 1, "button": "left"}), session).await;+ cdp(&mut ctx, 3, "Page.close", json!({}), session).await;+ assert!(ctx.get_page(&page_id).is_some());+ assert_eq!(emitted(&ctx, "Page.javascriptDialogOpening").len(), 1);+ cdp(&mut ctx, 4, "Target.closeTarget", json!({"targetId": page_id}), session).await;+ assert!(ctx.get_page(&page_id).is_none(), "force-close must bypass confirmation");+}++#[tokio::test(flavor = "current_thread")]+async fn page_close_honors_an_empty_beforeunload_handler_return_value() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session = "close-empty-return";+ ctx.sessions.insert(session.into(), page_id.clone());+ let synthetic = cdp(&mut ctx, 0, "Runtime.evaluate", json!({"expression": "globalThis.onbeforeunload = () => false; globalThis.dispatchEvent(new Event('beforeunload', {cancelable: true}))", "returnByValue": true}), session).await;+ assert_eq!(synthetic["result"]["value"], false, "generic events must keep ordinary false-return cancellation");+ cdp(&mut ctx, 1, "Runtime.evaluate", json!({"expression": "onbeforeunload = () => '';"}), session).await;+ cdp(&mut ctx, 2, "Input.dispatchKeyEvent", json!({"type": "keyDown", "key": "a", "code": "KeyA"}), session).await;+ cdp(&mut ctx, 3, "Page.close", json!({}), session).await;+ assert!(ctx.get_page(&page_id).is_some(), "every non-null handler return requests confirmation");+ assert_eq!(emitted(&ctx, "Page.javascriptDialogOpening").len(), 1);+}++#[cfg(feature = "render")]+async fn assert_stop_loading_cancels_images(native: bool) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ tokio::task::LocalSet::new().run_until(async {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let (requested_tx, requested_rx) = tokio::sync::oneshot::channel();+ let fixture = tokio::task::spawn_local(async move {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut buffer = [0; 2048];+ stream.read(&mut buffer).await.unwrap();+ let body = if native { "<!doctype html><title>Images</title>" }+ else { "<!doctype html><img src='/held.png'>" };+ stream.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();+ drop(stream);+ let (mut stream, _) = listener.accept().await.unwrap();+ assert!(stream.read(&mut buffer).await.unwrap() > 0);+ requested_tx.send(()).unwrap();+ assert_eq!(stream.read(&mut buffer).await.unwrap(), 0, "stop must close the HTTP request");+ });+ let context = obscura_browser::context::BrowserContext::with_storage_and_network(+ "stop-resources-test".into(), None, false, None, None, true,+ );+ let mut ctx = CdpContext::new_with_shared_context(std::sync::Arc::new(context));+ let page_id = ctx.create_page();+ let session = "stop-resources";+ ctx.sessions.insert(session.into(), page_id.clone());+ cdp(&mut ctx, 1, "Page.navigate", json!({"url": format!("http://{address}/"), "waitUntil": "domcontentloaded"}), session).await;+ if native {+ cdp(&mut ctx, 10, "Runtime.evaluate", json!({"expression": "globalThis.imageErrors = 0; globalThis.images = [new Image(), new Image()]; for (const image of images) { image.src = '/held.png'; image.decode().catch(() => imageErrors++); }"}), session).await;+ ctx.get_page_mut(&page_id).unwrap().js.as_mut().unwrap().run_event_loop_bounded(10).await.unwrap();+ }+ ctx.get_page_mut(&page_id).unwrap().queue_pending_render_resources();+ tokio::time::timeout(std::time::Duration::from_secs(5), requested_rx).await.expect("image request").unwrap();+ cdp(&mut ctx, 2, "Page.stopLoading", json!({}), session).await;+ ctx.get_page_mut(&page_id).unwrap().js.as_mut().unwrap().run_event_loop_bounded(10).await.unwrap();+ let page = ctx.get_page_mut(&page_id).unwrap();+ if native { assert_eq!(page.evaluate("imageErrors").as_f64(), Some(2.0)); }+ assert!(!page.has_pending_render_resources(), "stop must cancel pending image loads");+ page.queue_pending_render_resources();+ assert!(!page.has_pending_render_resources(), "the autonomous pump must not restart canceled loads");+ assert!(page.js.as_ref().unwrap().render_resource_is_known(&format!("http://{address}/held.png")));+ tokio::time::timeout(std::time::Duration::from_secs(2), fixture).await.expect("image socket closes").unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(2100)).await;+ let page = ctx.get_page_mut(&page_id).unwrap();+ page.queue_pending_render_resources();+ assert!(!page.has_pending_render_resources(), "stopped loads must not restart after the failure retry window");+ }).await;+}++#[cfg(feature = "render")]+#[tokio::test(flavor = "current_thread")]+async fn stop_loading_cancels_background_resources_without_restarting_them() {+ assert_stop_loading_cancels_images(false).await;+}++#[cfg(feature = "render")]+#[tokio::test(flavor = "current_thread")]+async fn stop_loading_cancels_native_image_requests_and_decode_waiters() {+ assert_stop_loading_cancels_images(true).await;+}diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex c6eff996..ec3d3bc1 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -21,7 +21,7 @@ const __obscuraCore = globalThis.Deno.core;'__obscura_errors', '__obscura_init', '__obscura_hide_list','__obscura_objects', '__obscura_oid', '__obscura_ua','__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version',- '__obscura_stealth', '__obscura_markTrusted', '__obscura_core_handoff',+ '__obscura_stealth', '__obscura_markTrusted', '__obscura_fireBeforeUnload', '__obscura_core_handoff',// Created by later evaluation, input and emulation paths. Register them// before the snapshot hide list is captured, just like the other internals.'__obscura_await_rejected', '__obscura_click_target',@@ -2024,7 +2024,13 @@ function _eventTargetDispatch(target, event) {const eventHandler = target === globalThis ? target['on' + event.type] : null;if (typeof eventHandler === 'function') {try {- if (eventHandler.call(target, event) === false) event.preventDefault();+ const result = eventHandler.call(target, event);+ if (event.type === 'beforeunload' && _beforeUnloadValues.has(event)) {+ if (result != null) {+ event.preventDefault();+ if (event.returnValue === '') event.returnValue = result;+ }+ } else if (result === false) event.preventDefault();} catch (error) {console.error(error);}@@ -10693,7 +10699,20 @@ globalThis.DOMException = (function () {// obscura's CDP input pipeline marks its synthetic events via the// non-enumerable __obscura_markTrusted helper.const _trustedEvents = new WeakSet();-globalThis.__obscura_markTrusted = function(ev) { try { if (ev) _trustedEvents.add(ev); } catch (_e) {} return ev; };+let _hasStickyActivation = false;+globalThis.__obscura_markTrusted = function(ev) {+ try {+ if (ev) {+ _trustedEvents.add(ev);+ if ((ev.type === 'keydown' && ev.key !== 'Escape') || ev.type === 'mousedown'+ || (ev.type === 'pointerdown' && ev.pointerType === 'mouse')+ || (ev.type === 'pointerup' && ev.pointerType !== 'mouse') || ev.type === 'touchend') {+ _hasStickyActivation = true;+ }+ }+ } catch (_e) {}+ return ev;+};// Write value/checked through the element's *prototype* accessor, skipping any// per-instance property a framework layered on top. React (and Preact/Vue)@@ -10771,6 +10790,28 @@ globalThis.Event = class Event {return path;}};++const _beforeUnloadValues = new WeakMap();+globalThis.BeforeUnloadEvent = class BeforeUnloadEvent extends Event {+ constructor() { throw new TypeError('Illegal constructor'); }+ get returnValue() {+ if (!_beforeUnloadValues.has(this)) throw new TypeError('Illegal invocation');+ return _beforeUnloadValues.get(this);+ }+ set returnValue(value) {+ if (!_beforeUnloadValues.has(this)) throw new TypeError('Illegal invocation');+ _beforeUnloadValues.set(this, String(value));+ }+};+globalThis.__obscura_fireBeforeUnload = function() {+ const event = new Event('beforeunload', { cancelable: true });+ _beforeUnloadValues.set(event, '');+ Object.setPrototypeOf(event, BeforeUnloadEvent.prototype);+ globalThis.__obscura_markTrusted(event);+ const allowed = globalThis.dispatchEvent(event);+ return _hasStickyActivation && (!allowed || event.returnValue !== '');+};+_markNative(BeforeUnloadEvent);_markNative(Event);globalThis.CustomEvent = class extends Event {constructor(t,o={}) { if (arguments.length < 1) throw new TypeError("Failed to construct 'CustomEvent': 1 argument required, but only 0 present."); super(t,o);this.detail=o.detail!==undefined?o.detail:null; }diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 7b6a21bd..bfc7aca6 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -285,12 +285,13 @@ pub struct ObscuraState {/// relayout of the same document reuses it without refetching.#[cfg(feature = "render")]pub render_resources: obscura_render::RenderResourceCache,- /// Waiters sharing an asynchronous HTMLImageElement request. The key keeps+ /// Cancellation handle and waiters sharing an HTMLImageElement request. The key keeps/// navigation identity and request credentials separate so neither stale/// pages nor incompatible CORS profiles share a completion.#[cfg(feature = "render")]pub render_image_in_flight:- HashMap<(u64, String, ImageRequestProfile), Vec<tokio::sync::oneshot::Sender<()>>>,+ HashMap<(u64, String, ImageRequestProfile),+ (tokio::sync::oneshot::Sender<()>, Vec<tokio::sync::oneshot::Sender<()>>)>,/// Page-transport loads for resources that cache-only layout or paint/// missed. The owning page fetches them and sends the outcome here; the/// runtime applies results at its own event-loop turns and at every@@ -7822,16 +7823,17 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> String// Different CORS/credential profiles do not share an in-flight response.let request_key = (document_generation, selected_url.clone(), request_profile);- let follower = {+ let (follower, cancel_rx) = {let mut gs = shared.borrow_mut();- if let Some(waiters) = gs.render_image_in_flight.get_mut(&request_key) {+ if let Some((_, waiters)) = gs.render_image_in_flight.get_mut(&request_key) {let (sender, receiver) = tokio::sync::oneshot::channel();waiters.push(sender);- Some(receiver)+ (Some(receiver), None)} else {+ let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();gs.render_image_in_flight- .insert(request_key.clone(), Vec::new());- None+ .insert(request_key.clone(), (cancel_tx, Vec::new()));+ (None, Some(cancel_rx))}};if let Some(receiver) = follower {@@ -7844,6 +7846,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringrequest_profile,);}+ let cancel_rx = cancel_rx.expect("image request leader owns cancellation");struct PageImageInFlightGuard(Arc<std::sync::atomic::AtomicU32>);impl Drop for PageImageInFlightGuard {@@ -7855,7 +7858,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringlet _page_in_flight = PageImageInFlightGuard(page_in_flight);let parsed_url = url::Url::parse(&selected_url).ok();- let response = if blocked || parsed_url.is_none() {+ let fetch = async { if blocked || parsed_url.is_none() {None} else {let parsed_url = parsed_url.as_ref().unwrap();@@ -7892,6 +7895,10 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> String.await.ok()}+ } };+ let response = tokio::select! {+ response = fetch => response,+ _ = cancel_rx => None,};let bytes = response.and_then(|response| {(200..300)@@ -7900,7 +7907,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> String});let waiters = {let mut gs = shared.borrow_mut();- if gs.document_generation == document_generation {+ if gs.document_generation == document_generation && gs.render_image_in_flight.contains_key(&request_key) {match bytes {Some(bytes) => {if obscura_render::image_intrinsic_dimensions(&bytes).is_some() {@@ -7926,6 +7933,7 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> String}gs.render_image_in_flight.remove(&request_key)+ .map(|(_, waiters)| waiters).unwrap_or_default()};for waiter in waiters {diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 38838d10..ca63715c 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1253,6 +1253,10 @@ impl ObscuraJsRuntime {}}+ pub fn document_url(&self) -> String {+ self.state.borrow().url.clone()+ }+/// Set the document's character encoding (WHATWG canonical name). Backs/// `document.characterSet` and the `<a>`/`<area>` URL query encoding/// override for legacy-charset documents.@@ -2092,6 +2096,29 @@ impl ObscuraJsRuntime {state.render_resource_rx = rx;}+ /// Cancel this document's current loads without letting the next render+ /// turn rediscover and restart them. Future new URLs can still load.+ #[cfg(feature = "render")]+ pub fn stop_render_resource_loading(&mut self) {+ self.service_render_resources();+ let (pending, backlog, queued, images) = {+ let mut state = self.state.borrow_mut();+ (std::mem::take(&mut state.render_resource_in_flight),+ std::mem::take(&mut state.render_resource_backlog),+ state.render_resources.take_sync_misses(),+ std::mem::take(&mut state.render_image_in_flight))+ };+ self.abandon_render_resources();+ let mut state = self.state.borrow_mut();+ for (url, profile, _) in pending.into_iter().chain(backlog).chain(queued) {+ state.render_resources.stop_resource(&url, profile);+ }+ for ((_, url, profile), (cancel, _)) in images {+ state.render_resources.stop_resource(&url, Some(profile));+ let _ = cancel.send(());+ }+ }+/// Whether a page transport (plain or stealth client) is installed.#[cfg(feature = "render")]pub fn has_page_transport(&self) -> bool {diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex 44c2f53c..1cc00704 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -162,6 +162,8 @@ struct CachedRasterPaint {/// Successful bytes use `Arc` so consumers never clone an image/font body.pub struct RenderResourceCache {entries: HashMap<String, CachedResource>,+ // Cancellation belongs to the document, not the retryable byte cache.+ stopped: HashSet<String>,order: VecDeque<String>,retained_bytes: usize,raster_paints: VecDeque<CachedRasterPaint>,@@ -209,6 +211,7 @@ impl RenderResourceCache {) -> Self {Self {entries: HashMap::new(),+ stopped: HashSet::new(),order: VecDeque::new(),retained_bytes: 0,raster_paints: VecDeque::new(),@@ -285,7 +288,9 @@ impl RenderResourceCache {}pub fn has_live_outcome(&self, url: &str) -> bool {- match self.entries.get(&network_resource_url(url)) {+ let key = network_resource_url(url);+ if self.stopped.contains(&key) { return true; }+ match self.entries.get(&key) {Some(CachedResource::Bytes { .. }) => true,Some(CachedResource::Missing(at)) => at.elapsed() < MISSING_RESOURCE_RETRY_AFTER,None => false,@@ -336,10 +341,22 @@ impl RenderResourceCache {/// Seed already-shared bytes without copying a complete response body.pub fn seed_shared(&mut self, url: String, bytes: Arc<[u8]>) {let url = network_resource_url(&url);+ self.stopped.remove(&url);self.remove(&url);self.insert_bytes(url, bytes);}+ /// Keep a canceled request stopped until this document's cache is replaced.+ pub fn stop_resource(&mut self, url: &str, profile: Option<ImageRequestProfile>) {+ let key = match profile {+ Some(profile) => image_resource_key(url, profile),+ None => network_resource_url(url),+ };+ if self.has_cached_bytes(&key) { return; }+ self.remove(&key);+ self.stopped.insert(key);+ }+/// Retain a page-transport failure so capture does not immediately repeat/// the same slow request through the renderer's compatibility loader.pub fn seed_missing(&mut self, url: String) {@@ -385,7 +402,9 @@ impl RenderResourceCache {.map(|(width, height)| (resolved_url, width, height)),);}- match self.entries.get(&network_resource_url(&resolved_url)) {+ let key = network_resource_url(&resolved_url);+ if self.stopped.contains(&key) { return Some(None); }+ match self.entries.get(&key) {Some(entry @ CachedResource::Bytes { .. }) => Some(entry.image_intrinsic().and_then(crate::ReplacedIntrinsic::natural_size).map(|(width, height)| (resolved_url, width, height)),@@ -408,6 +427,7 @@ impl RenderResourceCache {return self.cached_image_metadata(&resolved_url, None);}let key = image_resource_key(&resolved_url, profile);+ if self.stopped.contains(&key) { return Some(None); }match self.entries.get(&key) {Some(entry @ CachedResource::Bytes { .. }) => Some(entry.image_intrinsic().and_then(crate::ReplacedIntrinsic::natural_size)@@ -525,6 +545,7 @@ impl RenderResourceCache {fn get_or_load(&mut self, url: &str, is_font: bool) -> Option<Arc<[u8]>> {let url = network_resource_url(url);+ if self.stopped.contains(&url) { return None; }if let Some(entry) = self.entries.get(&url) {match entry {CachedResource::Bytes { bytes, .. } => return Some(Arc::clone(bytes)),@@ -555,6 +576,7 @@ impl RenderResourceCache {fn get_or_load_image(&mut self, url: &str, profile: ImageRequestProfile) -> Option<Arc<[u8]>> {let key = image_resource_key(url, profile);+ if self.stopped.contains(&key) { return None; }if let Some(entry) = self.entries.get(&key) {match entry {CachedResource::Bytes { bytes, .. } => return Some(Arc::clone(bytes)),@@ -13853,6 +13875,43 @@ mod tests {Arc::from(encoded.into_inner())}+ #[test]+ fn stopped_resources_survive_cache_eviction_and_preserve_request_profiles() {+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let loader_calls = calls.clone();+ let mut cache = RenderResourceCache::with_loader_and_limits(move |_url: &str| {+ loader_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ None+ }, 1, 4096);+ let url = "https://example.test/image.png";+ cache.stop_resource(url, Some(ImageRequestProfile::CorsInclude));+ assert!(cache.has_live_image_outcome(url, ImageRequestProfile::CorsInclude));+ assert!(!cache.has_live_image_outcome(url, ImageRequestProfile::NoCorsInclude));+ cache.seed_shared(url.to_owned(), raster_cache_fixture());+ assert!(cache.get_or_load_image(url, ImageRequestProfile::NoCorsInclude).is_some());+ assert!(cache.get_or_load_image(url, ImageRequestProfile::CorsInclude).is_none());+ cache.stop_resource(url, None);+ assert!(cache.get_or_load_image(url, ImageRequestProfile::NoCorsInclude).is_some(),+ "canceling a duplicate request must preserve already-loaded bytes");+ cache.seed_shared("https://example.test/other.png".to_owned(), raster_cache_fixture());+ cache.stop_resource(url, None);+ assert!(cache.has_live_outcome(url));+ assert_eq!(cache.cached_image_metadata(url, None), Some(None));+ assert!(cache.get_or_load(url, true).is_none());+ assert!(cache.get_or_load_image(url, ImageRequestProfile::CorsInclude).is_none());+ cache.set_sync_loading_enabled(false);+ assert!(cache.get_or_load_image(url, ImageRequestProfile::NoCorsInclude).is_none());+ assert!(cache.take_sync_misses().is_empty());+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);+ let new_url = "https://example.test/new.png";+ assert!(cache.get_or_load(new_url, false).is_none());+ assert_eq!(cache.take_sync_misses(), vec![(new_url.to_owned(), None, false)]);+ cache.seed_shared(url.to_owned(), raster_cache_fixture());+ assert!(cache.get_or_load_image(url, ImageRequestProfile::NoCorsInclude).is_some());+ assert_eq!(cache.retained_entry_count(), 1);+ assert!(!RenderResourceCache::default().has_live_outcome(url));+ }+#[test]fn cached_raster_relative_urls_preserve_request_profiles_and_pixels() {let url = "https://example.test/images/image.png";diff --git a/docs/Use-with-Puppeteer.md b/docs/Use-with-Puppeteer.mdindex 24f56d02..d6e02b5b 100644--- a/docs/Use-with-Puppeteer.md+++ b/docs/Use-with-Puppeteer.md@@ -167,6 +167,21 @@ Frames are activity-driven page captures, not fixed-rate desktop video.await browser.disconnect(); // leaves obscura serve running```+## Page lifecycle++`Page.stopLoading` cancels an in-flight document or parser-resource request,+clears queued document navigation, and leaves the target usable. Rendering+builds also cancel pending image/font loads, including `Image`/`decode()`+requests, without restarting those URLs on the next render turn. Already-loaded+resources are preserved. Ordinary JavaScript `fetch()` calls are not canceled.++`Page.close` runs the top-level document's `beforeunload` handlers. A document+activated through native input can request confirmation, reported through+`Page.javascriptDialogOpening` with type `beforeunload`. Use+`Page.handleJavaScriptDialog` to accept or dismiss it. `Target.closeTarget`+remains a force-close path. Other dialog types and child-frame unload hooks+are not implemented by this change.+## Current limits- Some device emulation, service-worker, native media, long-tail CSS, and