The headless browser for AI agents and web scraping
Emit document replacement lifecycle for Playwright setContent
Antonio Rossia74e050a3453
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 518757a7..0806111c 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -885,6 +885,15 @@ pub(crate) fn drain_runtime_events(ctx: &mut CdpContext) {for runtime_event in runtime_events {for session_id in sessions {let (method, params) = match &runtime_event {+ obscura_js::ops::RuntimeEvent::DocumentLifecycle { name, timestamp } => (+ "Page.lifecycleEvent",+ json!({+ "frameId": ctx.pages.iter().find(|page| page.id == page_id).map(|page| &page.frame_id),+ "loaderId": ctx.current_loader_ids.get(&page_id),+ "name": name,+ "timestamp": timestamp,+ }),+ ),obscura_js::ops::RuntimeEvent::Console(event) => ("Runtime.consoleAPICalled",json!({diff --git a/crates/obscura-cdp/tests/document_write_lifecycle.rs b/crates/obscura-cdp/tests/document_write_lifecycle.rsnew file mode 100644index 00000000..1d3e415a--- /dev/null+++ b/crates/obscura-cdp/tests/document_write_lifecycle.rs@@ -0,0 +1,44 @@+use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn call(ctx: &mut CdpContext, method: &str, params: Value, session: &str) -> Value {+ let response = dispatch(&CdpRequest {+ id: 1, method: method.into(), params, session_id: Some(session.into()),+ }, ctx).await;+ assert!(response.error.is_none(), "{method}: {:?}", response.error);+ response.result.unwrap()+}++#[tokio::test]+async fn document_replacement_emits_ordered_lifecycle_without_replacing_the_context() {+ let mut ctx = CdpContext::new();+ let page = ctx.create_page();+ ctx.sessions.insert("write-session".into(), page.clone());+ call(&mut ctx, "Page.enable", json!({}), "write-session").await;+ call(&mut ctx, "Runtime.enable", json!({}), "write-session").await;+ call(&mut ctx, "Page.navigate", json!({"url":"data:text/html,<title>old</title><p>old</p>"}), "write-session").await;+ ctx.pending_events.clear();+ for _ in 0..2 {+ call(&mut ctx, "Runtime.evaluate", json!({"expression":r#"(() => {+ document.open(); console.debug('write-marker');+ document.write('<title>new</title><p id="replacement">written</p>');+ document.close();+ })()"#}), "write-session").await;+ ctx.get_session_page_mut(&Some("write-session".into())).unwrap().settle(40).await;+ let result = call(&mut ctx, "Runtime.evaluate", json!({+ "expression":"[document.title,document.readyState,document.querySelector('#replacement').textContent]",+ "returnByValue":true,+ }), "write-session").await;+ assert_eq!(result["result"]["value"], json!(["new", "complete", "written"]));+ let lifecycle: Vec<_> = ctx.pending_events.iter().filter(|e| e.method == "Page.lifecycleEvent")+ .map(|e| e.params["name"].as_str().unwrap()).collect();+ assert_eq!(lifecycle, ["init", "DOMContentLoaded", "load"]);+ assert!(!ctx.pending_events.iter().any(|e| matches!(e.method.as_str(),+ "Runtime.executionContextsCleared" | "Runtime.executionContextDestroyed" | "Page.frameNavigated")));+ let marker = ctx.pending_events.iter().position(|e| e.method == "Runtime.consoleAPICalled").unwrap();+ let loaded = ctx.pending_events.iter().position(|e| e.params["name"] == "DOMContentLoaded").unwrap();+ assert!(marker < loaded, "setContent marker must precede completion");+ ctx.pending_events.clear();+ }+}diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 2735832d..fb1c0ed1 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -5883,16 +5883,39 @@ class Document extends Node {this.write(args.join('') + '\n');}open() {+ if (this.head) this.head.innerHTML = '';var body = this.body;if (body) body.innerHTML = '';// A new parse begins. Whatever the input stream still held is gone._dom("document_write_reset");this._writeAnchorScript = 0;this._writeAnchorNid = 0;+ this._writeGeneration = (this._writeGeneration || 0) + 1;+ this._writeOpen = true;+ globalThis.__documentReadyState__ = 'loading';+ _dom('document_lifecycle', 'init');return this;}close() {- return;+ if (!this._writeOpen) return;+ this._writeOpen = false;+ const generation = this._writeGeneration;+ setTimeout(() => {+ if (generation !== this._writeGeneration) return;+ globalThis.__documentReadyState__ = 'interactive';+ this.dispatchEvent(new Event('readystatechange'));+ this.dispatchEvent(new Event('DOMContentLoaded', { bubbles: true }));+ _dom('document_lifecycle', 'DOMContentLoaded');+ const complete = () => {+ if (generation !== this._writeGeneration) return;+ if (__dynLoadDelayingPending > 0) { setTimeout(complete, 1); return; }+ globalThis.__documentReadyState__ = 'complete';+ this.dispatchEvent(new Event('readystatechange'));+ globalThis.dispatchEvent(new Event('load'));+ _dom('document_lifecycle', 'load');+ };+ complete();+ }, 0);}hasFocus() { return true; }execCommand() { return false; }diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex ff374f8e..b7dfecd3 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -462,6 +462,7 @@ pub struct RuntimeExceptionEvent {pub enum RuntimeEvent {Console(RuntimeConsoleEvent),Exception(RuntimeExceptionEvent),+ DocumentLifecycle { name: String, timestamp: f64 },}pub(crate) fn node_is_script(dom: &DomTree, node_id: NodeId) -> bool {@@ -1352,6 +1353,18 @@ fn op_dom(}fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) -> String {+ if cmd == "document_lifecycle" {+ let mut state = shared.borrow_mut();+ if state.runtime_events_enabled && matches!(arg1.as_str(), "init" | "DOMContentLoaded" | "load") {+ if state.pending_runtime_events.len() >= 1_024 {+ state.pending_runtime_events.pop_front();+ }+ let timestamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs_f64();+ state.pending_runtime_events.push_back(RuntimeEvent::DocumentLifecycle { name: arg1, timestamp });+ }+ return "true".into();+ }{// Scroll offsets belong to a node at its current tree position.// Temporary box/style loss keeps that latent state, but DOM removal,