The headless browser for AI agents and web scraping
Load frame Location navigations in their owning frame
SGavrl8dddc6f046d4
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex d756cdf2..c06c82e0 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1646,9 +1646,24 @@ impl Page {for _ in 0..queued {scripts_ran |= self.run_next_pending_frame().await;}+ let navigated = self.advance_frame_navigations();let delivered = self.deliver_frame_messages();self.release_detached_frames();- queued_new || scripts_ran || delivered+ queued_new || scripts_ran || delivered || navigated+ }++ fn advance_frame_navigations(&mut self) -> bool {+ if self.frames.is_empty() { return false; }+ let pending = match &self.js { Some(js) => js.take_pending_frame_navigations(), None => return false };+ let changed = !pending.is_empty();+ for (id, url, method, body) in pending {+ let Some(frame) = self.frames.iter().find(|frame| frame.frame_id() == id) else { continue; };+ let owner = frame.parent_frame_id();+ let script = format!("(function(){{const frame=globalThis.__obscura_frameElements[{id}]; if(frame && frame._frameId==={id} && frame.isConnected) frame._loadIframeSrc({},{{method:{},body:{}}});}})()",+ serde_json::to_string(&url).unwrap(), serde_json::to_string(&method).unwrap(), serde_json::to_string(&body).unwrap());+ self.execute_frame_owner_script(owner, &script);+ }+ changed}/// URLs of the page's live child frames, in creation order.@@ -7383,6 +7398,62 @@ mod tests {assert_eq!(page.frame_urls(), vec!["about:srcdoc", "about:srcdoc"]);}+ /// A page script can call a frame's own Location methods (lazy-load+ /// scripts do `iframe.contentWindow.location.replace(src)`). The running+ /// context is then the page's, so the navigation was queued on the top+ /// document, which loaded the iframe's URL in place of its own.+ #[tokio::test(flavor = "current_thread")]+ async fn frame_location_navigation_loads_the_child_and_ignores_detached_windows() {+ use std::io::{Read as _, Write as _};+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ std::thread::spawn(move || {+ let (mut socket, _) = listener.accept().unwrap();+ let mut request = [0; 4096];socket.read(&mut request).unwrap();+ let body = "<!doctype html><title>Child after</title><p>after</p>";+ write!(socket, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();+ });+ let mut page = import_map_test_page("frame-location-commit", &base,+ "<title>Parent</title><iframe srcdoc='<p>before</p>'></iframe>");+ pump_srcdoc_frames(&mut page).await;+ page.evaluate_script(&format!("document.querySelector('iframe').contentWindow.location.replace({});1",serde_json::to_string(&format!("{base}/after")).unwrap())).unwrap();+ assert!(!page.has_pending_navigation());+ for _ in 0..20 {+ page.advance_frames().await;+ if let Some(js)=page.js.as_mut() {js.run_event_loop_bounded(20).await.unwrap();}+ if page.frame_urls().iter().any(|url|url.ends_with("/after")) { break; }+ }+ assert_eq!(page.frame_urls(),vec![format!("{base}/after")]);+ assert_eq!(page.evaluate_in_frame(0,"document.body.textContent").unwrap(),serde_json::json!("after"));+ assert_eq!(page.evaluate_script("document.title").unwrap(),serde_json::json!("Parent"));+ page.evaluate_script("globalThis.stale=document.querySelector('iframe').contentWindow;document.querySelector('iframe').remove();1").unwrap();+ page.advance_frames().await;+ page.evaluate_script("stale.location.assign('https://other.test/');1").unwrap();+ assert!(!page.has_pending_navigation(),"a discarded child cannot navigate the top document");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn navigating_a_frame_from_the_page_keeps_the_top_document() {+ let mut page = import_map_test_page("frame-location-from-page", "https://parent.test",+ "<title>Top document</title><body><iframe srcdoc='<form id=f action=/x></form>'></iframe></body>");+ pump_srcdoc_frames(&mut page).await;+ for call in [+ "location.replace('https://embed.test/video')",+ "location.assign('https://embed.test/video')",+ "location.href = 'https://embed.test/video'",+ "location.reload()",+ "document.getElementById('f').submit()",+ ] {+ page.evaluate_script(&format!("document.querySelector('iframe').contentWindow.{call}; 1")).unwrap();+ assert!(!page.has_pending_navigation(), "{call} queued a navigation on the top document");+ }+ assert_eq!(page.evaluate_script("[location.href, document.title]").unwrap(),+ serde_json::json!(["https://parent.test/app/index.html", "Top document"]));+ // The top document still navigates itself.+ page.evaluate_script("location.href = 'https://other.test/'; 1").unwrap();+ assert!(page.has_pending_navigation());+ }+#[tokio::test(flavor = "current_thread")]async fn iframe_srcdoc_replacement_cancels_stale_documents() {let mut page = import_map_test_page("srcdoc-replace", "https://parent.test", "<body></body>");diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 1a66d14b..f834e0f0 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -5207,7 +5207,7 @@ class Element extends Node {}_loadIframeSrc(url, submission) {if (!submission && this.hasAttribute('srcdoc')) { this._loadIframeSrcdoc(); return; }- if (url === 'about:blank' || !url) { this._resetIframeFrame(); return; }+ if (url === 'about:blank' || !url) { this._resetIframeFrame(); if (submission) _ensureInitialFrameRealm(this); return; }let fullUrl = url;if (!url.includes('://')) {try { fullUrl = new URL(url, _domParse("document_url") || "about:blank").href; } catch(e) {}@@ -5505,9 +5505,9 @@ class Element extends Node {}}if (method === 'POST') {- __obscuraCore.ops.op_navigate(targetUrl, 'POST', encoded);+ __obscuraCore.ops.op_navigate(targetUrl, 'POST', encoded, _realmFrameId);} else {- __obscuraCore.ops.op_navigate(targetUrl, 'GET', '');+ __obscuraCore.ops.op_navigate(targetUrl, 'GET', '', _realmFrameId);}}reset() {@@ -7886,7 +7886,7 @@ function __locationNavigate(url, replace) {return;}globalThis.__virtualUrl = r;- __obscuraCore.ops.op_navigate(r, 'GET', '');+ __obscuraCore.ops.op_navigate(r, 'GET', '', _realmFrameId);}// Location setters (HTML spec): change one component of a copy of the current// URL, then navigate to it. Only the fragment setter can stay in-document.@@ -7923,7 +7923,7 @@ globalThis.location = {set port(v) { __locationSetPart('port', v); },toString() { return this.href; },assign(url) { __locationNavigate(url, false); },- reload() { var r = _resolveUrl(this.href); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },+ reload() { var r = _resolveUrl(this.href); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', '', _realmFrameId); },replace(url) { __locationNavigate(url, true); },};const _locationObj = globalThis.location;@@ -13361,7 +13361,7 @@ globalThis.atob = globalThis.atob || ((s) => {let forwardCleared = false;const session = () => {try {- const [start, current, length] = String(__obscuraCore.ops.op_session_history())+ const [start, current, length] = String(__obscuraCore.ops.op_session_history(_realmFrameId)).split(",").map(Number);if (length > 0) {return {start, current, before: start,@@ -13487,9 +13487,9 @@ globalThis.atob = globalThis.atob || ((s) => {// Another document's entry: the page loads it and moves its cursor.const {start, current, before, after} = session();if (target < 0 && -target <= before) {- __obscuraCore.ops.op_history_traverse(start + target);+ __obscuraCore.ops.op_history_traverse(start + target, _realmFrameId);} else if (target >= stack.length && target - (stack.length - 1) <= after) {- __obscuraCore.ops.op_history_traverse(current + target - (stack.length - 1));+ __obscuraCore.ops.op_history_traverse(current + target - (stack.length - 1), _realmFrameId);}return;}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 76a3ac76..64956fb5 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -1243,6 +1243,16 @@ impl RealmStates {removed}+ pub(crate) fn has_pending_navigation(&self) -> bool {+ self.entries.iter().any(|(_, _, state)| state.borrow().pending_navigation.is_some())+ }++ pub(crate) fn take_pending_navigations(&self) -> Vec<(u32, String, String, String)> {+ self.entries.iter().filter_map(|(_, id, state)| {+ state.borrow_mut().pending_navigation.take().map(|(url, method, body)| (*id, url, method, body))+ }).collect()+ }+pub(crate) fn by_frame_id(&self, frame_id: u32) -> Option<SharedState> {self.entries.iter()@@ -6451,12 +6461,17 @@ pub struct SessionHistory {pub current: usize,}+fn navigation_state(state: &OpState, frame_id: u32) -> Option<SharedState> {+ if frame_id == 0 { return Some(state.borrow::<SharedState>().clone()); }+ state.try_borrow::<Rc<RefCell<RealmStates>>>()?.borrow().by_frame_id(frame_id)+}+/// `"documentStart,current,length"` of the session history; length is 0 when/// this realm has none.#[op2]#[string]-fn op_session_history(scope: &mut v8::PinScope, state: &OpState) -> String {- let gs = realm_state(scope, state);+fn op_session_history(state: &OpState, frame_id: u32) -> String {+ let Some(gs) = navigation_state(state, frame_id) else { return "0,0,0".into(); };let gs = gs.borrow();let history = &gs.session_history;format!("{},{},{}", history.document_start, history.current, history.urls.len())@@ -6465,8 +6480,8 @@ fn op_session_history(scope: &mut v8::PinScope, state: &OpState) -> String {/// Queue a traversal to another document's session history entry. Returns/// false when the index is out of range.#[op2(fast)]-fn op_history_traverse(scope: &mut v8::PinScope, state: &OpState, index: u32) -> bool {- let gs = realm_state(scope, state);+fn op_history_traverse(state: &OpState, index: u32, frame_id: u32) -> bool {+ let Some(gs) = navigation_state(state, frame_id) else { return false; };let mut gs = gs.borrow_mut();let index = index as usize;let Some(url) = gs.session_history.urls.get(index).cloned() else {@@ -6478,16 +6493,19 @@ fn op_history_traverse(scope: &mut v8::PinScope, state: &OpState, index: u32) ->}// A frame that navigates itself must not move the top document. Recording the-// navigation against the calling realm keeps it inside that frame.+// navigation against the realm that owns the Location object keeps it inside+// that frame, also when another realm calls it: the page can run+// `iframe.contentWindow.location.replace(url)`, and the running context is+// then the page's, not the frame's (see `frame_state`).#[op2(fast)]fn op_navigate(- scope: &mut v8::PinScope,state: &OpState,#[string] url: &str,#[string] method: &str,#[string] body: &str,+ frame_id: u32,) {- let gs = realm_state(scope, state);+ let Some(gs) = navigation_state(state, frame_id) else { return; };let mut gs = gs.borrow_mut();// Only queue the navigation — do NOT change the realm URL here. The URL is// updated on commit via `set_url` once the navigation is actually performed.diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex a8cac29b..7ef5adb5 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1196,6 +1196,12 @@ impl ObscuraJsRuntime {pub fn has_pending_frame_tasks(&self) -> bool {let state = self.state.borrow();!state.pending_frames.is_empty() || !state.pending_frame_messages.is_empty()+ || self.realm_states().borrow().has_pending_navigation()+ }++ #[doc(hidden)]+ pub fn take_pending_frame_navigations(&self) -> Vec<(u32, String, String, String)> {+ self.realm_states().borrow().take_pending_navigations()}/// postMessage traffic waiting to be delivered to another realm.