Skip to content

The headless browser for AI agents and web scraping

fix(browser): preserve same-document history traversal (#1577)

SGavrl0ecc41770da5
diff --git a/crates/obscura-browser/src/fork_virtual_url.rs b/crates/obscura-browser/src/fork_virtual_url.rs
index 77974f2e..abdc50ec 100644
--- a/crates/obscura-browser/src/fork_virtual_url.rs
+++ b/crates/obscura-browser/src/fork_virtual_url.rs
@@ -13,6 +13,7 @@
//! `self.sync_virtual_url()`.
use url::Url;
+use obscura_js::runtime::HistoryUpdate;
use crate::page::Page;
@@ -24,25 +25,44 @@ impl Page {
let Some(js) = self.js.as_mut() else {
return false;
};
- let Ok(virtual_url) = js.evaluate("globalThis.__virtualUrl || ''") else {
+ let Ok(value) = js.take_history_update() else {
return false;
};
- let Some(virtual_url) = virtual_url.as_str().filter(|url| !url.is_empty()) else {
+ self.adopt_virtual_url(value)
+ }
+
+ /// Flush history mutations before replacing a document, without adopting
+ /// a Location setter's uncommitted navigation preview.
+ pub fn sync_history_updates(&mut self) -> bool {
+ let Some(js) = self.js.as_mut() else { return false; };
+ let Ok(value) = js.take_history_update() else { return false; };
+ if !matches!(&value, HistoryUpdate::Entries { .. }) { return false; }
+ self.adopt_virtual_url(value)
+ }
+
+ fn adopt_virtual_url(&mut self, value: HistoryUpdate) -> bool {
+ let virtual_url = match &value {
+ HistoryUpdate::Url(url) | HistoryUpdate::Entries { url, .. } => url,
+ };
+ if virtual_url.is_empty() {
return false;
};
let Ok(parsed) = Url::parse(virtual_url) else {
return false;
};
- if self.url.as_ref() == Some(&parsed) {
- return false;
- }
- // A web document must not become a file:// page without loading one:
// page.url keys the file:// sub-resource gate (#1069).
if crate::page::cross_scheme_to_file(&self.url_string(), virtual_url) {
return false;
}
- self.url = Some(parsed);
- self.push_same_document_history(self.url_string());
- true
+ let changed = self.url.as_ref() != Some(&parsed);
+ if matches!(&value, HistoryUpdate::Entries { .. }) {
+ self.apply_history_update(value);
+ self.url = Some(parsed);
+ self.sync_js_session_history();
+ } else if changed {
+ self.url = Some(parsed);
+ self.push_same_document_history(self.url_string());
+ }
+ changed
}
}
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index cf9e9020..55156c66 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -4,7 +4,7 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use obscura_dom::{parse_html, DomTree};
use obscura_js::frame::FrameRealm;
use obscura_js::ops::{OriginStorage, max_live_frames, NavigationTiming};
-use obscura_js::runtime::ObscuraJsRuntime;
+use obscura_js::runtime::{HistoryUpdate, ObscuraJsRuntime};
use obscura_net::{
CallbackRegistry, ObscuraHttpClient, ObscuraNetError, RequestCallback, ResourceRequest,
ResourceType, Response, ResponseCallback,
@@ -3381,6 +3381,37 @@ impl Page {
self.push_history_entry(url, false);
}
+ pub(crate) fn apply_history_update(&mut self, update: HistoryUpdate) {
+ let HistoryUpdate::Entries { start, index, old_length, truncate_forward, first, urls, .. } = update else { return; };
+ let Some(end) = first.checked_add(urls.len()) else { return; };
+ let length = if truncate_forward { end } else { old_length };
+ if first > old_length || index >= length || (!truncate_forward && end > old_length) { return; }
+ let current_url = self.url_string();
+ if urls.iter().any(|url| cross_scheme_to_file(&current_url, url)) { return; }
+ if self.history.is_empty() && start == 0 {
+ self.history.push(current_url);
+ }
+ let Some(document_end) = start.checked_add(old_length).filter(|&end| end <= self.history.len()) else { return; };
+ let Some(changed_end) = start.checked_add(end) else { return; };
+ self.history.splice(start + first..changed_end.min(document_end), urls);
+ self.document_history_start = start;
+ self.history_index = start + index;
+ if truncate_forward {
+ self.history.truncate(start + length);
+ }
+ }
+
+ /// Traverse an entry belonging to the live document without replacing its runtime.
+ pub fn traverse_same_document_history(&mut self, index: usize) -> bool {
+ self.sync_history_updates();
+ let Some(url) = self.history.get(index) else { return false; };
+ let expression = format!("globalThis.__obscuraHistory.traverse({}, {})", index,
+ serde_json::to_string(url).unwrap_or_default());
+ if self.evaluate(&expression) != serde_json::json!(true) { return false; }
+ self.sync_virtual_url();
+ true
+ }
+
fn push_history_entry(&mut self, url: String, new_document: bool) {
if url.is_empty() {
return;
@@ -3413,6 +3444,13 @@ impl Page {
self.history = history;
self.history_index = index;
self.document_history_start = index;
+ if self.history.is_empty() {
+ let url = self.url_string();
+ if let Some(js) = self.js.as_mut() {
+ let _ = js.execute_script("<reset-history>", &format!(
+ "globalThis.__obscuraHistory.reset({})", serde_json::to_string(&url).unwrap_or_default()));
+ }
+ }
self.sync_js_session_history();
}
@@ -3464,6 +3502,7 @@ impl Page {
initial_referrer: &str,
initial_initiator: Option<&Url>,
) -> Result<(), PageError> {
+ self.sync_history_updates();
// file:// is a local file read. Every client route (CLI, CDP's
// Page.navigate/reload/history and Target.createTarget, the MCP
// tools) ends up here, so the context's opt-in is enforced once
@@ -5228,6 +5267,7 @@ impl Page {
method: &str,
body: &str,
) -> Result<(), PageError> {
+ self.sync_history_updates();
let initiator = self.url.clone();
let source_url = initiator.as_ref().and_then(|source| {
Url::parse(url).ok().map(|target| navigation_referrer(source, &target))
@@ -5293,7 +5333,7 @@ mod tests {
register_linked_stylesheet_script, script_response_is_executable, split_css_imports,
stylesheet_graph_is_origin_clean, truncate_on_char_boundary, url_matches_cdp_pattern,
LoadedStylesheet, PendingFrameWork, StylesheetImport, DEFAULT_NAVIGATION_CHAIN_LIMIT,
- Page, BrowserContext, LifecycleState, BASE64,
+ Page, BrowserContext, LifecycleState, HistoryUpdate, BASE64,
};
#[cfg(feature = "render")]
use super::remaining_settle_resource_warmup_ms;
@@ -6657,6 +6697,158 @@ mod tests {
assert_eq!(page.url_string(), two);
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn same_document_history_keeps_entries_when_the_cursor_moves() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-cursor");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { globalThis.marker=42; history.pushState({n:1}, '', '#one'); history.pushState({n:2}, '', '#two'); })()");
+ page.sync_virtual_url();
+ let entries = vec![url.to_string(), format!("{url}#one"), format!("{url}#two")];
+ assert_eq!(page.history, entries);
+ assert_eq!(page.history_index, 2);
+ page.evaluate("history.back()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, entries);
+ assert_eq!(page.history_index, 1);
+ assert_eq!(page.evaluate("[marker, history.state.n, history.length]"), serde_json::json!([42, 1, 3]));
+ page.evaluate("history.replaceState({n:3}, '', '#replaced')");
+ page.sync_virtual_url();
+ assert_eq!(page.history.len(), 3);
+ assert_eq!(page.history[1], format!("{url}#replaced"));
+ page.evaluate("history.forward()");
+ page.sync_virtual_url();
+ assert_eq!(page.history_index, 2);
+ assert_eq!(page.evaluate("history.state.n"), serde_json::json!(2.0));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn same_document_history_keeps_distinct_entries_with_the_same_url() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-same-url");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { history.pushState({n:1}, ''); history.pushState({n:2}, ''); })()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![url.to_string(); 3]);
+ assert_eq!(page.history_index, 2);
+ page.evaluate("history.back()");
+ page.sync_virtual_url();
+ assert_eq!(page.history_index, 1);
+ assert_eq!(page.evaluate("history.state.n"), serde_json::json!(1.0));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn same_document_history_sync_ignores_authored_json_serialization() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-json-override");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { history.pushState({n:1}, '', '#one'); JSON.stringify=()=> '\"forged\"'; Array.prototype.toJSON=()=> 'forged'; })()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![url.to_string(), format!("{url}#one")]);
+ assert_eq!(page.history_index, 1);
+ assert_eq!(page.url_string(), format!("{url}#one"));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_keeps_native_document_position_when_authors_patch_array_map() {
+ let one = "data:text/html,<title>one</title>";
+ let two = "data:text/html,<title>two</title>";
+ let mut page = page_without_chain_limit("history-native-position");
+ page.navigate(one).await.unwrap();
+ page.navigate(two).await.unwrap();
+ page.evaluate("(() => { const map=Array.prototype.map; Array.prototype.map=function(...args){if(this.length===3 && this.every(v=>typeof v==='string' && /^\\d+$/.test(v)))throw new Error('authored map');return Reflect.apply(map,this,args);}; history.pushState(1,'','#one'); })()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![one.to_string(), two.to_string(), format!("{two}#one")]);
+ assert_eq!(page.history_index, 2);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_metadata_is_bounded_by_entries() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-metadata");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { for(let i=0;i<10000;i++) history.replaceState(i, '', '#'+i); })()");
+ let update = page.js.as_mut().unwrap().take_history_update().unwrap();
+ assert!(matches!(update, HistoryUpdate::Entries { urls, .. }
+ if urls.len() == 1 && urls[0].len() < 512), "one entry must not retain a mutation log");
+ page.evaluate("history.replaceState(null, '', '#last')");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![format!("{url}#last")]);
+ assert_eq!(page.history_index, 0);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_does_not_transfer_unchanged_entries() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-incremental-sync");
+ page.navigate(url).await.unwrap();
+ for index in 0..1000 {
+ page.evaluate(&format!("history.pushState({index}, '', '#{index}')"));
+ page.sync_virtual_url();
+ }
+ page.evaluate("history.replaceState(null, '', '#last')");
+ let update = page.js.as_mut().unwrap().take_history_update().unwrap();
+ assert!(matches!(update, HistoryUpdate::Entries { urls, .. }
+ if urls.len() == 1 && urls[0].len() < 512), "one changed entry must not transfer the unchanged history");
+ page.evaluate("history.replaceState(null, '', '#verified')");
+ page.sync_virtual_url();
+ assert_eq!(page.history.len(), 1001);
+ assert_eq!(page.history[0], url);
+ assert_eq!(page.history[1000], format!("{url}#verified"));
+ page.evaluate("history.go(-500)");
+ page.sync_virtual_url();
+ assert_eq!(page.history_index, 500);
+ assert_eq!(page.url_string(), format!("{url}#499"));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_keeps_only_surviving_batched_changes() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-batched-changes");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { history.pushState(1, '', '#one'); history.pushState(2, '', '#two'); history.pushState(3, '', '#three'); })()");
+ page.sync_virtual_url();
+ page.evaluate("(() => { history.replaceState(4, '', '#discarded'); history.go(-2); history.pushState(5, '', '#last'); })()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![url.to_string(), format!("{url}#one"), format!("{url}#last")]);
+ assert_eq!(page.history_index, 2);
+ page.evaluate("(() => { history.back(); history.replaceState(6, '', '#changed'); history.forward(); })()");
+ page.sync_virtual_url();
+ assert_eq!(page.history, vec![url.to_string(), format!("{url}#changed"), format!("{url}#last")]);
+ assert_eq!(page.history_index, 2);
+ assert_eq!(page.url_string(), format!("{url}#last"));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_does_not_commit_a_pending_location_navigation() {
+ let url = "data:text/html,<title>history</title>";
+ let mut page = page_without_chain_limit("history-location-preview");
+ page.navigate(url).await.unwrap();
+ page.evaluate("(() => { history.pushState(1, '', '#one'); location.href='https://example.org/next'; })()");
+ page.sync_history_updates();
+ assert_eq!(page.url_string(), format!("{url}#one"));
+ assert_eq!(page.history, vec![url.to_string(), format!("{url}#one")]);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_urls_keep_the_committed_origin_during_pending_navigation() {
+ let mut page = import_map_test_page("history-committed-origin", "http://example.com/current", "<title>history</title>");
+ let result = page.evaluate("(() => { location.href='https://other.example/next'; let error=null; try { history.pushState({}, '', 'https://other.example/spoof'); } catch(e) { error=e.name; } history.pushState({n:1}, '', '/kept'); location.href='https://other.example/again'; history.replaceState({n:2}, ''); return {error,href:location.href,state:history.state}; })()");
+ assert_eq!(result, serde_json::json!({"error":"SecurityError","href":"http://example.com/kept","state":{"n":2}}));
+ page.sync_history_updates();
+ assert_eq!(page.url_string(), "http://example.com/kept");
+ assert!(page.history.iter().all(|url| url.starts_with("http://example.com/")));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn history_sync_rejects_non_url_page_values() {
+ let mut page = page_without_chain_limit("history-url-type");
+ page.navigate("data:text/html,<title>history</title>").await.unwrap();
+ page.evaluate("globalThis.__virtualUrl = new Array(100000)");
+ assert!(matches!(page.js.as_mut().unwrap().take_history_update().unwrap(),
+ HistoryUpdate::Url(url) if url.is_empty()));
+ }
+
/// 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.
@@ -6680,7 +6872,8 @@ mod tests {
page.evaluate("history.go(-2)");
assert!(!page.process_pending_navigation().await.unwrap());
page.evaluate("history.back()");
- assert!(!page.process_pending_navigation().await.unwrap());
+ assert!(page.process_pending_navigation().await.unwrap());
+ assert_eq!(page.url_string(), one);
assert_eq!(page.evaluate("location.hash"), serde_json::json!(""));
}
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rs
index f1f80166..c7f6673e 100644
--- a/crates/obscura-cdp/src/domains/page.rs
+++ b/crates/obscura-cdp/src/domains/page.rs
@@ -1759,6 +1759,11 @@ pub async fn handle(
}))
}
"getNavigationHistory" => {
+ let changed = {
+ let page = ctx.get_session_page_mut(session_id).ok_or("No page for session")?;
+ page.sync_history_updates().then(|| (page.frame_id.clone(), page.url_string()))
+ };
+ if let Some((frame, url)) = changed { emit_same_document_navigation(ctx, session_id, &frame, &url); }
let page = ctx
.get_session_page(session_id)
.ok_or("No page for session")?;
@@ -1790,6 +1795,14 @@ pub async fn handle(
}
"navigateToHistoryEntry" => {
let entry_id = params.get("entryId").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
+ let same_document = ctx.get_session_page_mut(session_id).ok_or("No page for session")?
+ .traverse_same_document_history(entry_id);
+ if same_document {
+ let page = ctx.get_session_page(session_id).ok_or("No page for session")?;
+ let (frame, url) = (page.frame_id.clone(), page.url_string());
+ emit_same_document_navigation(ctx, session_id, &frame, &url);
+ return Ok(json!({}));
+ }
// Snapshot history and the current cursor BEFORE moving it, so a
// navigation that fails can roll back to where the page actually is
// instead of leaving currentIndex on an entry it never reached (#920).
@@ -1861,6 +1874,7 @@ pub async fn handle(
}
"resetNavigationHistory" => {
if let Some(page) = ctx.get_session_page_mut(session_id) {
+ page.sync_history_updates();
page.set_history(Vec::new(), 0);
}
Ok(json!({}))
@@ -2347,6 +2361,32 @@ mod tests {
assert_eq!(preload_state(&mut ctx, &session).await, json!([0, 1]));
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn same_document_history_traversal_preserves_the_document_and_state() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session = Some(format!("{page_id}-session"));
+ ctx.sessions.insert(session.clone().unwrap(), page_id);
+ handle("enable", &json!({}), &mut ctx, &session).await.unwrap();
+ handle("navigate", &json!({"url":"data:text/html,<title>history</title>"}), &mut ctx, &session).await.unwrap();
+ let entries = {
+ let page = ctx.get_session_page_mut(&session).unwrap();
+ page.evaluate("(() => { globalThis.marker=42; globalThis.pops=[]; addEventListener('popstate', e=>pops.push(e.state)); history.pushState({n:1}, '', '#one'); })()");
+ page.sync_virtual_url();
+ page.evaluate("history.pushState({n:2}, '', '#two')");
+ page.sync_virtual_url();
+ page.history.clone()
+ };
+ ctx.pending_events.clear();
+ handle("navigateToHistoryEntry", &json!({"entryId":1}), &mut ctx, &session).await.unwrap();
+ let page = ctx.get_session_page_mut(&session).unwrap();
+ assert_eq!(page.history, entries);
+ assert_eq!(page.history_index, 1);
+ assert_eq!(page.evaluate("[globalThis.marker, history.state, globalThis.pops]"), json!([42, {"n":1}, [{"n":1}]]));
+ assert!(ctx.pending_events.iter().any(|e| e.method == "Page.navigatedWithinDocument"));
+ assert!(!ctx.pending_events.iter().any(|e| e.method == "Page.frameNavigated" || e.method == "Runtime.executionContextsCleared"));
+ }
+
// #920: a history navigation that fails to load must not move the recorded
// currentIndex — the page never actually went anywhere, so a later
// getNavigationHistory must still report where it really is.
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 14c38be0..d150d990 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -30,6 +30,7 @@ const __obscuraCore = globalThis.Deno.core;
'__obscura_frameId', '__obscura_parentFrameId', '__obscura_frameWindows',
'__obscura_frameObjects', '__obscura_frameElements', '__obscura_deliverMessage',
'__obscura_liveFrameIds', '__obscura_forgetFrame',
+ '__obscuraHistory',
'__obscura_registerLinkedStylesheet', '__obscura_activateLabel',
'__obscura_isDisabled', '__obscura_labeledControl', '__obscura_interactiveHost',
'__obscura_inputChecked', '__obscura_setInputChecked',
@@ -13626,6 +13627,12 @@ globalThis.atob = globalThis.atob || ((s) => {
(() => {
const stack = [{state: null, url: undefined}]; // initial entry; url=undefined means "use document URL"
let idx = 0;
+ let dirty = false;
+ let syncedLength = 1;
+ let truncateForward = false;
+ let changedStart = Infinity;
+ let changedEnd = 0;
+ const setPrototypeOf = Object.setPrototypeOf;
// 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.
@@ -13636,18 +13643,19 @@ globalThis.atob = globalThis.atob || ((s) => {
.split(",").map(Number);
if (length > 0) {
return {start, current, before: start,
- after: forwardCleared ? 0 : Math.max(0, length - 1 - current)};
+ after: forwardCleared ? 0 : Math.max(0, length - start - stack.length)};
}
} catch (e) {}
return {start: 0, current: 0, before: 0, after: 0};
};
const historyToken = Symbol("History");
const resolveHistoryUrl = (url, method) => {
+ // A Location setter can preview a destination before the document commits.
+ const base = stack[idx].url ?? (_domParse("document_url") || "about:blank");
// A missing url (pushState/replaceState called with < 3 args) keeps the
// current document URL per the HTML spec; capture it so the entry does not
// reset location back to the original document URL.
- if (url === null || url === undefined) return __currentUrl();
- const base = __currentUrl();
+ if (url === null || url === undefined) return base;
let target;
try {
target = new URL(String(url), base);
@@ -13674,9 +13682,18 @@ globalThis.atob = globalThis.atob || ((s) => {
}
return target.href;
};
- const applyVirtual = () => {
+ const applyVirtual = (action) => {
const entry = stack[idx];
globalThis.__virtualUrl = entry.url ?? null;
+ dirty = true;
+ if (action !== 'traverse') {
+ if (idx < changedStart) changedStart = idx;
+ if (idx + 1 > changedEnd) changedEnd = idx + 1;
+ }
+ if (action === 'push') {
+ truncateForward = true;
+ if (changedEnd > stack.length) changedEnd = stack.length;
+ }
};
// Same-document fragment navigation, reached from the Location setters and
// `<a href="#x">` activation. Per the HTML spec it adds a history entry
@@ -13694,7 +13711,7 @@ globalThis.atob = globalThis.atob || ((s) => {
idx = stack.length - 1;
forwardCleared = true;
}
- applyVirtual();
+ applyVirtual(replace ? 'replace' : 'push');
setTimeout(() => {
const ev = new HashChangeEvent('hashchange');
ev.oldURL = prevUrl; ev.newURL = url;
@@ -13740,14 +13757,14 @@ globalThis.atob = globalThis.atob || ((s) => {
stack.push({state: state ?? null, url: resolved});
idx = stack.length - 1;
forwardCleared = true;
- applyVirtual();
+ applyVirtual('push');
fireHashChangeIfNeeded(prevUrl);
}
replaceState(state, _title, url) {
const prevUrl = __currentUrl();
const resolved = resolveHistoryUrl(url, 'replaceState');
stack[idx] = {state: state ?? null, url: resolved};
- applyVirtual();
+ applyVirtual('replace');
fireHashChangeIfNeeded(prevUrl);
}
go(n) {
@@ -13756,18 +13773,18 @@ globalThis.atob = globalThis.atob || ((s) => {
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();
+ const {start, before, after} = session();
if (target < 0 && -target <= before) {
__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), _realmFrameId);
+ __obscuraCore.ops.op_history_traverse(start + target, _realmFrameId);
}
return;
}
const next = target;
const prevUrl = __currentUrl();
idx = next;
- applyVirtual();
+ applyVirtual('traverse');
// Real Chrome fires popstate on back/forward with the destination entry's state.
try {
const ev = new PopStateEvent('popstate', {state: stack[idx].state});
@@ -13778,6 +13795,39 @@ globalThis.atob = globalThis.atob || ((s) => {
back() { this.go(-1); }
forward() { this.go(1); }
}
+ const traverse = History.prototype.go.bind(null);
+ Object.defineProperty(globalThis, '__obscuraHistory', {
+ writable: false, configurable: false,
+ value: Object.freeze({
+ take() {
+ if (!dirty) return null;
+ const urls = setPrototypeOf([], null);
+ const first = changedEnd ? changedStart : syncedLength;
+ for (let i = first; i < changedEnd; i++) urls[i - first] = stack[i].url ?? _domParse('document_url');
+ const url = stack[idx].url ?? _domParse('document_url');
+ const result = [url, idx, syncedLength, truncateForward, first, urls];
+ syncedLength = stack.length;
+ dirty = false; truncateForward = false;
+ changedStart = Infinity; changedEnd = 0;
+ return result;
+ },
+ traverse(index, url) {
+ const target = index - session().start;
+ if (target < 0 || target >= stack.length || target === idx) return false;
+ if ((stack[target].url ?? _domParse('document_url')) !== url) return false;
+ traverse(target - idx);
+ return true;
+ },
+ reset(url) {
+ const entry = {state: stack[idx].state, url};
+ stack.length = 1; stack[0] = entry; idx = 0;
+ dirty = false; syncedLength = 1;
+ truncateForward = false; forwardCleared = false;
+ changedStart = Infinity; changedEnd = 0;
+ globalThis.__virtualUrl = url;
+ },
+ }),
+ });
Object.defineProperty(History.prototype, Symbol.toStringTag, {value: "History"});
Object.defineProperty(globalThis, "History", {
value: History, writable: true, configurable: true,
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 91b6200e..c3fe80f5 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -212,6 +212,21 @@ pub struct AccessibilityStyle {
pub visibility_hidden: Option<bool>,
}
+#[doc(hidden)]
+#[derive(Debug)]
+pub enum HistoryUpdate {
+ Url(String),
+ Entries {
+ url: String,
+ start: usize,
+ index: usize,
+ old_length: usize,
+ truncate_forward: bool,
+ first: usize,
+ urls: Vec<String>,
+ },
+}
+
#[derive(Debug, Clone)]
pub struct RemoteObjectInfo {
/// True when this object is a value that was thrown or that a promise
@@ -2709,6 +2724,30 @@ impl ObscuraJsRuntime {
self.v8_to_json(result)
}
+ /// Read host history metadata without invoking author-defined JSON hooks.
+ pub fn take_history_update(&mut self) -> Result<HistoryUpdate, String> {
+ #[cfg(feature = "render")]
+ self.service_render_resources();
+ self.begin_javascript_task();
+ let result = self.execute_runtime_script("<history-update>",
+ "(() => { const update = globalThis.__obscuraHistory.take(); if (update) return update; const url = globalThis.__virtualUrl; return typeof url === 'string' ? url : ''; })()".to_owned())?;
+ let document_start = self.state.borrow().session_history.document_start;
+ let mut entered = self.runtime();
+ let context = entered.main_context();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ let value = v8::Local::new(scope, result);
+ if value.is_string() {
+ return Ok(HistoryUpdate::Url(value.to_rust_string_lossy(scope)));
+ }
+ let update: (String, usize, usize, bool, usize, Vec<String>) =
+ deno_core::serde_v8::from_v8(scope, value).map_err(|error| error.to_string())?;
+ Ok(HistoryUpdate::Entries {
+ url: update.0, start: document_start, index: update.1,
+ old_length: update.2, truncate_forward: update.3,
+ first: update.4, urls: update.5,
+ })
+ }
+
pub async fn evaluate_for_cdp(
&mut self,
expression: &str,