From 732d32dfd2278fec669df777fe9f45a60f7892bf Mon Sep 17 00:00:00 2001 From: ldm0 Date: Tue, 24 Nov 2026 03:42:07 +0800 Subject: [PATCH] fix(navigation): replace same-URL top-level link entries Resolve link history from the active URL and the source Document origin. Use that result for the navigate event and both renderer-followed and browser-owned commits. Route same-document fragments through the resolved target Window. --- moli-core/tests/viewport.rs | 123 ++++++++++++++++++ .../context_bootstrap/location_navigation.rs | 9 +- .../element/activation/default_action.rs | 52 +------- .../element/activation/targets.rs | 57 ++++++-- .../tests/extracted/navigation_streaming.rs | 53 ++++++++ .../src/script_vm/child_frame_runtime.rs | 15 ++- .../navigation/element_navigation.rs | 43 ++++++ 7 files changed, 277 insertions(+), 75 deletions(-) diff --git a/moli-core/tests/viewport.rs b/moli-core/tests/viewport.rs index 3e4516989b5..32940c62fc4 100644 --- a/moli-core/tests/viewport.rs +++ b/moli-core/tests/viewport.rs @@ -236,6 +236,129 @@ async fn viewport_history_survives_link_and_form_navigation() -> Result<()> { Ok(()) } +#[tokio::test] +async fn viewport_history_uses_the_link_source_origin_for_same_url_navigation() -> Result<()> { + let origin = moli_test_support::FixtureServer::spawn().await?; + let other_origin = moli_test_support::FixtureServer::spawn().await?; + let browser = + Browser::new(BrowserConfig::default().with_layout_policy(LayoutPolicy::Realtime))?; + let previous = origin.url("/static?previous"); + let current = origin.url("/static?current"); + let style = "display:block;width:180px;height:60px"; + + for (case, target, frame_origin, adds_entry) in [ + ("default target", "", None, false), + ("explicit self", "_self", None, false), + ("explicit top", "_top", None, false), + ("explicit parent", "_parent", None, false), + ("same-origin child", "_top", Some(&origin), false), + ("cross-origin child", "_top", Some(&other_origin), true), + ] { + let mut page = browser.fetch(&previous).await?; + page.evaluate_runtime_expression_async(&format!("location.assign({current:?})")) + .await?; + let mut frames = page + .subscribe_viewport_frames(ViewportSurface::default(), 1) + .await?; + let first = frame(&mut frames, |frame| { + frame.navigation.url.as_str() == current && frame.snapshot.is_some() + }) + .await + .with_context(|| format!("{case} initial frame"))?; + assert!(first.navigation.can_go_back, "{case}"); + + let anchor = format!(r#"Open"#); + if let Some(frame_origin) = frame_origin { + let mut child = + url::Url::parse(&frame_origin.url("/compat/child-dynamic-markup-document"))?; + child.query_pairs_mut().append_pair( + "markup", + &format!(r#"{anchor}"#), + ); + let loaded = page + .evaluate_runtime_expression_with_await_async( + &format!( + r#" + new Promise(resolve => {{ + const child = document.createElement('iframe'); + child.style.cssText = 'display:block;width:200px;height:80px;border:0'; + child.onload = () => resolve(true); + child.src = {:?}; + document.body.style.margin = '0'; + document.body.replaceChildren(child); + }}) + "#, + child.as_str(), + ), + true, + ) + .await?; + assert_eq!(loaded["value"], true, "{case} child load"); + } else { + page.evaluate_runtime_expression_async(&format!( + "document.body.style.margin = '0'; document.body.innerHTML = {anchor:?}" + )) + .await?; + } + let before = page + .evaluate_runtime_expression_by_value_async( + r#" + sessionStorage.removeItem('link-navigation-type'); + navigation.addEventListener('navigate', event => { + sessionStorage.setItem('link-navigation-type', event.navigationType); + }); + [history.length, navigation.currentEntry.key] + "#, + ) + .await?; + let history_length = before["value"][0].as_u64().context("history.length")?; + + page.dispatch_mouse_event_at_point_async(16., 16., "mousedown", 0, Some(1), 0., 0.) + .await?; + page.dispatch_mouse_event_at_point_async(16., 16., "mouseup", 0, Some(0), 0., 0.) + .await?; + let next = frame(&mut frames, |frame| frame.document != first.document) + .await + .with_context(|| format!("{case} committed frame"))?; + assert_eq!(next.navigation.url.as_str(), current, "{case}"); + assert!(next.navigation.can_go_back, "{case}"); + let after = page + .evaluate_runtime_expression_by_value_async( + r#" + [history.length, navigation.currentEntry.key, navigation.activation.navigationType, + sessionStorage.getItem('link-navigation-type')] + "#, + ) + .await?; + let kind = if adds_entry { "push" } else { "replace" }; + assert_eq!( + after["value"][0], + history_length + u64::from(adds_entry), + "{case}" + ); + assert_eq!( + after["value"][1] != before["value"][1], + adds_entry, + "{case}" + ); + assert_eq!(after["value"][2], kind, "{case}"); + if !adds_entry || !after["value"][3].is_null() { + assert_eq!(after["value"][3], kind, "{case} navigate event"); + } + + assert!(page.traverse_viewport_history(-1).await?, "{case}"); + let back = frame(&mut frames, |frame| frame.document != next.document) + .await + .with_context(|| format!("{case} back frame"))?; + assert_eq!( + back.navigation.url.as_str(), + if adds_entry { ¤t } else { &previous }, + "{case}" + ); + } + Ok(()) +} + #[tokio::test] async fn viewport_history_keeps_the_page_before_scripted_form_submission() -> Result<()> { let server = moli_test_support::FixtureServer::spawn().await?; diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs index 01d734e8236..7e967deb8fa 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs @@ -251,7 +251,7 @@ pub(crate) fn navigate_location_object_with_source_element<'s>( raw_target, source_element, false, - false, + true, ); } @@ -416,9 +416,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( LocationNavigationKind::Assign if replaces_initial_about_blank => { LocationNavigationKind::Replace } - LocationNavigationKind::Assign if source_element.is_some() && exact_same_href => { - LocationNavigationKind::Replace - } LocationNavigationKind::Assign if source_element.is_none() && runtime_window_is_global(scope, owner) @@ -433,7 +430,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( _ => kind, }; let navigation_type = match effective_kind { - LocationNavigationKind::Assign if source_element.is_some() => "push", LocationNavigationKind::Assign => "push", LocationNavigationKind::Replace => "replace", LocationNavigationKind::Reload => "reload", @@ -594,9 +590,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( cancel_active_intercepted_same_document_navigation(scope, navigation); cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation); let navigation_type = match kind { - LocationNavigationKind::Assign if source_element.is_some() && exact_same_href => { - "replace" - } LocationNavigationKind::Assign => "push", LocationNavigationKind::Replace => "replace", LocationNavigationKind::Reload => "reload", diff --git a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs index f0fa40bdbb1..03a9feb5e65 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs @@ -6,10 +6,7 @@ pub(crate) use devtools::{ perform_auxiliary_link_default_action, perform_drop_default_action, }; -use crate::context_bootstrap::{ - LocationNavigationKind, navigate_location_object_with_source_element, - selection_value_for_window, -}; +use crate::context_bootstrap::selection_value_for_window; use crate::dom::{ forms::{ButtonTypeState, InputType}, native::{Element, Node}, @@ -1682,53 +1679,6 @@ fn anchor_click_default_action( { return None; } - if (target_name.is_none() || special_target == Some(SpecialBrowsingContextTarget::Current)) - && runtime.host_document().url().as_str() == resolved - { - let global = scope.get_current_context().global(scope); - if let Some(location) = global - .get(scope, v8str(scope, "location").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - { - let source_element = node_wrapper_from_handle(scope, handle); - navigate_location_object_with_source_element( - scope, - location, - LocationNavigationKind::Assign, - Some(resolved), - source_element, - ); - } - return None; - } - if (target_name.is_none() - || matches!( - special_target, - Some( - SpecialBrowsingContextTarget::Current - | SpecialBrowsingContextTarget::Top - | SpecialBrowsingContextTarget::Parent - ) - )) - && let Ok(url) = url::Url::parse(&resolved) - && same_document_fragment_target(runtime.host_document().url(), &url) - { - let global = scope.get_current_context().global(scope); - if let Some(location) = global - .get(scope, v8str(scope, "location").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - { - let source_element = node_wrapper_from_handle(scope, handle); - navigate_location_object_with_source_element( - scope, - location, - LocationNavigationKind::Assign, - Some(resolved), - source_element, - ); - } - return None; - } let source_element = node_wrapper_from_handle(scope, handle); if click_listener_changed_named_child_navigation( scope, diff --git a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs index f959f1bad46..3a179988c3d 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs @@ -1,8 +1,9 @@ use crate::{ RendererPendingPopupActivation, RendererPendingWindowOpenEvent, RendererPopupDisposition, context_bootstrap::{ - dispatch_cross_document_navigation_navigate_event_for_window, - dispatch_top_level_navigation_event_with_source_element, runtime_window_dispatch_scope, + LocationNavigationKind, dispatch_cross_document_navigation_navigate_event_for_window, + dispatch_top_level_navigation_event_with_source_element, + navigate_location_object_with_source_element, runtime_window_dispatch_scope, sandbox_blocks_ancestor_or_top_navigation_from_source, }, document_runtime::{DocumentPolicyContainer, DomHandle}, @@ -756,16 +757,56 @@ pub(in crate::native_bridge) fn navigate_hyperlink_target_browsing_context<'s>( { return true; } + let Ok(url) = url::Url::parse(resolved_url) else { + return false; + }; let runtime = unsafe { &*runtime_ptr }; - let can_intercept = url::Url::parse(resolved_url) - .is_ok_and(|url| moli_url::same_origin(runtime.document_url(), &url)); + let target_document = runtime.document_handle(); + let same_url_from_same_origin = &url == runtime.document_url() + && runtime + .dom_host() + .owner_document_handle(source_handle) + .is_some_and(|source_document| { + source_document == target_document + || runtime.document_security_origin(source_document) + == runtime.document_security_origin(target_document) + }); + let history = if runtime.main_document_is_initial_empty() + || url.scheme() == "javascript" + || same_url_from_same_origin + { + NavigationHistoryMutation::Replace + } else { + NavigationHistoryMutation::Push + }; + if url.fragment().is_some() && urls_refer_to_same_document(runtime.document_url(), &url) { + let Some(location) = target_window + .get(scope, v8str(scope, "location").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + else { + return false; + }; + let kind = match history { + NavigationHistoryMutation::Push => LocationNavigationKind::Assign, + NavigationHistoryMutation::Replace => LocationNavigationKind::Replace, + }; + navigate_location_object_with_source_element( + scope, + location, + kind, + Some(resolved_url.to_owned()), + source_element, + ); + return true; + } + let can_intercept = moli_url::same_origin(runtime.document_url(), &url); // Every top-target hyperlink dispatches once after resolving its owner. // Cancellation or interception must prevent the navigation from queuing. if !dispatch_top_level_navigation_event_with_source_element( scope, target_window, resolved_url, - "push", + history.navigation_type(), source_element, can_intercept, user_initiated, @@ -773,11 +814,7 @@ pub(in crate::native_bridge) fn navigate_hyperlink_target_browsing_context<'s>( ) { return true; } - return queue_top_level_location_navigation( - runtime_ptr, - resolved_url, - NavigationHistoryMutation::Push, - ); + return queue_top_level_location_navigation(runtime_ptr, resolved_url, history); } navigate_target_window_location(scope, target_window, resolved_url) } diff --git a/moli-renderer-v8/src/runtime/tests/extracted/navigation_streaming.rs b/moli-renderer-v8/src/runtime/tests/extracted/navigation_streaming.rs index c60a0a5b17f..c1d4e14ebc5 100644 --- a/moli-renderer-v8/src/runtime/tests/extracted/navigation_streaming.rs +++ b/moli-renderer-v8/src/runtime/tests/extracted/navigation_streaming.rs @@ -1312,6 +1312,59 @@ async fn same_document_navigation_publication_carries_exact_source_document() { .await .expect("same-Document navigation test page should close"); } +#[tokio::test(flavor = "current_thread")] +async fn delegated_same_url_link_publishes_its_history_mutation() { + let runtime = JsRuntime::initialize(); + let (output_tx, mut output_rx) = renderer_external_activity_test_channel(); + runtime.set_renderer_output_transport_sender(output_tx); + let loader = + ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader"); + let current = "https://example.test/source.html"; + let mut page = create_test_html_page_with_navigation_dispatch( + &runtime, + &loader, + url::Url::parse(current).unwrap(), + r#"Open"#, + RendererTopLevelNavigationDispatch::DelegateToBrowser, + ) + .await; + output_rx.drain(); + let (reply, _) = page + .run_async_command(RendererPageCommand::EvaluateExpression { + expression: r#" + let kind; + navigation.onnavigate = event => kind = event.navigationType; + document.querySelector('a').click(); + kind; + "# + .to_owned(), + await_promise: false, + }) + .await + .expect("click same-URL link"); + assert_eq!( + renderer_json_value(reply), + Some(serde_json::json!("replace")) + ); + let navigation = output_rx + .drain() + .into_iter() + .flat_map(RendererOutputPublication::into_records) + .find_map(|record| match record.into_parts().1 { + RendererOutputItem::OwnerAction(RendererOwnerAction::TopLevelLocationNavigation( + navigation, + )) => Some(navigation), + _ => None, + }) + .expect("same-URL link must be delegated"); + assert_eq!(navigation.url(), current); + assert_eq!( + navigation.history_mutation(), + moli_page_types::NavigationHistoryMutation::Replace + ); + page.close_async().await.expect("close same-URL fixture"); +} + #[tokio::test(flavor = "current_thread")] async fn document_open_preserves_document_sourced_navigation_handoffs() { let runtime = JsRuntime::initialize(); diff --git a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs index 43c8d955884..e573bbf66df 100644 --- a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs +++ b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs @@ -1,4 +1,5 @@ use super::*; +use moli_page_types::{NavigationHistoryMutation, SessionHistoryCommit}; impl ScriptVm { pub(crate) fn resync_child_browsing_contexts(&mut self) { @@ -501,12 +502,14 @@ impl ScriptVm { ) })?; let runtime_command_cause = pending.runtime_command_cause; - let history_mutation = if pending.entry_seed.as_ref().is_some_and(|seed| { - seed.session_history.commit == moli_page_types::SessionHistoryCommit::Replace - }) { - moli_page_types::NavigationHistoryMutation::Replace - } else { - moli_page_types::NavigationHistoryMutation::Push + let history_mutation = match pending.entry_seed.as_ref() { + Some(seed) if seed.session_history.commit == SessionHistoryCommit::Replace => { + NavigationHistoryMutation::Replace + } + Some(_) => NavigationHistoryMutation::Push, + None => pending + .history_mutation + .unwrap_or(NavigationHistoryMutation::Push), }; let action = crate::runtime::RendererOwnerAction::TopLevelLocationNavigation( crate::runtime::RendererDocumentSourcedTopLevelLocationNavigation:: diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation/element_navigation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation/element_navigation.rs index a645e81a5f5..095b2a40b2b 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation/element_navigation.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation/element_navigation.rs @@ -1,5 +1,48 @@ use super::*; +#[test] +fn link_navigation_replaces_the_initial_top_level_document() { + let mut vm = new_parsed_test_vm( + "about:blank", + r#"Open"#, + ); + vm._context_host + .borrow_mut() + .mark_main_document_initial_empty(); + vm.eval("document.querySelector('a').click()").unwrap(); + let pending = vm.take_pending_location_navigation_with_seed().unwrap(); + assert_eq!( + pending.history_mutation, + Some(moli_page_types::NavigationHistoryMutation::Replace) + ); +} + +#[test] +fn link_navigation_to_the_current_fragment_replaces_in_the_same_document() { + let mut vm = new_parsed_test_vm( + "https://anchor-navigation-target.test/source#current", + r##"Open"##, + ); + let result = vm + .eval( + r#" + (() => { + const original = document; + const length = history.length; + let result; + navigation.onnavigate = event => { + result = [event.navigationType, event.destination.sameDocument]; + }; + document.querySelector('a').click(); + return JSON.stringify([result, original === document, history.length === length]); + })() + "#, + ) + .unwrap(); + assert_eq!(result, r#"[["replace",true],true,true]"#); + assert!(vm.take_pending_location_navigation_with_seed().is_none()); +} + #[test] fn anchor_navigation_fires_once_when_click_is_borrowed_from_child_realm() { for target in ["", "_sElF", "_ToP", "_PARENT"] {