The headless browser for AI agents and web scraping
fix(frames): initialize blank documents during insertion
SGavrl47a34311ed43
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 0879ee1e..d756cdf2 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1280,9 +1280,17 @@ impl Page {// New-document scripts must be installed before the published// child context can be observed, including while its external// scripts are still loading.- for source in &self.preload_scripts {- if let Err(error) = realm.execute_script(js, source) {- tracing::debug!("frame {} preload failed: {error}", frame.url);+ if frame.url != "about:blank" {+ for source in &self.preload_scripts {+ if let Err(error) = realm.execute_script(js, source) {+ tracing::debug!("frame {} preload failed: {error}", frame.url);+ }+ }+ if !self.preload_scripts.is_empty() {+ let watchdog = js.arm_watchdog(std::time::Duration::from_secs(5));+ let result = realm.execute_script(js, "globalThis.__obscura_init_frames();");+ js.disarm_watchdog(watchdog);+ if let Err(error) = result { tracing::debug!("frame initialization failed: {error}"); }}}}@@ -1367,22 +1375,25 @@ impl Page {self.pending_frame_work.pop_front();return true;};- if let Some(js) = self.js.as_mut() {- for problem in self.frames[index]- .run_document_scripts(js, |url| sources.get(url).cloned())- {- tracing::debug!("frame {}: {}", frame_url, problem);- }- if let Err(error) = self.frames[index].dispatch_load_events(js) {- tracing::debug!("frame {} load events failed: {error}", frame_url);+ // Initial blank documents finish synchronously during insertion.+ if frame_url != "about:blank" {+ if let Some(js) = self.js.as_mut() {+ for problem in self.frames[index]+ .run_document_scripts(js, |url| sources.get(url).cloned())+ {+ tracing::debug!("frame {}: {}", frame_url, problem);+ }+ if let Err(error) = self.frames[index].dispatch_load_events(js) {+ tracing::debug!("frame {} load events failed: {error}", frame_url);+ }}+ self.execute_frame_owner_script(parent_frame_id, &format!(+ "(function(){{ const frame = globalThis.__obscura_frameElements[{frame_id}]; \+ if (frame && frame.isConnected && frame._frameId === {frame_id}) \+ frame.dispatchEvent(new Event('load')); }})()"+ ));}self.pending_frame_work.pop_front();- self.execute_frame_owner_script(parent_frame_id, &format!(- "(function(){{ const frame = globalThis.__obscura_frameElements[{frame_id}]; \- if (frame && frame.isConnected && frame._frameId === {frame_id}) \- frame.dispatchEvent(new Event('load')); }})()"- ));true}@@ -1914,6 +1925,7 @@ impl Page {}rt.set_navigation_timing(self.navigation_timing.clone());+ rt.set_frame_preload_scripts(&self.preload_scripts);rt.run_page_init();rt.set_media_preferences(self.reduced_motion, self.dark_color_scheme);let _ = rt.execute_script(@@ -2582,6 +2594,10 @@ impl Page {tracing::debug!("Preload script error: {}", e);}}+ if !preload_sources.is_empty() {+ let _ = js.execute_script_with_timeout("<frame-init>", "globalThis.__obscura_init_frames();",+ std::time::Duration::from_secs(5));+ }}// Per-module budget. Modules on an already-rendered page are@@ -3481,6 +3497,10 @@ impl Page {tracing::debug!("Preload script error on about:blank: {}", e);}}+ if !preload_sources.is_empty() {+ let _ = js.execute_script_with_timeout("<frame-init>", "globalThis.__obscura_init_frames();",+ std::time::Duration::from_secs(5));+ }}return Ok(());}@@ -4914,6 +4934,7 @@ impl Page {}pub fn set_preload_scripts(&mut self, scripts: Vec<String>) {+ if let Some(js) = &self.js { js.set_frame_preload_scripts(&scripts); }self.preload_scripts = scripts;}@@ -7256,6 +7277,81 @@ mod tests {})()"#).unwrap(), serde_json::json!(["Top document", true, false]));}+ #[test]+ fn foreign_iframe_elements_do_not_create_browsing_contexts() {+ let mut page = import_map_test_page("foreign-frame", "https://parent.test",+ "<body><svg><iframe id='foreign'></iframe></svg></body>");+ assert!(!page.js.as_ref().unwrap().has_pending_frame_tasks(), "parser-created SVG iframe");+ page.evaluate_script(r#"(() => {+ const root = document.createElement('div');+ root.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'iframe'));+ document.body.appendChild(root);+ root.innerHTML = '<svg><iframe></iframe></svg>';+ return true;+ })()"#).unwrap();+ assert!(!page.js.as_ref().unwrap().has_pending_frame_tasks(), "inserted SVG iframe");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn blank_iframe_load_runs_while_an_unrelated_timer_is_pending() {+ for inserted in [false, true] {+ let html = if inserted { "<body></body>" } else {+ "<body><iframe id='f' onload='globalThis.loads = (globalThis.loads || 0) + 1'></iframe></body>"+ };+ let mut page = import_map_test_page("blank-frame-load", "https://parent.test", html);+ page.set_preload_scripts(vec!["globalThis.eval = () => undefined;".into(),+ "globalThis.preloadCount = (globalThis.preloadCount || 0) + 1;".into()]);+ page.evaluate_script(&format!(r#"(() => {{+ globalThis.loads = globalThis.loads || 0;+ if ({inserted}) {{+ const frame = document.createElement('iframe');+ frame.id = 'f'; frame.onload = () => loads++;+ document.body.appendChild(frame);+ }}+ setTimeout(() => {{}}, 60000);+ return true;+ }})()"#)).unwrap();+ assert_eq!(page.evaluate_script("loads").unwrap().as_f64(), Some(1.0),+ "initial blank load must fire during insertion, without getters");+ tokio::time::timeout(std::time::Duration::from_secs(2),+ page.run_autonomous_event_loop_turn()).await+ .expect("frame adoption must not wait for an unrelated timer").unwrap();+ assert_eq!(page.frame_urls(), ["about:blank"]);+ assert_eq!(page.evaluate_script("[document.getElementById('f').contentDocument.URL, loads]").unwrap(),+ serde_json::json!(["about:blank", 1]));+ if inserted {+ assert_eq!(page.evaluate_script("document.getElementById('f').contentWindow.preloadCount").unwrap().as_f64(),+ Some(1.0), "initial-frame preloads run once");+ }+ }+ }++ #[tokio::test(flavor = "current_thread")]+ async fn parser_blank_iframe_load_runs_after_parent_initialization_scripts() {+ let mut page = import_map_test_page("parser-frame-order", "https://parent.test", "<body></body>");+ page.set_preload_scripts(vec!["globalThis.preloadMarker = 'ready';".into()]);+ page.navigate("data:text/html,<body><iframe onload='globalThis.observed = [window.preloadMarker, this.contentWindow.preloadMarker]'></iframe></body>").await.unwrap();+ assert_eq!(page.evaluate_script("observed").unwrap(), serde_json::json!(["ready", "ready"]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn blank_iframe_load_observes_preloads_and_precedes_append_return() {+ let mut page = import_map_test_page("blank-frame-order", "https://parent.test", "<body></body>");+ page.set_preload_scripts(vec!["globalThis.preloadCount = (globalThis.preloadCount || 0) + 1;".into()]);+ assert_eq!(page.evaluate_script(r#"(() => {+ const events = []; const frame = document.createElement('iframe');+ frame.onload = () => events.push(['load', frame.contentDocument.readyState, frame.contentWindow.preloadCount]);+ document.body.appendChild(frame); events.push(['after']);+ return events;+ })()"#).unwrap(), serde_json::json!([["load", "complete", 1], ["after"]]));+ page.set_preload_scripts(vec!["globalThis.preloadCount = 7;".into()]);+ assert_eq!(page.evaluate_script(r#"(() => {+ const parent = document.querySelector('iframe').contentDocument;+ const nested = parent.createElement('iframe'); parent.body.appendChild(nested);+ return nested.contentWindow.preloadCount;+ })()"#).unwrap().as_f64(), Some(7.0), "existing parent frames see updated initialization scripts");+ }+#[tokio::test(flavor = "current_thread")]async fn iframe_srcdoc_loads_parser_and_inserted_documents_in_their_own_realms() {let mut page = import_map_test_page("srcdoc", "https://parent.test",diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 6cc50bee..691e8fcf 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -2351,12 +2351,11 @@ function __prepareInsertedSubtree(root) {if (!root || !root.isConnected) return;const scripts = [];const seen = new Set();- if (root.nodeType === 1 && (root.tagName === 'SCRIPT'- || (root.tagName === 'IFRAME' && root.hasAttribute('srcdoc')))) {+ if (root.nodeType === 1 && (root.tagName === 'SCRIPT' || root.tagName === 'IFRAME')) {scripts.push(root);seen.add(root._nid);}- const ids = _domParse("query_selector_all_scoped", root._nid, "script,iframe[srcdoc]") || [];+ const ids = _domParse("query_selector_all_scoped", root._nid, "script,iframe") || [];for (const nid of ids) {const script = _wrapEl(+nid);if (script && !seen.has(script._nid)) {@@ -2366,8 +2365,15 @@ function __prepareInsertedSubtree(root) {}for (const script of scripts) {if (_postConnection) _postConnection.cursor = script;- if (script.localName === 'iframe') script._loadIframeSrcdoc();- else __prepareInsertedScript(script);+ if (script.localName === 'iframe') {+ if (script.namespaceURI !== 'http://www.w3.org/1999/xhtml') continue;+ if (script.hasAttribute('srcdoc')) script._loadIframeSrcdoc();+ else {+ const src = script.getAttribute('src');+ if (src && src !== 'about:blank') script._loadIframeSrc(src);+ else if (_ensureInitialFrameRealm(script)) script.dispatchEvent(new Event('load'));+ }+ } else __prepareInsertedScript(script);}}@@ -4190,7 +4196,7 @@ class Element extends Node {// before script can synchronously read `window.someId`._registerWindowNamedTree(this);_reconcileWindowNamedProperties(previousWindowNames);- _connectSrcdocFrames(this, html);+ _connectInsertedFrames(this, html);if (globalThis.__mutationObservers?.length) {newChildren = _domParse("child_nodes", this._nid) || [];globalThis.__notifyMutation('childList', this._nid, newChildren, oldChildren);@@ -7096,7 +7102,7 @@ class DocumentFragment extends Node {} else {_dom("set_inner_html", this._nid, html);}- _connectSrcdocFrames(this, html);+ _connectInsertedFrames(this, html);}querySelector(s) { return _wrapEl(+_dom("query_selector_scoped", this._nid, s)); }querySelectorAll(s) {@@ -15486,9 +15492,9 @@ function _frameObjectsFor(element) {return entry || null;}-function _connectSrcdocFrames(root, html) {+function _connectInsertedFrames(root, html) {if (root.isConnected && /<iframe[\s/>]/i.test(html)) {- _runPostConnectionSteps(Array.from(root.querySelectorAll('iframe[srcdoc]')));+ _runPostConnectionSteps(Array.from(root.querySelectorAll('iframe')));}}@@ -15533,6 +15539,16 @@ function _ensureInitialFrameRealm(element, srcdoc) {element._iframeDoc = opaque ? null: globalThis.__obscura_frameObjects[frameId].document;globalThis.__obscura_frameElements[frameId] = element;+ if (srcdoc === undefined && !opaque) {+ const evaluate = element._iframeWin.eval;+ const initializeFrames = element._iframeWin.__obscura_init_frames;+ const sources = JSON.parse(__obscuraCore.ops.op_frame_preload_scripts());+ for (const source of sources) {+ try { evaluate(source); }+ catch (error) { console.error('Frame preload failed:', error && error.message || error); }+ }+ if (sources.length) initializeFrames();+ }}return frameId !== 0;}@@ -18426,6 +18442,22 @@ const _documentMembers = Object.freeze(Object.fromEntries([['elementStyle', function() { return _elementStyle(this); }],]));+globalThis.__obscura_init_frames = function() {+ // A parser-created <iframe src> never went through the src setter, so+ // nothing had started its load and the frame stayed empty (issue #600).+ // This also runs inside a frame realm, so a frame nested in a frame loads+ // by the same path, with op_frame_document_ready recording the caller as+ // its parent.+ for (const frame of globalThis.document.querySelectorAll('iframe')) {+ if (frame.namespaceURI !== 'http://www.w3.org/1999/xhtml') continue;+ const src = frame.getAttribute('src');+ if (frame.hasAttribute('srcdoc')) frame._loadIframeSrcdoc();+ else if (src && src !== 'about:blank') frame._loadIframeSrc(src);+ else if (_ensureInitialFrameRealm(frame)) frame.dispatchEvent(new Event('load'));+ }++};+globalThis.__obscura_init = (function() {// The host sets __obscura_frameId on a frame realm before calling this._realmFrameId = globalThis.__obscura_frameId >>> 0;@@ -18513,16 +18545,7 @@ globalThis.__obscura_init = (function() {// wrongly changes everything after it._installFramingRelationships();- // A parser-created <iframe src> never went through the src setter, so- // nothing had started its load and the frame stayed empty (issue #600).- // This also runs inside a frame realm, so a frame nested in a frame loads- // by the same path, with op_frame_document_ready recording the caller as- // its parent.- for (const frame of globalThis.document.querySelectorAll('iframe')) {- const src = frame.getAttribute('src');- if (frame.hasAttribute('srcdoc')) frame._loadIframeSrcdoc();- else if (src && src !== 'about:blank') frame._loadIframeSrc(src);- }+ if (JSON.parse(__obscuraCore.ops.op_frame_preload_scripts()).length === 0) globalThis.__obscura_init_frames();// Hide internals (_*, obscura, Obscura). The set of keys is static at// snapshot-build time, so we precompute it ONCE below (after thisdiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex 7675b733..26853b71 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -130,16 +130,14 @@ impl FrameRealm {// Both ids before init, not after: init is what installs `parent` and// `top`, and a document that runs even one script believing it is// top-level has already taken the wrong branch.- realm- .run(- parent,- &format!(- "globalThis.__obscura_frameId = {frame_id};\- globalThis.__obscura_parentFrameId = {parent_frame_id};\- globalThis.__obscura_init();"- ),- )- .ok()?;+ let watchdog = parent.arm_watchdog(std::time::Duration::from_secs(5));+ let initialized = realm.run(parent, &format!(+ "globalThis.__obscura_frameId = {frame_id};\+ globalThis.__obscura_parentFrameId = {parent_frame_id};\+ globalThis.__obscura_init();"+ ));+ parent.disarm_watchdog(watchdog);+ initialized.ok()?;// Only after init, so the document the page reaches through// `contentDocument` is the initialized one.if same_origin {diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 3d9893d5..76a3ac76 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -1116,6 +1116,7 @@ pub type SharedState = Rc<RefCell<ObscuraState>>;pub struct RealmStates {entries: Vec<(v8::Global<v8::Context>, u32, SharedState)>,frame_timers: HashMap<u32, FrameTimers>,+ pub(crate) frame_preload_scripts: Vec<String>,}struct FrameTimers {@@ -7765,6 +7766,18 @@ fn op_canvas_paint_damage(state: &OpState, nid: u32) -> bool {connected}+#[op2]+#[string]+fn op_frame_preload_scripts(state: &OpState) -> String {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let registry = state.borrow::<Rc<RefCell<RealmStates>>>();+ serde_json::to_string(®istry.borrow().frame_preload_scripts).unwrap_or("[]".into())+ })).unwrap_or_else(|_| {+ tracing::error!("op_frame_preload_scripts panicked; returning no scripts");+ "[]".into()+ })+}+pub fn build_extension() -> Extension {let mut ops = vec![op_dom(),@@ -7855,6 +7868,7 @@ pub fn build_extension() -> Extension {ops.push(op_waapi_create());ops.push(op_waapi_control());}+ ops.push(op_frame_preload_scripts());Extension {name: "obscura_dom",ops: std::borrow::Cow::Owned(ops),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex c0c1c715..4b085688 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -2580,13 +2580,19 @@ impl ObscuraJsRuntime {.has_live_image_outcome(url, profile)}+ #[doc(hidden)]+ pub fn set_frame_preload_scripts(&self, scripts: &[String]) {+ self.realm_states().borrow_mut().frame_preload_scripts = scripts.to_vec();+ }+/// Run __obscura_init() after all per-page properties (UA, platform, stealth, etc.)/// have been set. Must be called once per page setup, after all set_* methods.pub fn run_page_init(&mut self) {self.state.borrow_mut().navigation_timing.record("domLoading");- let _ = self.execute_runtime_script(+ let _ = self.execute_script_with_timeout("<obscura:page-init>",- "globalThis.__obscura_init();".to_string(),+ "globalThis.__obscura_init();",+ std::time::Duration::from_secs(5),);}@@ -3766,8 +3772,8 @@ impl ObscuraJsRuntime {return Err("JavaScript heap limit exceeded; execution terminated".into());}- // Publish settled protocol replies before parking on unrelated page work.- if self.has_ready_cdp_evaluations() { return Ok(false); }+ // Let the page adopt frame documents and deliver messages before parking.+ if self.has_ready_cdp_evaluations() || self.has_pending_frame_tasks() { return Ok(false); }let isolate_handle = self.isolate_handle();let mut waiting_for_wake = false;@@ -3787,7 +3793,7 @@ impl ObscuraJsRuntime {"autonomous browser task exceeded its task budget".into(),));}- if self.has_ready_cdp_evaluations() {+ if self.has_ready_cdp_evaluations() || self.has_pending_frame_tasks() {return std::task::Poll::Ready(Ok(false));}match tick {