The headless browser for AI agents and web scraping
fix(js): preserve promise rejection semantics
hongdeca82a3e2a5aa
diff --git a/crates/obscura-browser/tests/unhandled_rejection.rs b/crates/obscura-browser/tests/unhandled_rejection.rsnew file mode 100644index 00000000..2c3b4b2e--- /dev/null+++ b/crates/obscura-browser/tests/unhandled_rejection.rs@@ -0,0 +1,60 @@+use std::io::{Read, Write};+use std::sync::Arc;++use obscura_browser::{BrowserContext, Page};++fn spawn_page() -> String {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();++ std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = [0_u8; 1_024];+ let _ = stream.read(&mut request).unwrap();+ let body = r#"<!doctype html><html><body data-ready="false">+ <script>+ globalThis.__rejectionObserved = false;+ addEventListener('unhandledrejection', function (event) {+ globalThis.__rejectionObserved = event.reason.message === 'background failure';+ });+ Promise.reject(new Error('background failure'));+ setTimeout(function () {+ document.body.setAttribute('data-ready', 'true');+ }, 20);+ </script>+ </body></html>"#;+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len(),+ )+ .unwrap();+ });++ format!("http://{address}")+}++#[tokio::test(flavor = "current_thread")]+async fn rejected_background_promise_does_not_stop_the_page_event_loop() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let context = Arc::new(BrowserContext::with_storage_and_network(+ "unhandled-rejection".to_owned(),+ None,+ false,+ None,+ None,+ true,+ ));+ let mut page = Page::new("unhandled-rejection-page".to_owned(), context);+ page.navigate(&spawn_page()).await.unwrap();+ page.settle(200).await;++ assert_eq!(+ page.evaluate("globalThis.__rejectionObserved"),+ serde_json::json!(true),+ );+ assert_eq!(+ page.evaluate("document.body.getAttribute('data-ready')"),+ serde_json::json!("true"),+ );+}diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex f6381771..8d5851a6 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -9722,6 +9722,31 @@ globalThis.PromiseRejectionEvent = class PromiseRejectionEvent extends Event {};_markNative(globalThis.PromiseRejectionEvent);+Deno.core.setUnhandledPromiseRejectionHandler((promise, reason) => {+ const event = new PromiseRejectionEvent("unhandledrejection", {+ promise,+ reason,+ cancelable: true,+ });+ globalThis.dispatchEvent(event);+ if (typeof globalThis.onunhandledrejection === "function") {+ try { globalThis.onunhandledrejection.call(globalThis, event); }+ catch (error) { console.error(error); }+ }+ // Browsers report an unhandled rejection without terminating the page's+ // event loop. Returning true tells deno_core that the host delivered it.+ return true;+});++Deno.core.setHandledPromiseRejectionHandler((promise, reason) => {+ const event = new PromiseRejectionEvent("rejectionhandled", { promise, reason });+ globalThis.dispatchEvent(event);+ if (typeof globalThis.onrejectionhandled === "function") {+ try { globalThis.onrejectionhandled.call(globalThis, event); }+ catch (error) { console.error(error); }+ }+});+globalThis.StorageEvent = class StorageEvent extends Event {constructor(type, init = {}) {super(type, init);diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 8b2df06a..35f6076f 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -2142,7 +2142,11 @@ impl ObscuraJsRuntime {Err(payload) => {let message = panic_payload_message(payload.as_ref());let outcome = if message.contains("Module already evaluated") {- Ok(())+ self+ .runtime+ .get_module_namespace(module_id)+ .map(|_| ())+ .map_err(|error| format!("{} eval error: {}", what, error))} else {Err(format!("{} evaluation panicked: {}", what, message))};@@ -2166,7 +2170,11 @@ impl ObscuraJsRuntime {.await;let outcome = match outcome {- Ok(Ok(())) => Ok(()),+ Ok(Ok(())) => self+ .runtime+ .get_module_namespace(module_id)+ .map(|_| ())+ .map_err(|error| format!("{} eval error: {}", what, error)),Ok(Err(e)) => Err(format!("{} eval error: {}", what, e)),Err(_) => Err(format!("{} evaluation timed out after {}ms",@@ -17548,5 +17556,3 @@ mod tests {);}}--