Skip to content

The headless browser for AI agents and web scraping

fix(cdp): emit runtime console and exception events

lisa0314b7ad0c231137
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index e1aa4ae6..4ed99b88 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -282,6 +282,10 @@ pub struct Page {
// contract. Includes `Runtime.addBinding` shims so puppeteer's
// `exposeFunction` bindings exist before inline `<script>` tags execute.
preload_scripts: Vec<String>,
+ /// Whether at least one attached CDP session enabled the Runtime domain.
+ /// Page-owned so the subscription survives replacement of the JS runtime
+ /// during navigation.
+ runtime_events_enabled: std::cell::Cell<bool>,
/// Document-owned HTML script preparation flags saved while the V8 realm
/// is suspended for CDP/MCP tab switching. These are restored only when
/// the same surviving DomTree is resumed; navigation clears them.
@@ -932,6 +936,7 @@ impl Page {
blocked_url_patterns: Vec::new(),
intercept_tx: None,
preload_scripts: Vec::new(),
+ runtime_events_enabled: std::cell::Cell::new(false),
suspended_started_script_ids: Vec::new(),
callbacks: Arc::new(CallbackRegistry::new()),
#[cfg(feature = "stealth")]
@@ -1474,6 +1479,7 @@ impl Page {
// runtime does not exist yet, so the new runtime would otherwise start
// with interception disabled and op_fetch_url would never intercept.
rt.set_intercept_enabled(self.intercept_enabled);
+ rt.set_runtime_events_enabled(self.runtime_events_enabled.get());
if let Some(dom) = self.dom.take() {
rt.set_dom(dom);
@@ -3998,6 +4004,21 @@ impl Page {
}
}
+ pub fn take_pending_runtime_events(&mut self) -> Vec<obscura_js::ops::RuntimeEvent> {
+ if let Some(js) = &mut self.js {
+ js.take_pending_runtime_events()
+ } else {
+ Vec::new()
+ }
+ }
+
+ pub fn set_runtime_events_enabled(&self, enabled: bool) {
+ self.runtime_events_enabled.set(enabled);
+ if let Some(js) = &self.js {
+ js.set_runtime_events_enabled(enabled);
+ }
+ }
+
pub fn set_preload_scripts(&mut self, scripts: Vec<String>) {
self.preload_scripts = scripts;
}
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index 1e93f02a..0007a1ee 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -65,6 +65,9 @@ pub struct CdpContext {
// that registered the name rather than to whichever session of the page
// happens to come first out of a HashMap.
pub binding_sessions: HashMap<String, Vec<String>>, // binding name -> session ids
+ /// Sessions that called Runtime.enable. Console and exception events are
+ /// page-scoped but only delivered to these subscribers.
+ pub runtime_enabled_sessions: HashSet<String>,
// World names registered via Page.createIsolatedWorld. After every
// navigation Obscura clears execution contexts (via
// Runtime.executionContextsCleared) and must re-emit a
@@ -177,6 +180,7 @@ impl CdpContext {
target_session_counter: 0,
preload_scripts: Vec::new(),
binding_sessions: HashMap::new(),
+ runtime_enabled_sessions: HashSet::new(),
preload_counter: 0,
fetch_intercept: FetchInterceptState::new(),
intercept_tx: None,
@@ -294,22 +298,36 @@ impl CdpContext {
self.pages.iter_mut().find(|p| p.id == id)
}
+ pub(crate) fn refresh_runtime_event_collection(&self, page_id: &str) {
+ let enabled = self.runtime_enabled_sessions.iter().any(|session_id| {
+ self.sessions
+ .get(session_id)
+ .is_some_and(|owner| owner == page_id)
+ });
+ if let Some(page) = self.get_page(page_id) {
+ page.set_runtime_events_enabled(enabled);
+ }
+ }
+
pub fn remove_page(&mut self, id: &str) {
+ let removed_sessions: Vec<String> = self
+ .sessions
+ .iter()
+ .filter(|(_, page_id)| page_id.as_str() == id)
+ .map(|(session_id, _)| session_id.clone())
+ .collect();
self.pages.retain(|p| p.id != id);
self.current_loader_ids.remove(id);
self.announced_frames.remove(id);
#[cfg(feature = "render")]
{
- let removed: Vec<String> = self
- .sessions
- .iter()
- .filter(|(_, page_id)| page_id.as_str() == id)
- .map(|(session_id, _)| session_id.clone())
- .collect();
- for session_id in removed {
- self.screencasts.remove(&session_id);
+ for session_id in &removed_sessions {
+ self.screencasts.remove(session_id);
}
}
+ for session_id in &removed_sessions {
+ self.runtime_enabled_sessions.remove(session_id);
+ }
self.sessions.retain(|_, v| v != id);
}
@@ -547,6 +565,7 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
}
}
+ drain_runtime_events(ctx);
drain_binding_calls(ctx);
drain_frame_events(ctx);
@@ -559,6 +578,84 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
}
}
+pub(crate) fn drain_runtime_events(ctx: &mut CdpContext) {
+ let mut page_to_sessions: HashMap<&str, Vec<&str>> = HashMap::new();
+ for session_id in &ctx.runtime_enabled_sessions {
+ if let Some(page_id) = ctx.sessions.get(session_id) {
+ page_to_sessions
+ .entry(page_id.as_str())
+ .or_default()
+ .push(session_id.as_str());
+ }
+ }
+ for sessions in page_to_sessions.values_mut() {
+ sessions.sort_unstable();
+ }
+
+ let mut events = Vec::new();
+ for page in &mut ctx.pages {
+ let runtime_events = page.take_pending_runtime_events();
+ if runtime_events.is_empty() {
+ continue;
+ }
+ let Some(sessions) = page_to_sessions.get(page.id.as_str()) else {
+ continue;
+ };
+ let execution_context_id = if ctx
+ .current_loader_ids
+ .get(&page.id)
+ .is_some_and(|loader_id| loader_id.starts_with("loader-blank-"))
+ {
+ 1
+ } else {
+ 2
+ };
+ for runtime_event in runtime_events {
+ for session_id in sessions {
+ let (method, params) = match &runtime_event {
+ obscura_js::ops::RuntimeEvent::Console(event) => (
+ "Runtime.consoleAPICalled",
+ json!({
+ "type": event.kind,
+ "args": event.args,
+ "executionContextId": execution_context_id,
+ "timestamp": event.timestamp,
+ }),
+ ),
+ obscura_js::ops::RuntimeEvent::Exception(event) => (
+ "Runtime.exceptionThrown",
+ json!({
+ "timestamp": event.timestamp,
+ "exceptionDetails": {
+ "exceptionId": event.exception_id,
+ "text": "Uncaught",
+ "lineNumber": event.line_number,
+ "columnNumber": event.column_number,
+ "scriptId": "",
+ "url": event.url,
+ "stackTrace": { "callFrames": event.stack_trace },
+ "executionContextId": execution_context_id,
+ "exception": {
+ "type": "object",
+ "subtype": "error",
+ "className": event.name,
+ "description": event.description,
+ },
+ },
+ }),
+ ),
+ };
+ events.push(CdpEvent {
+ method: method.to_string(),
+ params,
+ session_id: Some((*session_id).to_string()),
+ });
+ }
+ }
+ }
+ ctx.pending_events.extend(events);
+}
+
// Drain every page's binding-call queue (filled by op_binding_called when
// page JS invokes a `Runtime.addBinding` shim) and turn each entry into a
// Runtime.bindingCalled CDP event that the writer task forwards to the
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index a6abfc90..9bcafd32 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -74,18 +74,25 @@ pub async fn handle(
// silently — the next Target.attachToTarget will set things up.
match ctx.get_session_page(session_id) {
Some(page) => {
+ let origin = page.url_string();
+ let page_id = page.id.clone();
+ let frame_id = page.frame_id.clone();
+ if let Some(session_id) = session_id {
+ ctx.runtime_enabled_sessions.insert(session_id.clone());
+ }
+ ctx.refresh_runtime_event_collection(&page_id);
let event = crate::types::CdpEvent {
method: "Runtime.executionContextCreated".to_string(),
params: json!({
"context": {
"id": 1,
- "origin": page.url_string(),
+ "origin": origin,
"name": "",
- "uniqueId": format!("ctx-{}", page.id),
+ "uniqueId": format!("ctx-{}", page_id),
"auxData": {
"isDefault": true,
"type": "default",
- "frameId": page.frame_id,
+ "frameId": frame_id,
}
}
}),
@@ -99,6 +106,16 @@ pub async fn handle(
}
Ok(json!({}))
}
+ "disable" => {
+ if let Some(session_id) = session_id {
+ let page_id = ctx.sessions.get(session_id).cloned();
+ ctx.runtime_enabled_sessions.remove(session_id);
+ if let Some(page_id) = page_id {
+ ctx.refresh_runtime_event_collection(&page_id);
+ }
+ }
+ Ok(json!({}))
+ }
"evaluate" => {
let expression = params
.get("expression")
diff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rs
index ab394f32..2b9215c6 100644
--- a/crates/obscura-cdp/src/domains/target.rs
+++ b/crates/obscura-cdp/src/domains/target.rs
@@ -229,7 +229,12 @@ pub async fn handle(
// Ack these so Chrome-shaped clients that call them do not warn (issue #340).
"detachFromTarget" => {
if let Some(session_id) = params.get("sessionId").and_then(Value::as_str) {
+ let page_id = ctx.sessions.get(session_id).cloned();
ctx.sessions.remove(session_id);
+ ctx.runtime_enabled_sessions.remove(session_id);
+ if let Some(page_id) = page_id {
+ ctx.refresh_runtime_event_collection(&page_id);
+ }
#[cfg(feature = "render")]
ctx.screencasts.remove(session_id);
}
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 3b4b5f25..2ee1e92d 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -790,6 +790,7 @@ async fn cdp_processor(
}
}
sync_live_page_network_events(&mut ctx);
+ dispatch::drain_runtime_events(&mut ctx);
dispatch::drain_binding_calls(&mut ctx);
dispatch::drain_frame_events(&mut ctx);
forward_pending_events(&mut ctx, connection_reply_tx.as_ref());
diff --git a/crates/obscura-cdp/tests/runtime_console_events.rs b/crates/obscura-cdp/tests/runtime_console_events.rs
new file mode 100644
index 00000000..809b159f
--- /dev/null
+++ b/crates/obscura-cdp/tests/runtime_console_events.rs
@@ -0,0 +1,256 @@
+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: Option<&str>,
+) -> Value {
+ let response = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: session.map(str::to_string),
+ },
+ ctx,
+ )
+ .await;
+ assert!(
+ response.error.is_none(),
+ "CDP {method} failed: {:?}",
+ response.error
+ );
+ response.result.unwrap_or_else(|| json!({}))
+}
+
+async fn create_and_attach(ctx: &mut CdpContext) -> (String, String) {
+ let created = cdp(
+ ctx,
+ 900,
+ "Target.createTarget",
+ json!({"url": "about:blank"}),
+ None,
+ )
+ .await;
+ let target_id = created["targetId"]
+ .as_str()
+ .expect("Target.createTarget returned no targetId")
+ .to_string();
+ let session = attach(ctx, &target_id, 901).await;
+ (target_id, session)
+}
+
+async fn attach(ctx: &mut CdpContext, target_id: &str, id: u64) -> String {
+ let attached = cdp(
+ ctx,
+ id,
+ "Target.attachToTarget",
+ json!({"targetId": target_id, "flatten": true}),
+ None,
+ )
+ .await;
+ attached["sessionId"]
+ .as_str()
+ .expect("Target.attachToTarget returned no sessionId")
+ .to_string()
+}
+
+fn events<'a>(ctx: &'a CdpContext, method: &str) -> Vec<(Option<&'a str>, &'a Value)> {
+ ctx.pending_events
+ .iter()
+ .filter(|event| event.method == method)
+ .map(|event| (event.session_id.as_deref(), &event.params))
+ .collect()
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn navigation_emits_console_arguments_and_uncaught_exception_details() {
+ let mut ctx = CdpContext::new();
+ let (_, session) = create_and_attach(&mut ctx).await;
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), Some(&session)).await;
+ ctx.pending_events.clear();
+
+ let url = concat!(
+ "data:text/html,<script>",
+ "window.__probe=1;",
+ "console.log('probe',{answer:42},undefined,NaN,-0,1n);",
+ "console.error('bad');",
+ "throw new Error('boom')",
+ "</script>"
+ );
+ cdp(
+ &mut ctx,
+ 2,
+ "Page.navigate",
+ json!({"url": url, "waitUntil": "load"}),
+ Some(&session),
+ )
+ .await;
+
+ let console = events(&ctx, "Runtime.consoleAPICalled");
+ assert_eq!(console.len(), 2, "console events: {console:?}");
+ assert!(console.iter().all(|(target, _)| *target == Some(&session)));
+
+ let log = console
+ .iter()
+ .find(|(_, params)| params["type"] == "log")
+ .expect("missing console.log event")
+ .1;
+ assert_eq!(log["executionContextId"], 2);
+ assert!(log["timestamp"].as_f64().is_some_and(|value| value > 0.0));
+ assert_eq!(log["args"].as_array().map(Vec::len), Some(6));
+ assert_eq!(log["args"][0]["type"], "string");
+ assert_eq!(log["args"][0]["value"], "probe");
+ assert_eq!(log["args"][1]["type"], "object");
+ let object_id = log["args"][1]["objectId"]
+ .as_str()
+ .expect("console object argument had no objectId")
+ .to_string();
+ assert_eq!(log["args"][2]["type"], "undefined");
+ assert_eq!(log["args"][3]["unserializableValue"], "NaN");
+ assert_eq!(log["args"][4]["unserializableValue"], "-0");
+ assert_eq!(log["args"][5]["type"], "bigint");
+ assert_eq!(log["args"][5]["unserializableValue"], "1n");
+
+ let error = console
+ .iter()
+ .find(|(_, params)| params["type"] == "error")
+ .expect("missing console.error event")
+ .1;
+ assert_eq!(error["args"][0]["value"], "bad");
+
+ let exceptions = events(&ctx, "Runtime.exceptionThrown");
+ assert_eq!(exceptions.len(), 1, "exception events: {exceptions:?}");
+ assert_eq!(exceptions[0].0, Some(session.as_str()));
+ let details = &exceptions[0].1["exceptionDetails"];
+ assert_eq!(details["text"], "Uncaught");
+ assert!(details["exceptionId"].as_u64().is_some());
+ assert!(details["url"].as_str().is_some_and(|url| url.starts_with("data:text/html,")));
+ assert!(details["exception"]["description"]
+ .as_str()
+ .is_some_and(|description| description.contains("Error: boom")));
+ assert!(exceptions[0].1["timestamp"]
+ .as_f64()
+ .is_some_and(|value| value > 0.0));
+ drop(console);
+ drop(exceptions);
+
+ let object_value = cdp(
+ &mut ctx,
+ 20,
+ "Runtime.callFunctionOn",
+ json!({
+ "functionDeclaration": "function() { return this.answer; }",
+ "objectId": object_id,
+ "returnByValue": true,
+ }),
+ Some(&session),
+ )
+ .await;
+ assert_eq!(object_value["result"]["value"], 42.0);
+
+ let marker = cdp(
+ &mut ctx,
+ 3,
+ "Runtime.evaluate",
+ json!({"expression": "window.__probe", "returnByValue": true}),
+ Some(&session),
+ )
+ .await;
+ assert_eq!(marker["result"]["value"], 1.0);
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn runtime_events_only_reach_sessions_while_runtime_is_enabled() {
+ let mut ctx = CdpContext::new();
+ let (target_id, first) = create_and_attach(&mut ctx).await;
+ let second = attach(&mut ctx, &target_id, 902).await;
+
+ cdp(&mut ctx, 1, "Runtime.enable", json!({}), Some(&first)).await;
+ ctx.pending_events.clear();
+ cdp(
+ &mut ctx,
+ 2,
+ "Runtime.evaluate",
+ json!({"expression": "console.log('first')"}),
+ Some(&first),
+ )
+ .await;
+ let first_events = events(&ctx, "Runtime.consoleAPICalled");
+ assert_eq!(
+ first_events
+ .iter()
+ .map(|(session, _)| *session)
+ .collect::<Vec<_>>(),
+ vec![Some(first.as_str())]
+ );
+ assert_eq!(first_events[0].1["executionContextId"], 1);
+
+ cdp(&mut ctx, 3, "Runtime.enable", json!({}), Some(&second)).await;
+ ctx.pending_events.clear();
+ cdp(
+ &mut ctx,
+ 4,
+ "Runtime.evaluate",
+ json!({"expression": "console.warn('both')"}),
+ Some(&first),
+ )
+ .await;
+ let mut targets: Vec<&str> = events(&ctx, "Runtime.consoleAPICalled")
+ .iter()
+ .map(|(session, _)| session.expect("runtime event had no session"))
+ .collect();
+ targets.sort_unstable();
+ let mut expected = vec![first.as_str(), second.as_str()];
+ expected.sort_unstable();
+ assert_eq!(targets, expected);
+ assert!(events(&ctx, "Runtime.consoleAPICalled")
+ .iter()
+ .all(|(_, params)| params["type"] == "warning"));
+
+ cdp(&mut ctx, 5, "Runtime.disable", json!({}), Some(&first)).await;
+ ctx.pending_events.clear();
+ cdp(
+ &mut ctx,
+ 6,
+ "Runtime.evaluate",
+ json!({"expression": "console.error('second')"}),
+ Some(&second),
+ )
+ .await;
+ assert_eq!(
+ events(&ctx, "Runtime.consoleAPICalled")
+ .iter()
+ .map(|(session, _)| *session)
+ .collect::<Vec<_>>(),
+ vec![Some(second.as_str())]
+ );
+
+ cdp(
+ &mut ctx,
+ 7,
+ "Runtime.releaseObjectGroup",
+ json!({}),
+ Some(&second),
+ )
+ .await;
+ cdp(&mut ctx, 8, "Runtime.disable", json!({}), Some(&second)).await;
+ ctx.pending_events.clear();
+ let retained = cdp(
+ &mut ctx,
+ 9,
+ "Runtime.evaluate",
+ json!({
+ "expression": "(() => { console.log({notRetained:true}); return Object.keys(globalThis.__obscura_objects).filter(k => k.startsWith('console-')).length; })()",
+ "returnByValue": true,
+ }),
+ Some(&second),
+ )
+ .await;
+ assert_eq!(retained["result"]["value"], 0.0);
+ assert!(events(&ctx, "Runtime.consoleAPICalled").is_empty());
+}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index d7e69040..b505d441 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -737,31 +737,90 @@ function _getElementsByClassName(root, classNames) {
}
return HTMLCollection._from(matched);
}
+let _consoleOid = 0;
+const _consoleObjectId = (value) => {
+ const objectId = "console-" + (globalThis.__obscura_frameId >>> 0) + "-" + (++_consoleOid);
+ const store = globalThis.__obscura_objects || (globalThis.__obscura_objects = {});
+ store[objectId] = value;
+ return objectId;
+};
+const _consoleRemoteObject = (value) => {
+ const type = typeof value;
+ if (value === null) return { type: "object", subtype: "null", value: null, description: "null" };
+ if (type === "undefined") return { type: "undefined" };
+ if (type === "string" || type === "boolean") return { type, value, description: String(value) };
+ if (type === "number") {
+ if (Number.isNaN(value)) return { type, unserializableValue: "NaN", description: "NaN" };
+ if (value === Infinity) return { type, unserializableValue: "Infinity", description: "Infinity" };
+ if (value === -Infinity) return { type, unserializableValue: "-Infinity", description: "-Infinity" };
+ if (Object.is(value, -0)) return { type, unserializableValue: "-0", description: "-0" };
+ return { type, value, description: String(value) };
+ }
+ if (type === "bigint") {
+ const description = String(value) + "n";
+ return { type, unserializableValue: description, description };
+ }
+ if (type === "symbol") return { type, description: String(value) };
+ if (value instanceof Error) {
+ const _pst = Error.prepareStackTrace;
+ if (_pst !== undefined) Error.prepareStackTrace = undefined;
+ const description = value.stack || value.message || String(value);
+ if (_pst !== undefined) Error.prepareStackTrace = _pst;
+ return {
+ type: "object", subtype: "error",
+ className: (value.constructor && value.constructor.name) || "Error",
+ description, objectId: _consoleObjectId(value)
+ };
+ }
+ const className = type === "function"
+ ? "Function"
+ : ((value.constructor && value.constructor.name) || "Object");
+ const remote = { type, className, description: type === "function" ? String(value) : className };
+ if (Array.isArray(value)) {
+ remote.subtype = "array";
+ remote.description = "Array(" + value.length + ")";
+ } else if (type === "object" && typeof value._nid === "number") {
+ remote.subtype = "node";
+ remote.description = value.tagName ? value.tagName.toLowerCase() : (value.nodeName || "node");
+ }
+ remote.objectId = _consoleObjectId(value);
+ return remote;
+};
const _consoleFn = (level, args) => {
- try { Deno.core.ops.op_console_msg(level, args.map(a => {
- if (a === null) return "null";
- if (a === undefined) return "undefined";
- if (a instanceof Error) {
- const _pst = Error.prepareStackTrace;
- if (_pst !== undefined) Error.prepareStackTrace = undefined;
- const _s = a.stack || a.message || String(a);
- if (_pst !== undefined) Error.prepareStackTrace = _pst;
- return _s;
- }
- if (typeof a === "object") {
- try {
- const s = JSON.stringify(a);
- return s === "{}" && a.message ? a.message : s;
- } catch { return String(a); }
- }
- return String(a);
- }).join(" ")); } catch {}
+ try {
+ const text = args.map(a => {
+ if (a === null) return "null";
+ if (a === undefined) return "undefined";
+ if (a instanceof Error) {
+ const _pst = Error.prepareStackTrace;
+ if (_pst !== undefined) Error.prepareStackTrace = undefined;
+ const _s = a.stack || a.message || String(a);
+ if (_pst !== undefined) Error.prepareStackTrace = _pst;
+ return _s;
+ }
+ if (typeof a === "object") {
+ try {
+ const s = JSON.stringify(a);
+ return s === "{}" && a.message ? a.message : s;
+ } catch { return String(a); }
+ }
+ return String(a);
+ }).join(" ");
+ const eventArgs = Deno.core.ops.op_runtime_events_enabled()
+ ? JSON.stringify(args.map(a => {
+ try { return _consoleRemoteObject(a); }
+ catch { return { type: typeof a, description: "<unavailable>" }; }
+ }))
+ : "";
+ Deno.core.ops.op_console_msg(level, text, eventArgs);
+ } catch {}
};
globalThis.console = {
- log: (...a) => _consoleFn("log", a), warn: (...a) => _consoleFn("warn", a),
- error: (...a) => _consoleFn("error", a), info: (...a) => _consoleFn("log", a),
- debug: () => {}, dir: () => {}, trace: () => {}, table: () => {}, group: () => {},
+ log: (...a) => _consoleFn("log", a), warn: (...a) => _consoleFn("warning", a),
+ error: (...a) => _consoleFn("error", a), info: (...a) => _consoleFn("info", a),
+ debug: (...a) => _consoleFn("debug", a), dir: (...a) => _consoleFn("dir", a),
+ trace: (...a) => _consoleFn("trace", a), table: (...a) => _consoleFn("table", a), group: () => {},
groupEnd: () => {}, groupCollapsed: () => {}, time: () => {}, timeEnd: () => {},
timeLog: () => {}, count: () => {}, countReset: () => {}, clear: () => {},
assert: (c, ...a) => { if (!c) _consoleFn("error", ["Assertion failed:", ...a]); },
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 7597a997..b55b631f 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -130,6 +130,11 @@ pub struct ObscuraState {
// `op_binding_called` op. Drained by the CDP layer after each dispatch
// and emitted as `Runtime.bindingCalled` events.
pub pending_binding_calls: Vec<(String, String)>,
+ // Console calls and uncaught script exceptions, in occurrence order.
+ // The CDP layer drains this after commands and autonomous event-loop turns.
+ pub pending_runtime_events: VecDeque<RuntimeEvent>,
+ pub runtime_events_enabled: bool,
+ pub runtime_exception_counter: u64,
pub network_response_bodies: HashMap<String, StoredNetworkResponseBody>,
pub network_response_body_order: VecDeque<String>,
pub network_response_body_counter: u64,
@@ -297,6 +302,9 @@ impl ObscuraState {
intercept_counter: 0,
intercept_enabled: false,
pending_binding_calls: Vec::new(),
+ pending_runtime_events: VecDeque::new(),
+ runtime_events_enabled: false,
+ runtime_exception_counter: 0,
network_response_bodies: HashMap::new(),
network_response_body_order: VecDeque::new(),
network_response_body_counter: 0,
@@ -354,6 +362,31 @@ impl ObscuraState {
}
}
+#[derive(Debug, Clone)]
+pub struct RuntimeConsoleEvent {
+ pub kind: String,
+ pub args: Vec<serde_json::Value>,
+ pub timestamp: f64,
+}
+
+#[derive(Debug, Clone)]
+pub struct RuntimeExceptionEvent {
+ pub exception_id: u64,
+ pub name: String,
+ pub description: String,
+ pub url: String,
+ pub line_number: i64,
+ pub column_number: i64,
+ pub stack_trace: Vec<serde_json::Value>,
+ pub timestamp: f64,
+}
+
+#[derive(Debug, Clone)]
+pub enum RuntimeEvent {
+ Console(RuntimeConsoleEvent),
+ Exception(RuntimeExceptionEvent),
+}
+
pub(crate) fn node_is_script(dom: &DomTree, node_id: NodeId) -> bool {
dom.with_node(node_id, |node| {
node.as_element()
@@ -2013,13 +2046,45 @@ fn compare_node_order(dom: &DomTree, a: NodeId, b: NodeId) -> i32 {
}
#[op2(fast)]
-fn op_console_msg(state: &OpState, #[string] level: &str, #[string] msg: &str) {
- let _ = state;
+fn op_runtime_events_enabled(state: &OpState) -> bool {
+ state.borrow::<SharedState>().borrow().runtime_events_enabled
+}
+
+#[op2(fast)]
+fn op_console_msg(
+ state: &OpState,
+ #[string] level: &str,
+ #[string] msg: &str,
+ #[string] args_json: &str,
+) {
match level {
- "warn" => tracing::warn!(target: "obscura::console", "{}", msg),
+ "warn" | "warning" => tracing::warn!(target: "obscura::console", "{}", msg),
"error" => tracing::error!(target: "obscura::console", "{}", msg),
_ => tracing::info!(target: "obscura::console", "{}", msg),
}
+
+ let page = state.borrow::<SharedState>().clone();
+ let mut page = page.borrow_mut();
+ if !page.runtime_events_enabled {
+ return;
+ }
+ let Ok(args) = serde_json::from_str::<Vec<serde_json::Value>>(args_json) else {
+ return;
+ };
+ if page.pending_runtime_events.len() >= 1_024 {
+ page.pending_runtime_events.pop_front();
+ }
+ let timestamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs_f64()
+ * 1_000.0;
+ page.pending_runtime_events
+ .push_back(RuntimeEvent::Console(RuntimeConsoleEvent {
+ kind: level.to_string(),
+ args,
+ timestamp,
+ }));
}
// Fallback cache for runtimes that have no owning ObscuraHttpClient, such as
@@ -4383,6 +4448,7 @@ pub fn build_extension() -> Extension {
op_script_try_start(),
op_shadow_attach(),
op_shadow_root_info(),
+ op_runtime_events_enabled(),
op_console_msg(),
op_fetch_url(),
op_get_cookies(),
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index f36f742e..2b32db94 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -13,7 +13,10 @@ use crate::import_map::ImportMap;
use crate::module_loader::{ModuleLoadActivity, ObscuraModuleLoader};
#[cfg(all(test, feature = "render"))]
use crate::ops::ensure_prepared_render;
-use crate::ops::{build_extension, node_is_script, ObscuraState, StoredNetworkResponseBody};
+use crate::ops::{
+ build_extension, node_is_script, ObscuraState, RuntimeEvent, RuntimeExceptionEvent,
+ StoredNetworkResponseBody,
+};
#[cfg(feature = "render")]
use crate::ops::{
begin_animation_task, clamp_scroll_offset, document_base_url, ensure_resolved_scroll,
@@ -875,6 +878,101 @@ impl ObscuraJsRuntime {
std::mem::take(&mut self.state.borrow_mut().pending_binding_calls)
}
+ pub fn take_pending_runtime_events(&mut self) -> Vec<RuntimeEvent> {
+ let events: Vec<_> = self
+ .state
+ .borrow_mut()
+ .pending_runtime_events
+ .drain(..)
+ .collect();
+ for event in &events {
+ let RuntimeEvent::Console(event) = event else {
+ continue;
+ };
+ for arg in &event.args {
+ let Some(object_id) = arg.get("objectId").and_then(|value| value.as_str()) else {
+ continue;
+ };
+ let frame_id = object_id
+ .strip_prefix("console-")
+ .and_then(|rest| rest.split_once('-'))
+ .and_then(|(frame_id, _)| frame_id.parse::<u32>().ok())
+ .unwrap_or(0);
+ let retrieval = if frame_id == 0 {
+ format!("globalThis.__obscura_objects['{object_id}']")
+ } else {
+ format!(
+ "globalThis.__obscura_frameObjects[{frame_id}]?.window?.__obscura_objects['{object_id}']"
+ )
+ };
+ self.object_store.insert(object_id.to_string(), retrieval);
+ }
+ }
+ events
+ }
+
+ pub fn set_runtime_events_enabled(&self, enabled: bool) {
+ self.state.borrow_mut().runtime_events_enabled = enabled;
+ }
+
+ fn record_uncaught_exception(&self, error: &deno_core::error::JsError, fallback_url: &str) {
+ let mut state = self.state.borrow_mut();
+ if !state.runtime_events_enabled {
+ return;
+ }
+ state.runtime_exception_counter = state.runtime_exception_counter.saturating_add(1);
+ let first = error.frames.first();
+ let url = first
+ .and_then(|frame| frame.file_name.clone())
+ .filter(|url| !url.is_empty())
+ .unwrap_or_else(|| fallback_url.to_string());
+ let line_number = first
+ .and_then(|frame| frame.line_number)
+ .unwrap_or(1)
+ .saturating_sub(1);
+ let column_number = first
+ .and_then(|frame| frame.column_number)
+ .unwrap_or(1)
+ .saturating_sub(1);
+ let stack_trace = error
+ .frames
+ .iter()
+ .map(|frame| {
+ serde_json::json!({
+ "functionName": frame.function_name.as_deref().unwrap_or(""),
+ "scriptId": "",
+ "url": frame.file_name.as_deref().unwrap_or(fallback_url),
+ "lineNumber": frame.line_number.unwrap_or(1).saturating_sub(1),
+ "columnNumber": frame.column_number.unwrap_or(1).saturating_sub(1),
+ })
+ })
+ .collect();
+ let timestamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs_f64()
+ * 1_000.0;
+ if state.pending_runtime_events.len() >= 1_024 {
+ state.pending_runtime_events.pop_front();
+ }
+ let exception_id = state.runtime_exception_counter;
+ state
+ .pending_runtime_events
+ .push_back(RuntimeEvent::Exception(RuntimeExceptionEvent {
+ exception_id,
+ name: error.name.clone().unwrap_or_else(|| "Error".to_string()),
+ description: error
+ .stack
+ .clone()
+ .unwrap_or_else(|| error.exception_message.clone()),
+ url,
+ line_number,
+ column_number,
+ stack_trace,
+ timestamp,
+ }));
+ }
+
pub fn get_network_response_body(&self, request_id: &str) -> Option<StoredNetworkResponseBody> {
self.state
.borrow()
@@ -1855,16 +1953,40 @@ impl ObscuraJsRuntime {
pub fn release_object(&mut self, object_id: &str) {
if self.object_store.remove(object_id).is_some() {
- let code = format!("delete globalThis.__obscura_objects['{}'];", object_id,);
+ let frame_id = object_id
+ .strip_prefix("console-")
+ .and_then(|rest| rest.split_once('-'))
+ .and_then(|(frame_id, _)| frame_id.parse::<u32>().ok())
+ .unwrap_or(0);
+ let code = if frame_id == 0 {
+ format!("delete globalThis.__obscura_objects['{object_id}'];")
+ } else {
+ format!(
+ "delete globalThis.__obscura_frameObjects[{frame_id}]?.window?.__obscura_objects['{object_id}'];"
+ )
+ };
let _ = self.execute_runtime_script("<release>", code);
}
}
pub fn release_object_group(&mut self) {
- let _ = self.execute_runtime_script(
- "<releaseGroup>",
- "globalThis.__obscura_objects = {};".to_string(),
- );
+ let mut frame_ids: Vec<u32> = self
+ .object_store
+ .keys()
+ .filter_map(|object_id| object_id.strip_prefix("console-"))
+ .filter_map(|rest| rest.split_once('-'))
+ .filter_map(|(frame_id, _)| frame_id.parse().ok())
+ .filter(|frame_id| *frame_id != 0)
+ .collect();
+ frame_ids.sort_unstable();
+ frame_ids.dedup();
+ let mut code = "globalThis.__obscura_objects = {};".to_string();
+ for frame_id in frame_ids {
+ code.push_str(&format!(
+ "if(globalThis.__obscura_frameObjects[{frame_id}]?.window)globalThis.__obscura_frameObjects[{frame_id}].window.__obscura_objects={{}};"
+ ));
+ }
+ let _ = self.execute_runtime_script("<releaseGroup>", code);
self.object_store.clear();
}
pub async fn load_module(&mut self, url: &str, budget_ms: u64) -> Result<(), String> {
@@ -2122,16 +2244,17 @@ impl ObscuraJsRuntime {
fn execute_classic_script(&mut self, name: &str, source: &str) -> Result<(), String> {
self.begin_javascript_task();
+ let script_url = name.to_string();
// JsRuntime::execute_script in deno_core 0.350 restricts `name` to a
// &'static str. Browser script URLs are runtime data, and V8 uses this
// origin as import()'s referrer, so compile in the runtime's main
// context directly instead of substituting the fixed "<script>" name.
- let result = (|| {
+ let result: Result<(), (String, Option<deno_core::error::JsError>)> = (|| {
let scope = &mut self.runtime.handle_scope();
let source = deno_core::v8::String::new(scope, source)
- .ok_or_else(|| "JS error: source allocation failed".to_string())?;
+ .ok_or_else(|| ("JS error: source allocation failed".to_string(), None))?;
let name = deno_core::v8::String::new(scope, name)
- .ok_or_else(|| "JS error: script URL allocation failed".to_string())?;
+ .ok_or_else(|| ("JS error: script URL allocation failed".to_string(), None))?;
let origin = deno_core::v8::ScriptOrigin::new(
scope,
name.into(),
@@ -2150,35 +2273,46 @@ impl ObscuraJsRuntime {
let Some(script) = script else {
if scope.is_execution_terminating() {
scope.cancel_terminate_execution();
- return Err("JS error: Uncaught Error: execution terminated".to_string());
+ return Err(("JS error: Uncaught Error: execution terminated".to_string(), None));
}
return match scope.exception() {
Some(exception) => {
let error = deno_core::error::JsError::from_v8_exception(scope, exception);
- Err(format!("JS error: {error}"))
- }
- None => {
- Err("JS error: script compilation failed without an exception".to_string())
+ Err((format!("JS error: {error}"), Some(error)))
}
+ None => Err((
+ "JS error: script compilation failed without an exception".to_string(),
+ None,
+ )),
};
};
if script.run(scope).is_none() {
if scope.is_execution_terminating() {
scope.cancel_terminate_execution();
- return Err("JS error: Uncaught Error: execution terminated".to_string());
+ return Err(("JS error: Uncaught Error: execution terminated".to_string(), None));
}
return match scope.exception() {
Some(exception) => {
let error = deno_core::error::JsError::from_v8_exception(scope, exception);
- Err(format!("JS error: {error}"))
- }
- None => {
- Err("JS error: script execution failed without an exception".to_string())
+ Err((format!("JS error: {error}"), Some(error)))
}
+ None => Err((
+ "JS error: script execution failed without an exception".to_string(),
+ None,
+ )),
};
}
Ok(())
})();
+ let result = match result {
+ Ok(()) => Ok(()),
+ Err((message, error)) => {
+ if let Some(error) = error.as_ref() {
+ self.record_uncaught_exception(error, &script_url);
+ }
+ Err(message)
+ }
+ };
self.finish_heap_checked(result)
}