diff --git a/moli-core/tests/history_form.rs b/moli-core/tests/history_form.rs new file mode 100644 index 00000000000..1d713b6f384 --- /dev/null +++ b/moli-core/tests/history_form.rs @@ -0,0 +1,210 @@ +use anyhow::Result; +use moli_core::runtime::{Browser, BrowserConfig}; +use moli_test_support::FixtureServer; +use tokio::time::Duration; +use url::Url; + +fn markup_url(server: &FixtureServer, markup: &str) -> String { + let mut url = Url::parse(&server.url("/compat/child-dynamic-markup-document")).unwrap(); + url.query_pairs_mut().append_pair("markup", markup); + url.into() +} + +async fn child_form_history(phase: &str, method: &str, target: &str) -> Result<()> { + let server = FixtureServer::spawn().await?; + let browser = Browser::new(BrowserConfig::default())?; + let source = format!( + r#""#, + serde_json::to_string(method)?, + serde_json::to_string(target)?, + serde_json::to_string(phase)? + ); + let parent = format!( + r#""#, + serde_json::to_string(&markup_url(&server, &source))?.replace("", "<\\/script>") + ); + let result = tokio::time::timeout(Duration::from_secs(10), async { + let mut page = browser.fetch(&markup_url(&server, &parent)).await?; + page.evaluate_runtime_expression_with_await_async( + "finished.then(value => JSON.stringify(value))", + true, + ) + .await + }) + .await??; + let result: serde_json::Value = serde_json::from_str(result["value"].as_str().unwrap())?; + let replaces = !matches!(phase, "after-load" | "reopen" | "foreign"); + let delta = if replaces { 0 } else { 1 }; + assert_eq!( + result["delta"], delta, + "{phase}/{method}/{target}: {result}" + ); + assert_eq!( + result["index"], delta, + "{phase}/{method}/{target}: {result}" + ); + assert_eq!( + result["navigationType"], + if replaces { "replace" } else { "push" } + ); + assert_eq!(result["oldDocumentUnchanged"], true); + assert_eq!(result["response"]["method"], method.to_uppercase()); + assert_eq!( + result["formDataValue"], + if method == "post" { + serde_json::json!("submitted") + } else { + serde_json::Value::Null + } + ); + assert_eq!( + result["readiness"], + match phase { + "parser" | "reopen" | "foreign" => "loading", + "DOMContentLoaded" => "interactive", + _ => "complete", + } + ); + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn self_form_navigation_replaces_until_load_callbacks_finish() -> Result<()> { + for method in ["get", "post"] { + for phase in ["parser", "DOMContentLoaded", "load", "pageshow"] { + child_form_history(phase, method, "_self").await?; + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn named_self_form_navigation_uses_the_target_document_load_state() -> Result<()> { + for method in ["get", "post"] { + for phase in ["parser", "pageshow", "after-load"] { + child_form_history(phase, method, "form-frame").await?; + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn self_form_navigation_pushes_after_load_even_after_document_open() -> Result<()> { + for method in ["get", "post"] { + for phase in ["after-load", "reopen"] { + child_form_history(phase, method, "_self").await?; + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn form_navigation_auto_replaces_the_same_url_after_load() -> Result<()> { + for method in ["get", "post"] { + for target in ["_self", "form-frame"] { + child_form_history("same-url", method, target).await?; + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn form_navigation_from_another_document_pushes_even_while_target_loads() -> Result<()> { + for method in ["get", "post"] { + child_form_history("foreign", method, "form-frame").await?; + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn main_form_navigation_events_use_submission_time_load_state() -> Result<()> { + let server = FixtureServer::spawn().await?; + for method in ["get", "post"] { + for phase in ["parser", "load", "pageshow", "after-load"] { + let browser = Browser::new(BrowserConfig::default())?; + let markup = format!( + r#"
+
"#, + method, + serde_json::to_string(phase)? + ); + let result = tokio::time::timeout(Duration::from_secs(10), async { + let mut page = browser.fetch(&markup_url(&server, &markup)).await?; + page.evaluate_runtime_expression_with_await_async( + "finished.then(value => JSON.stringify(value))", + true, + ) + .await + }) + .await??; + let result: serde_json::Value = + serde_json::from_str(result["value"].as_str().unwrap())?; + assert_eq!( + result, + serde_json::json!({ + "type": if phase == "after-load" { "push" } else { "replace" }, + "data": if method == "post" { Some("submitted") } else { None }, + }), + "{phase}/{method}" + ); + } + } + server.shutdown().await; + Ok(()) +} diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index e7f60a97bab..f9de8d0a48f 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -72,6 +72,7 @@ pub(crate) use indexed_db::{ serialize_indexed_db_value_for_test, sql_transaction_handle_for_test, sql_transaction_started_for_test, }; +mod form_navigation; mod location_history_storage; mod location_navigation; mod location_runtime; @@ -191,6 +192,7 @@ pub(crate) use crypto::{ pub(crate) use css_fontface_runtime::{ new_font_face_set, rebuild_font_face_set_faces, settle_document_font_face_set_ready, }; +pub(crate) use form_navigation::FormNavigationHistory; pub(crate) use location_navigation::{ LocationNavigationKind, dispatch_top_level_form_navigation_event, dispatch_top_level_navigation_event_with_source_element, is_native_location, diff --git a/moli-renderer-v8/src/context_bootstrap/form_navigation.rs b/moli-renderer-v8/src/context_bootstrap/form_navigation.rs new file mode 100644 index 00000000000..2a5db128c85 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/form_navigation.rs @@ -0,0 +1,49 @@ +use super::navigation_entry::{history_index, navigation_current_entry_index}; +use super::navigation_serialize::serialize_history_entries; +use super::navigation_window::window_history_for_holder; +use crate::document_runtime::DomHandle; +use crate::native_bridge::PageScriptHost; +use moli_page_types::{ + NavigationHistoryEntrySeed, NavigationHistoryMutation, cross_document_navigation_seed, +}; +use url::Url; + +pub(crate) struct FormNavigationHistory { + pub(crate) mutation: NavigationHistoryMutation, + pub(crate) entry_seed: Option, +} + +impl FormNavigationHistory { + pub(crate) fn capture( + scope: &mut v8::PinScope<'_, '_>, + host: &mut PageScriptHost, + source_document: Option, + target_child: Option, + destination: &Url, + requested_mutation: Option, + ) -> Self { + let mutation = requested_mutation.unwrap_or_else(|| { + host.form_navigation_history_mutation(source_document, target_child, destination) + }); + let owner = match target_child { + Some(handle) => host.existing_child_browsing_context_window_wrapper(scope, handle), + None => Some(scope.get_current_context().global(scope)), + }; + let entry_seed = owner.and_then(|owner| { + let history = window_history_for_holder(scope, owner)?; + let index = history_index(scope, history); + let navigation_index = navigation_current_entry_index(scope, owner).unwrap_or(0); + Some(cross_document_navigation_seed( + serialize_history_entries(scope, history), + index, + navigation_index, + destination, + mutation, + )) + }); + Self { + mutation, + entry_seed, + } + } +} diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs index 4b7b1b3afd6..c3bf17f3351 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs @@ -421,7 +421,7 @@ fn effective_history_mutation_kind<'s>( }; let host = unsafe { &*host_ptr }; let is_initial_empty = child_browsing_context_handle_for_runtime_owner(scope, owner) - .is_some_and(|handle| host.child_browsing_context_is_on_initial_about_blank_entry(handle)) + .is_some_and(|handle| host.child_current_document_is_initial_empty(handle)) || crate::native_bridge::lightweight_popup_id_from_window(scope, owner).is_some_and( |popup_id| host.lightweight_popup_current_document_is_initial_empty(popup_id), ); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs index b3847e0e640..4aaa3e199e3 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs @@ -3,9 +3,80 @@ use super::super::{ NavigationHistoryEntrySeed, PageScriptHost, }; use crate::document_runtime::DomHandle; +use moli_page_types::{NavigationHistoryMutation, cross_document_navigation_seed}; use url::Url; impl PageScriptHost { + pub(crate) fn queue_deferred_child_form_navigation_request( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + handle: DomHandle, + request: ChildBrowsingContextNavigationRequest, + entry_seed: Option, + mutation: NavigationHistoryMutation, + ) -> bool { + let Some(entry) = self.child_browsing_contexts.get(&handle) else { + return false; + }; + if request.url.scheme() == "javascript" { + return self.queue_child_browsing_context_navigation_without_seed_update( + scope, + handle, + request.url.as_str(), + None, + ); + } + let entry_seed = entry_seed.unwrap_or_else(|| { + // A named target need not have a Window wrapper yet. Use its + // committed history, never a previously planned form navigation. + let committed = entry.committed_navigation_entry_seed(); + let index = committed + .entries + .iter() + .find(|entry| entry.history_index == committed.current_index) + .map_or(0, |entry| entry.index); + cross_document_navigation_seed( + committed.entries, + committed.current_index, + index, + &request.url, + mutation, + ) + }); + if request.method == "GET" { + return self.queue_deferred_child_browsing_context_navigation_from_entry_seed( + scope, + handle, + request.url.as_str(), + entry_seed, + None, + ); + } + self.reject_replaced_service_worker_child_client_navigation( + handle, + "The navigation was canceled.".to_owned(), + ); + if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { + entry.replace_navigation_entry_seed(entry_seed); + } + let url = request.url.clone(); + if self + .set_child_browsing_context_pending_navigation( + handle, + ChildBrowsingContextBootstrap::Request(request), + None, + false, + ) + .is_none() + { + return false; + } + let download_policy = self.capture_child_navigation_download_policy(scope, handle); + self.register_reserved_service_worker_child_client_for_navigation(handle, &url); + let queued = self.queue_child_browsing_context_navigation_commit(handle); + self.remember_child_navigation_download_policy(handle, download_policy, queued) + } + pub(crate) fn navigate_child_browsing_context_to_url( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -159,69 +230,6 @@ impl PageScriptHost { } } - pub(crate) fn queue_deferred_child_browsing_context_navigation_to_url( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - resolved_url: &str, - ) -> bool { - let download_policy = self.capture_child_navigation_download_policy(scope, handle); - if !self.child_browsing_contexts.contains_key(&handle) { - return false; - } - let Some(url) = Url::parse(resolved_url).ok() else { - return false; - }; - if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.apply_deferred_navigation_to_entry_seed(&url); - } - if self - .set_child_browsing_context_pending_navigation( - handle, - ChildBrowsingContextBootstrap::Url(url), - None, - false, - ) - .is_none() - { - return false; - } - let queued = self.queue_child_browsing_context_navigation_commit(handle); - self.remember_child_navigation_download_policy(handle, download_policy, queued) - } - - pub(crate) fn queue_deferred_child_browsing_context_navigation_request( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - request: ChildBrowsingContextNavigationRequest, - ) -> bool { - let download_policy = self.capture_child_navigation_download_policy(scope, handle); - if !self.child_browsing_contexts.contains_key(&handle) { - return false; - } - self.reject_replaced_service_worker_child_client_navigation( - handle, - "The navigation was canceled.".to_owned(), - ); - if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { - entry.apply_deferred_navigation_to_entry_seed(&request.url); - } - if self - .set_child_browsing_context_pending_navigation( - handle, - ChildBrowsingContextBootstrap::Request(request), - None, - false, - ) - .is_none() - { - return false; - } - let queued = self.queue_child_browsing_context_navigation_commit(handle); - self.remember_child_navigation_download_policy(handle, download_policy, queued) - } - pub(crate) fn child_browsing_context_has_pending_cross_document_traversal( &self, handle: DomHandle, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index 85943307da9..dda2a400061 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -775,10 +775,6 @@ impl ChildBrowsingContextEntry { } } - pub(super) fn apply_deferred_navigation_to_entry_seed(&mut self, url: &Url) { - self.apply_navigation_to_entry_seed(url); - } - pub(super) fn clear_navigation_activation(&mut self) { self.navigation_entry_seed.activation = None; } diff --git a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs index 180586719ba..954005510fa 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs @@ -1,4 +1,5 @@ -use super::PageScriptHost; +use super::{OwnerDispatchScope, PageScriptHost}; +use crate::document_runtime::DomHandle; use crate::page_task_queue::RendererTopLevelNavigationHandoff; use crate::runtime::{ RendererBrowserContextRuntime, RendererDocumentLifecycleIdentity, @@ -7,7 +8,9 @@ use crate::runtime::{ }; use crate::service_worker_runtime::{ServiceWorkerClientId, ServiceWorkerClientNavigateError}; use moli_fetch::BrowserNavigationRequestKind; -use moli_page_types::NavigationHistoryEntrySeed; +use moli_page_types::{ + NavigationHistoryEntrySeed, NavigationHistoryMutation, SameDocumentHistoryUpdate, +}; use url::Url; pub(crate) struct PendingReservedServiceWorkerClient { @@ -115,6 +118,46 @@ impl PageScriptHost { ); } + pub(crate) fn form_navigation_history_mutation( + &self, + source_document: Option, + target_child: Option, + destination: &Url, + ) -> NavigationHistoryMutation { + let target_scope = target_child.map_or(OwnerDispatchScope::Top, OwnerDispatchScope::Child); + let target_document = match target_child { + Some(handle) => self + .frame_owner_current_child_snapshot(handle) + .map(|s| s.document_handle), + None => Some(self.document_handle()), + }; + // Form submission fixes history handling before planning the navigation. + // Unlike Location assignment, transient activation does not change this rule. + let replaces_loading_self = source_document.is_some() + && source_document == target_document + && source_document.and_then(|document| self.document_is_completely_loaded(document)) + == Some(false); + let replaces_initial = + target_child.is_some_and(|handle| self.child_current_document_is_initial_empty(handle)); + let same_origin = source_document + .and_then(|document| self.owner_dispatch_scope_for_node(document)) + .and_then(|source| self.window_access_origin_for_dispatch_scope(source)) + .zip(self.window_access_origin_for_dispatch_scope(target_scope)) + .is_some_and(|(source, target)| source.has_same_origin(&target)); + let replaces_same_url = same_origin + && target_document + .is_some_and(|document| self.document_url_for_handle(document) == *destination); + if replaces_loading_self + || replaces_initial + || replaces_same_url + || destination.scheme() == "javascript" + { + NavigationHistoryMutation::Replace + } else { + NavigationHistoryMutation::Push + } + } + pub(crate) fn document_is_completely_loaded( &self, document_handle: crate::document_runtime::DomHandle, 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 7029fb18bb3..edf85993a2d 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 @@ -24,7 +24,9 @@ use crate::{ RendererPendingFileChooserActivation, RendererPopupDisposition, document_runtime::{DomHandle, EventTargetHandle}, frame_owner_model::DocumentId, - native_bridge::context_host::ChildBrowsingContextBootstrap, + native_bridge::context_host::{ + ChildBrowsingContextBootstrap, ChildBrowsingContextNavigationRequest, + }, native_bridge::{CurrentInputEvent, InputNavigationPolicy, navigation_policy_from_event}, runtime::RendererDocumentLifecycleIdentity, }; @@ -2073,14 +2075,16 @@ pub(in crate::native_bridge) fn navigate_form_target_browsing_context( && !has_noopener && (has_opener || special_target != Some(SpecialBrowsingContextTarget::Blank)) }; - let target_document = { - let runtime = unsafe { &*runtime_ptr }; - runtime - .dom_host() - .owner_document_handle(form_handle) - .and_then(|source| form_navigation_target_document(runtime, source, target_name)) - }; + let source_document = unsafe { &*runtime_ptr } + .dom_host() + .owner_document_handle(form_handle); + let target_document = source_document.and_then(|source| { + form_navigation_target_document(unsafe { &*runtime_ptr }, source, target_name) + }); if let Some(document_handle) = target_document { + let Ok(url) = url::Url::parse(resolved_url) else { + return false; + }; let runtime = unsafe { &*runtime_ptr }; if document_handle != runtime.document_handle() { let Some(child_handle) = @@ -2089,8 +2093,34 @@ pub(in crate::native_bridge) fn navigate_form_target_browsing_context( return false; }; let runtime = unsafe { &mut *runtime_ptr }; - let navigated = - runtime.navigate_child_browsing_context_to_url(scope, child_handle, resolved_url); + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + runtime, + source_document, + Some(child_handle), + &url, + None, + ); + let source_element = node_wrapper_from_handle(scope, form_handle); + if let Some(window) = runtime.existing_child_browsing_context_window_wrapper(scope, child_handle) + && !crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data( + scope, window, resolved_url, history.mutation.navigation_type(), + source_element, false, None, None, + ) { + return true; + } + let navigated = runtime.queue_deferred_child_form_navigation_request( + scope, + child_handle, + ChildBrowsingContextNavigationRequest { + url, + method: "GET".to_owned(), + body: None, + request_headers: Vec::new(), + }, + history.entry_seed, + history.mutation, + ); if navigated { crate::context_bootstrap::web_mcp::bind_child_navigation( runtime, @@ -2107,12 +2137,20 @@ pub(in crate::native_bridge) fn navigate_form_target_browsing_context( ) else { return false; }; + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + unsafe { &mut *runtime_ptr }, + source_document, + None, + &url, + None, + ); let source_element = node_wrapper_from_handle(scope, form_handle); if !crate::context_bootstrap::dispatch_top_level_navigation_event_with_source_element( scope, window, resolved_url, - "replace", + history.mutation.navigation_type(), source_element, true, false, @@ -2120,10 +2158,7 @@ pub(in crate::native_bridge) fn navigate_form_target_browsing_context( ) { return true; } - let Ok(url) = url::Url::parse(resolved_url) else { - return false; - }; - unsafe { &mut *runtime_ptr }.record_pending_location_navigation(url, None); + unsafe { &mut *runtime_ptr }.record_pending_location_navigation(url, history.entry_seed); crate::context_bootstrap::web_mcp::bind_root_navigation( unsafe { &mut *runtime_ptr }, form_handle, 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 41ac06d649b..efe70508ef3 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs @@ -832,6 +832,15 @@ pub(in crate::native_bridge) fn queue_deferred_named_iframe_target_navigation_fr source_document, )?; let runtime = unsafe { &mut *runtime_ptr }; + let destination = url::Url::parse(resolved_url).ok()?; + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + runtime, + source_document, + Some(target_iframe), + &destination, + None, + ); let target_url = url::Url::parse(resolved_url).ok(); let target_is_same_origin_with_top = target_url .as_ref() @@ -846,22 +855,31 @@ pub(in crate::native_bridge) fn queue_deferred_named_iframe_target_navigation_fr || target_is_same_document_with_child) && let Some(window) = runtime.existing_child_browsing_context_window_wrapper(scope, target_iframe) - && !dispatch_cross_document_navigation_navigate_event_for_window( + && !crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data( scope, window, resolved_url, + history.mutation.navigation_type(), source_element, false, None, + None, ) { return Some(target_iframe); } - let queued = runtime.queue_deferred_child_browsing_context_navigation_to_url( - scope, - target_iframe, - resolved_url, - ); + let queued = runtime.queue_deferred_child_form_navigation_request( + scope, + target_iframe, + ChildBrowsingContextNavigationRequest { + url: destination, + method: "GET".to_owned(), + body: None, + request_headers: Vec::new(), + }, + history.entry_seed, + history.mutation, + ); if queued && let Some(document) = source_document { runtime.set_pending_child_navigation_download_source(target_iframe, document); } @@ -879,22 +897,19 @@ fn urls_refer_to_same_document(current: &url::Url, target: &url::Url) -> bool { pub(in crate::native_bridge) fn queue_deferred_named_iframe_target_request( scope: &mut v8::PinScope<'_, '_>, runtime_ptr: *mut PageScriptHost, - target_name: &str, + target_iframe: DomHandle, source_document: Option, request: ChildBrowsingContextNavigationRequest, + history: crate::context_bootstrap::FormNavigationHistory, ) -> Option { - let target_iframe = named_iframe_target_handle_for_navigation( - scope, - runtime_ptr, - target_name, - source_document, - )?; let runtime = unsafe { &mut *runtime_ptr }; - let queued = runtime.queue_deferred_child_browsing_context_navigation_request( - scope, - target_iframe, - request, - ); + let queued = runtime.queue_deferred_child_form_navigation_request( + scope, + target_iframe, + request, + history.entry_seed, + history.mutation, + ); if queued && let Some(document) = source_document { runtime.set_pending_child_navigation_download_source(target_iframe, document); } diff --git a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs index 25ae5c14293..d06712daa28 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs @@ -709,22 +709,33 @@ pub(in crate::native_bridge) fn submit_form_default_action( content_type, form_data_entries, } => { + let Some(target_handle) = target_handle else { + return false; + }; + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + unsafe { &mut *runtime_ptr }, + source_document, + Some(target_handle), + &resolved_url, + None, + ); if !dispatch_named_iframe_form_navigation_event( scope, runtime_ptr, - target_name, + target_handle, form_handle, submitter, - source_document, resolved_url.as_str(), &form_data_entries, + history.mutation.navigation_type(), ) { return true; } let navigated = queue_deferred_named_iframe_target_request( scope, runtime_ptr, - target_name, + target_handle, source_document, ChildBrowsingContextNavigationRequest { initiator, @@ -736,6 +747,7 @@ pub(in crate::native_bridge) fn submit_form_default_action( content_type.to_owned(), )], }, + history, ); if let Some(target_handle) = navigated { unsafe { &mut *runtime_ptr }.mark_pending_form_submission_child_navigation( @@ -973,28 +985,14 @@ fn submit_form_to_popup_browsing_context( fn dispatch_named_iframe_form_navigation_event( scope: &mut v8::PinScope<'_, '_>, runtime_ptr: *mut PageScriptHost, - target_name: &str, + target_iframe: DomHandle, form_handle: DomHandle, submitter: Option, - source_document: Option, resolved_url: &str, form_data_entries: &[(String, v8::Global)], + navigation_type: &str, ) -> bool { let runtime = unsafe { &mut *runtime_ptr }; - let target_iframe = source_document - .and_then(|document| { - runtime.child_browsing_context_handle_by_name_for_navigation_from_document( - scope, - target_name, - document, - ) - }) - .or_else(|| { - runtime.child_browsing_context_handle_by_name_for_navigation(scope, target_name) - }); - let Some(target_iframe) = target_iframe else { - return true; - }; let Some(window) = runtime.existing_child_browsing_context_window_wrapper(scope, target_iframe) else { return true; @@ -1006,10 +1004,11 @@ fn dispatch_named_iframe_form_navigation_event( }; let source_handle = submitter.unwrap_or(form_handle); let source_element = wrap_handle_object(scope, runtime_ptr, source_handle); - crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_form_data( + crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data( scope, window, resolved_url, + navigation_type, source_element, false, None, @@ -1043,12 +1042,23 @@ fn submit_post_form_to_top_level_browsing_context( }; let source_handle = submitter.unwrap_or(form_handle); let source_element = wrap_handle_object(scope, runtime_ptr, source_handle); - let navigation_type = if user_initiated { "push" } else { "replace" }; + let runtime = unsafe { &mut *runtime_ptr }; + let source_document = runtime.dom_host().owner_document_handle(form_handle); + // Keep an input-initiated POST on its existing explicit push path. + // Ambient activation does not turn form.submit() into an input submission. + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + runtime, + source_document, + None, + &resolved_url, + user_initiated.then_some(moli_page_types::NavigationHistoryMutation::Push), + ); if !crate::context_bootstrap::dispatch_top_level_form_navigation_event( scope, window, resolved_url.as_str(), - navigation_type, + history.mutation.navigation_type(), source_element, user_initiated, form_data, @@ -1060,7 +1070,7 @@ fn submit_post_form_to_top_level_browsing_context( "POST".to_owned(), Some(body), vec![("Content-Type".to_owned(), content_type)], - None, + history.entry_seed, moli_fetch::BrowserNavigationRequestKind::Navigate, ); unsafe { &mut *runtime_ptr }.set_pending_location_navigation_source(initiator, None); @@ -1093,6 +1103,14 @@ fn submit_post_form_to_child_browsing_context( }) else { return false; }; + let history = crate::context_bootstrap::FormNavigationHistory::capture( + scope, + unsafe { &mut *runtime_ptr }, + Some(source_document), + Some(child_handle), + &resolved_url, + None, + ); if let Some(window) = unsafe { &mut *runtime_ptr } .existing_child_browsing_context_window_wrapper(scope, child_handle) { @@ -1103,10 +1121,11 @@ fn submit_post_form_to_child_browsing_context( }; let source_handle = submitter.unwrap_or(form_handle); let source_element = wrap_handle_object(scope, runtime_ptr, source_handle); - if !crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_form_data( + if !crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data( scope, window, resolved_url.as_str(), + history.mutation.navigation_type(), source_element, false, None, @@ -1116,7 +1135,7 @@ fn submit_post_form_to_child_browsing_context( } } let runtime = unsafe { &mut *runtime_ptr }; - let navigated = runtime.navigate_child_browsing_context_with_request( + let navigated = runtime.queue_deferred_child_form_navigation_request( scope, child_handle, ChildBrowsingContextNavigationRequest { @@ -1126,6 +1145,8 @@ fn submit_post_form_to_child_browsing_context( body: Some(body), request_headers: vec![("Content-Type".to_owned(), content_type)], }, + history.entry_seed, + history.mutation, ); if navigated { crate::context_bootstrap::web_mcp::bind_child_navigation( diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs index 21190724c55..9617a4d0b0b 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs @@ -5158,45 +5158,74 @@ root.appendChild(label); #[test] fn submit_button_click_queues_pending_top_level_location_navigation() { - let mut vm = new_storage_test_vm("https://form-submit-navigation.test/path/index.html"); + for target in ["", "_self", "_SeLf"] { + for activated in [false, true] { + let mut vm = new_storage_test_vm("https://form-submit-navigation.test/path/index.html"); - vm.eval( - r#" -(() => { - if (!document.documentElement) { - document.appendChild(document.createElement('html')); - } - if (!document.body) { - document.documentElement.appendChild(document.createElement('body')); - } - const form = document.createElement('form'); - form.action = '/submit?from=form'; - const input = document.createElement('input'); - input.type = 'hidden'; - input.name = 'from'; - input.value = 'form'; - const button = document.createElement('button'); - button.type = 'submit'; - form.appendChild(input); - form.appendChild(button); - document.body.appendChild(form); - button.click(); -})() -"#, - ) - .expect("submit button click should execute"); + vm.eval(&format!("globalThis.targetKeyword = {target:?}")) + .expect("target keyword should be set"); + if activated { + vm._context_host + .borrow_mut() + .begin_protocol_user_gesture_activation(); + } + vm.eval( + r#" + (() => { + if (!document.documentElement) { + document.appendChild(document.createElement('html')); + } + if (!document.body) { + document.documentElement.appendChild(document.createElement('body')); + } + const form = document.createElement('form'); + form.action = '/submit?from=form'; + form.target = globalThis.targetKeyword; + const input = document.createElement('input'); + input.type = 'hidden'; + input.name = 'from'; + input.value = 'form'; + const button = document.createElement('button'); + button.type = 'submit'; + form.appendChild(input); + form.appendChild(button); + document.body.appendChild(form); + button.click(); + })() + "#, + ) + .expect("submit button click should execute"); - let pending = vm - .take_pending_location_navigation_with_seed() - .expect("submit button click should queue a pending location navigation"); - assert_eq!( - pending.url.as_str(), - "https://form-submit-navigation.test/submit?from=form" - ); - assert!( - pending.entry_seed.is_none(), - "default form submission should not synthesize a history seed" - ); + if activated { + vm._context_host + .borrow_mut() + .end_protocol_user_gesture_activation(); + } + let pending = vm + .take_pending_location_navigation_with_seed() + .expect("submit button click should queue a pending location navigation"); + assert_eq!( + pending.url.as_str(), + "https://form-submit-navigation.test/submit?from=form" + ); + let seed = pending + .entry_seed + .expect("script submission should retain its history decision"); + let activation = seed + .activation + .as_ref() + .expect("form navigation activation"); + let from = activation.from.as_ref().expect("previous document entry"); + assert_eq!(activation.navigation_type.as_deref(), Some("replace")); + assert_eq!(seed.current_index, from.history_index); + assert_eq!(activation.entry.url, pending.url.as_str()); + assert_eq!( + from.url, + "https://form-submit-navigation.test/path/index.html" + ); + assert!(!seed.entries.iter().any(|entry| entry.url == from.url)); + } + } } #[cfg(feature = "devtools")] @@ -6026,7 +6055,7 @@ fn get_form_submit_dispatches_cancelable_navigate_event_with_source_element() { } #[test] fn form_top_and_parent_targets_queue_plain_top_level_navigation() { - for target in ["_top", "_parent", "_ToP", "_PaReNt", "_SeLf"] { + for target in ["_top", "_parent", "_ToP", "_PaReNt"] { let mut vm = new_storage_test_vm("https://form-target-navigation.test/path/index.html"); vm.eval(&format!(