The headless browser for AI agents and web scraping
Expose session history to window.history
SGavrlba807f4d2504
diff --git a/crates/obscura-browser/src/fork_virtual_url.rs b/crates/obscura-browser/src/fork_virtual_url.rsindex b9ce3335..77974f2e 100644--- a/crates/obscura-browser/src/fork_virtual_url.rs+++ b/crates/obscura-browser/src/fork_virtual_url.rs@@ -42,7 +42,7 @@ impl Page {return false;}self.url = Some(parsed);- self.push_history(self.url_string());+ self.push_same_document_history(self.url_string());true}}diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex beeda896..55767045 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -292,6 +292,13 @@ pub struct Page {/// Pushed on every successful navigation; truncated on goBack -> new nav.pub history: Vec<String>,pub history_index: usize,+ /// Index of the current document's first history entry. Entries after it+ /// up to `history_index` are its same-document (pushState) URLs.+ document_history_start: usize,+ /// Entry a page-initiated `history.go()` is traversing to, taken with the+ /// pending navigation that loads it. Committing that load moves the cursor+ /// to the entry instead of appending a new one.+ pending_history_traversal: std::sync::Mutex<Option<usize>>,pub network_events: Vec<NetworkEvent>,response_bodies: std::collections::HashMap<String, StoredResponseBody>,response_body_order: std::collections::VecDeque<String>,@@ -1118,6 +1125,8 @@ impl Page {navigation_chain_limit: None,history: Vec::new(),history_index: 0,+ document_history_start: 0,+ pending_history_traversal: std::sync::Mutex::new(None),network_events: Vec::new(),response_bodies: std::collections::HashMap::new(),response_body_order: std::collections::VecDeque::new(),@@ -1767,6 +1776,8 @@ impl Page {rt.set_encoding(&self.encoding);rt.set_title(&self.title);rt.set_referrer(&self.referrer);+ let (session_history, session_index) = self.predicted_session_history();+ rt.set_session_history(session_history, session_index, session_index);#[cfg(feature = "stealth")]if self.stealth_client.is_some() {@@ -3180,18 +3191,79 @@ impl Page {/// entries past the cursor (matches real Chrome: navigating after a/// goBack clobbers the forward history).pub fn push_history(&mut self, url: String) {+ self.push_history_entry(url, true);+ }++ /// Record a URL the current document reached through pushState or+ /// replaceState. It stays part of the same document's entries.+ pub(crate) fn push_same_document_history(&mut self, url: String) {+ self.push_history_entry(url, false);+ }++ fn push_history_entry(&mut self, url: String, new_document: bool) {if url.is_empty() {return;}- // Don't dupe consecutive entries (Page.reload would otherwise pile up).- if self.history.get(self.history_index) == Some(&url) {- return;+ let traversal = if new_document {+ self.pending_history_traversal.lock().ok().and_then(|mut index| index.take())+ } else {+ None+ };+ if let Some(index) = traversal.filter(|&index| self.history.get(index) == Some(&url)) {+ self.history_index = index;+ } else if self.history.get(self.history_index) != Some(&url) {+ // Consecutive duplicates are skipped so Page.reload does not pile up entries.+ if !self.history.is_empty() && self.history_index < self.history.len() - 1 {+ self.history.truncate(self.history_index + 1);+ }+ self.history.push(url);+ self.history_index = self.history.len() - 1;+ }+ if new_document {+ self.document_history_start = self.history_index;+ }+ self.sync_js_session_history();+ }++ /// Replace the history and cursor, treating the current document as the+ /// entry at `index`. Page.navigateToHistoryEntry and+ /// Page.resetNavigationHistory rewrite history through this.+ pub fn set_history(&mut self, history: Vec<String>, index: usize) {+ self.history = history;+ self.history_index = index;+ self.document_history_start = index;+ self.sync_js_session_history();+ }++ /// Give the document's `window.history` the page's session history, so+ /// `history.length` and cross-document `history.go()` see every entry.+ pub fn sync_js_session_history(&self) {+ if let Some(js) = &self.js {+ js.set_session_history(+ self.history.clone(),+ self.document_history_start,+ self.history_index,+ );+ }+ }++ /// The session history as it will be once the document being created+ /// commits through `push_history`: the entry a traversal targets, the+ /// current entry on a reload, or a new entry replacing the forward ones.+ fn predicted_session_history(&self) -> (Vec<String>, usize) {+ let url = self.url_string();+ let traversal = self.pending_history_traversal.lock().ok().and_then(|index| *index);+ if let Some(index) = traversal.filter(|&index| self.history.get(index) == Some(&url)) {+ return (self.history.clone(), index);}- if !self.history.is_empty() && self.history_index < self.history.len() - 1 {- self.history.truncate(self.history_index + 1);+ if self.history.get(self.history_index) == Some(&url) {+ return (self.history.clone(), self.history_index);}- self.history.push(url);- self.history_index = self.history.len() - 1;+ let mut urls: Vec<String> =+ self.history.iter().take(self.history_index + 1).cloned().collect();+ urls.push(url);+ let index = urls.len() - 1;+ (urls, index)}/// Move the history cursor without re-navigating; used by@@ -4632,11 +4704,12 @@ impl Page {}pub fn take_pending_navigation(&self) -> Option<(String, String, String)> {- if let Some(js) = &self.js {- js.take_pending_navigation()- } else {- None+ let js = self.js.as_ref()?;+ let navigation = js.take_pending_navigation()?;+ if let Ok(mut traversal) = self.pending_history_traversal.lock() {+ *traversal = js.take_pending_history_traversal();}+ Some(navigation)}pub fn has_pending_navigation(&self) -> bool {@@ -5503,6 +5576,62 @@ mod tests {assert_eq!(page.navigation_chain_limit(), 17);}+ /// Issue #1068: page script sees the tab's session history. history.length+ /// counts earlier documents, and history.back()/forward() load them while+ /// moving the history cursor instead of appending entries.+ #[tokio::test(flavor = "current_thread")]+ async fn page_history_traverses_across_documents() {+ let one = "data:text/html,<title>one</title>";+ let two = "data:text/html,<title>two</title>";+ let mut page = page_without_chain_limit("history-across-documents");+ page.navigate(one).await.unwrap();+ page.navigate(two).await.unwrap();+ assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));++ page.evaluate("history.back()");+ assert!(page.process_pending_navigation().await.unwrap());+ assert_eq!(page.url_string(), one);+ assert_eq!((page.history.len(), page.history_index), (2, 0));+ assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));++ page.evaluate("history.go(1)");+ assert!(page.process_pending_navigation().await.unwrap());+ assert_eq!(page.url_string(), two);+ assert_eq!((page.history.len(), page.history_index), (2, 1));++ // Out-of-range traversal stays put.+ page.evaluate("history.go(5)");+ assert!(!page.process_pending_navigation().await.unwrap());+ assert_eq!(page.url_string(), two);+ }++ /// Same-document entries sit between the documents: a push drops the+ /// forward documents, and back() past the document's own entries loads+ /// the previous document.+ #[tokio::test(flavor = "current_thread")]+ async fn page_history_counts_same_document_entries_once() {+ let one = "data:text/html,<title>one</title>";+ let two = "data:text/html,<title>two</title>";+ let mut page = page_without_chain_limit("history-same-document");+ page.navigate(one).await.unwrap();+ page.navigate(two).await.unwrap();+ page.evaluate("history.back()");+ page.process_pending_navigation().await.unwrap();+ assert_eq!(page.url_string(), one);++ page.evaluate("history.pushState(null, '', '#a')");+ assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));+ // Recording the pushState URL on the page must not double count it.+ page.sync_virtual_url();+ assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));++ page.evaluate("history.go(-2)");+ assert!(!page.process_pending_navigation().await.unwrap());+ page.evaluate("history.back()");+ assert!(!page.process_pending_navigation().await.unwrap());+ assert_eq!(page.evaluate("location.hash"), serde_json::json!(""));+ }+#[test]fn a_per_page_navigation_chain_limit_wins_over_the_environment() {std::env::set_var("OBSCURA_NAV_CHAIN_LIMIT", "17");diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 415891f3..bf10219d 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -1607,6 +1607,7 @@ pub async fn handle(if let Some(page) = ctx.get_session_page_mut(session_id) {page.history = saved_history;page.history_index = prev_index;+ page.sync_js_session_history();}return Err(e.to_string());}@@ -1614,8 +1615,7 @@ pub async fn handle(let page = ctx.get_session_page_mut(session_id).ok_or("No page for session")?;- page.history = saved_history;- page.history_index = entry_id;+ page.set_history(saved_history, entry_id);// Flush script-initiated network events before draining,// matching do_navigate — otherwise fetch/XHR requests the// navigated page starts are dropped from CDP events (#920).@@ -1645,8 +1645,7 @@ pub async fn handle(}"resetNavigationHistory" => {if let Some(page) = ctx.get_session_page_mut(session_id) {- page.history.clear();- page.history_index = 0;+ page.set_history(Vec::new(), 0);}Ok(json!({}))}diff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rsindex 4c428ac4..a22371a1 100644--- a/crates/obscura-cdp/src/domains/target.rs+++ b/crates/obscura-cdp/src/domains/target.rs@@ -91,6 +91,9 @@ pub async fn handle(let committed_document = if let Some(page) = ctx.get_page_mut(&page_id) {if url == "about:blank" || url.is_empty() {page.navigate_blank();+ // Chrome keeps the new tab's about:blank as the first+ // session history entry, so history.back() can return to it.+ page.push_history(page.url_string());None} else {page.navigate(url).await.ok().map(|_| {diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex fca7b9f2..4469b2cb 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -11370,6 +11370,21 @@ globalThis.atob = globalThis.atob || ((s) => {(() => {const stack = [{state: null, url: undefined}]; // initial entry; url=undefined means "use document URL"let idx = 0;+ // The page owns the tab's session history. `stack` covers only this+ // document's entries; entries before it and after the current one come+ // from the page, and a push drops the forward ones as the page will.+ let forwardCleared = false;+ const session = () => {+ try {+ const [start, current, length] = String(__obscuraCore.ops.op_session_history())+ .split(",").map(Number);+ if (length > 0) {+ return {start, current, before: start,+ after: forwardCleared ? 0 : Math.max(0, length - 1 - current)};+ }+ } catch (e) {}+ return {start: 0, current: 0, before: 0, after: 0};+ };const historyToken = Symbol("History");const resolveHistoryUrl = (url, method) => {// A missing url (pushState/replaceState called with < 3 args) keeps the@@ -11423,7 +11438,10 @@ globalThis.atob = globalThis.atob || ((s) => {constructor(token) {if (token !== historyToken) throw new TypeError("Illegal constructor");}- get length() { return stack.length; }+ get length() {+ const {before, after} = session();+ return before + stack.length + after;+ }get state() { return stack[idx].state; }get scrollRestoration() { return this._scrollRestoration || "auto"; }set scrollRestoration(value) {@@ -11440,6 +11458,7 @@ globalThis.atob = globalThis.atob || ((s) => {stack.length = idx + 1;stack.push({state: state ?? null, url: resolved});idx = stack.length - 1;+ forwardCleared = true;applyVirtual();fireHashChangeIfNeeded(prevUrl);}@@ -11453,8 +11472,18 @@ globalThis.atob = globalThis.atob || ((s) => {go(n) {n = (n | 0);if (n === 0) return; // real spec: go(0) reloads. We don't reload SPAs.- const next = Math.max(0, Math.min(stack.length - 1, idx + n));- if (next === idx) return;+ const target = idx + n;+ if (target < 0 || target >= stack.length) {+ // 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);+ } else if (target >= stack.length && target - (stack.length - 1) <= after) {+ __obscuraCore.ops.op_history_traverse(current + target - (stack.length - 1));+ }+ return;+ }+ const next = target;const prevUrl = __currentUrl();idx = next;applyVirtual();diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex cfba8ff9..40ee3f15 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -133,6 +133,15 @@ pub struct ObscuraState {#[cfg(feature = "stealth")]pub stealth_client: Option<Arc<StealthHttpClient>>,pub pending_navigation: Option<(String, String, String)>,+ /// The tab's session history as the owning page sees it: entry URLs, the+ /// index of this document's first entry, and the current index. Empty+ /// for frames and for runtimes outside a page, where `history` only+ /// covers the document's own same-document entries.+ pub session_history: SessionHistory,+ /// Session history index a cross-document `history.go()` asked for. It+ /// travels with `pending_navigation`, which carries the entry's URL, so+ /// the page can move its cursor instead of appending an entry.+ pub pending_history_traversal: Option<usize>,pub intercept_tx: Option<tokio::sync::mpsc::UnboundedSender<InterceptedRequest>>,pub intercept_enabled: bool,pub intercept_page_id: String,@@ -358,6 +367,8 @@ impl ObscuraState {#[cfg(feature = "stealth")]stealth_client: None,pending_navigation: None,+ session_history: SessionHistory::default(),+ pending_history_traversal: None,intercept_tx: None,intercept_enabled: false,intercept_page_id: String::new(),@@ -5143,6 +5154,39 @@ fn op_set_cookie(scope: &mut v8::PinScope, state: &OpState, #[string] cookie_strjar.set_cookie_from_js(cookie_str, &url);}+#[derive(Debug, Clone, Default)]+pub struct SessionHistory {+ pub urls: Vec<String>,+ pub document_start: usize,+ pub current: usize,+}++/// `"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);+ let gs = gs.borrow();+ let history = &gs.session_history;+ format!("{},{},{}", history.document_start, history.current, history.urls.len())+}++/// 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);+ let mut gs = gs.borrow_mut();+ let index = index as usize;+ let Some(url) = gs.session_history.urls.get(index).cloned() else {+ return false;+ };+ gs.pending_navigation = Some((url, "GET".to_string(), String::new()));+ gs.pending_history_traversal = Some(index);+ true+}+// A frame that navigates itself must not move the top document. Recording the// navigation against the calling realm keeps it inside that frame.#[op2(fast)]@@ -6179,6 +6223,8 @@ pub fn build_extension() -> Extension {op_get_cookies(),op_set_cookie(),op_navigate(),+ op_session_history(),+ op_history_traverse(),op_frame_document_ready(),op_post_frame_message(),op_sleep(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 3fcc159c..742af545 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1263,6 +1263,20 @@ impl ObscuraJsRuntime {self.state.borrow_mut().pending_navigation.take()}+ /// Session history index that accompanies the pending navigation when+ /// page script traversed to another document with `history.go()`.+ pub fn take_pending_history_traversal(&self) -> Option<usize> {+ self.state.borrow_mut().pending_history_traversal.take()+ }++ pub fn set_session_history(&self, urls: Vec<String>, document_start: usize, current: usize) {+ self.state.borrow_mut().session_history = crate::ops::SessionHistory {+ urls,+ document_start,+ current,+ };+ }+pub fn has_pending_navigation(&self) -> bool {self.state.borrow().pending_navigation.is_some()}