diff --git a/moli-benchmark/wpt-cross-current/passed-cases.txt b/moli-benchmark/wpt-cross-current/passed-cases.txt index a8a50214691..ba3ffba898c 100644 --- a/moli-benchmark/wpt-cross-current/passed-cases.txt +++ b/moli-benchmark/wpt-cross-current/passed-cases.txt @@ -8055,7 +8055,6 @@ html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document-open- html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-02.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/form-control-state.html -html/webappapis/dynamic-markup-insertion/opening-the-input-stream/ignore-opens-during-unload.window.js?moli-wpt-script=window html/webappapis/dynamic-markup-insertion/opening-the-input-stream/location-set-and-document-open.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/origin-check-in-document-open-basic.html html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-documentfragment.html diff --git a/moli-core/tests/history_visibility.rs b/moli-core/tests/history_visibility.rs new file mode 100644 index 00000000000..5f180f0a17a --- /dev/null +++ b/moli-core/tests/history_visibility.rs @@ -0,0 +1,233 @@ +use anyhow::Result; +use moli_core::runtime::{Browser, BrowserConfig}; +use moli_test_support::FixtureServer; +use serde_json::{Value, json}; +use tokio::time::Duration; +use url::Url; + +async fn history_visibility(flow: &str, api: &str, depth: usize) -> Result { + let child = r#"

child

"#; + let child = serde_json::to_string(child)?.replace("", "<\\/script>"); + let markup = r#""# + .replace("__CHILD__", &child) + .replace("__FLOW__", &serde_json::to_string(flow)?) + .replace("__API__", &serde_json::to_string(api)?) + .replace("__DEPTH__", &depth.to_string()); + let server = FixtureServer::spawn().await?; + let browser = Browser::new(BrowserConfig::default())?; + let mut url = Url::parse(&server.url("/compat/child-dynamic-markup-document"))?; + url.query_pairs_mut().append_pair("markup", &markup); + let result = tokio::time::timeout(Duration::from_secs(10), async { + let mut page = browser.fetch(url.as_str()).await?; + page.evaluate_runtime_expression_with_await_async( + "finished.then(value => JSON.stringify(value))", + true, + ) + .await + }) + .await??; + let result = serde_json::from_str(result["value"].as_str().unwrap())?; + server.shutdown().await; + Ok(result) +} + +#[tokio::test(flavor = "multi_thread")] +async fn native_window_event_targets_are_distinct_from_script_dispatch() -> Result<()> { + let result = history_visibility("synthetic", "history", 0).await?; + let native = result["native"].as_array().unwrap(); + assert_eq!(native.len(), 2, "{result}"); + for (event, kind) in native.iter().zip(["load", "pageshow"]) { + assert_eq!(event["type"], kind); + assert_eq!(event["target"], "document", "{result}"); + assert_eq!(event["currentWindow"], true); + assert_eq!(event["trusted"], true); + } + let synthetic = result["synthetic"].as_array().unwrap(); + assert_eq!(synthetic.len(), 5); + for event in synthetic { + assert_eq!(event["target"], "window", "{result}"); + assert_eq!(event["currentWindow"], true); + assert_eq!(event["trusted"], false, "{result}"); + } + assert_eq!(result["documentCalls"], 0); + assert_eq!(result["documentWindowEventCalls"], 0); + assert_eq!(result["wasTrusted"], true); + assert_eq!(result["completedBeforeRedispatch"], true); + assert_eq!(result["currentTargetCleared"], true); + assert_eq!(result["phase"], 0); + assert_eq!(result["hidden"], false); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn history_traversal_updates_visibility_and_unloads_descendants_once() -> Result<()> { + for api in ["history", "navigation"] { + for depth in [0, 2] { + let result = history_visibility("roundtrip", api, depth).await?; + assert_eq!(result["unrelatedUnchanged"], true); + for (phase, old, new, descendant_count) in + [("back", "B", "A", depth), ("forward", "A", "B", 0)] + { + let phase = &result[phase]; + assert_eq!(phase["oldHidden"], true, "{api}/{depth}: {result}"); + assert_eq!(phase["newHidden"], false); + assert_eq!(phase["sameDocument"], false); + let events = phase["events"].as_array().unwrap(); + let labels: Vec<_> = std::iter::once(old.to_owned()) + .chain((0..descendant_count).map(|n| format!("descendant-{n}"))) + .collect(); + assert!( + events + .iter() + .take(labels.len()) + .all(|e| e["type"] == "beforeunload"), + "{api}/{depth}: {result}" + ); + for label in &labels { + let actual: Vec<_> = events.iter().filter(|e| e["label"] == *label).collect(); + assert_eq!(actual.len(), 4, "{api}/{depth}: {result}"); + for (event, kind) in actual.iter().zip([ + "beforeunload", + "pagehide", + "visibilitychange", + "unload", + ]) { + assert_eq!(event["type"], kind, "{api}/{depth}: {result}"); + assert_eq!( + event["hidden"], + matches!(kind, "visibilitychange" | "unload") + ); + if kind != "beforeunload" { + assert_eq!(event["target"], "document", "{result}"); + } + assert_eq!(event["trusted"], true); + } + } + let loaded: Vec<_> = events.iter().filter(|e| e["label"] == new).collect(); + assert_eq!(loaded.len(), 2, "{api}/{depth}: {result}"); + for (event, kind) in loaded.iter().zip(["load", "pageshow"]) { + assert_eq!(event["type"], kind); + assert_eq!(event["target"], "document"); + assert_eq!(event["hidden"], false); + } + assert_eq!(events.len(), labels.len() * 4 + 2); + } + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn same_document_traversal_keeps_visibility_and_skips_unload() -> Result<()> { + for api in ["history", "navigation"] { + let result = history_visibility("same-document", api, 0).await?; + assert_eq!(result["events"], json!([]), "{api}: {result}"); + assert_eq!(result["sameDocument"], true); + assert_eq!(result["hidden"], false); + } + Ok(()) +} diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs index 6d7b9f9d260..267e41f4f76 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs @@ -674,11 +674,12 @@ fn dispatch_unload_lifecycle_event_for_runtime_owner<'s>( } else if let Some(child_handle) = child_browsing_context_handle_for_runtime_owner(scope, owner) && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) { - unsafe { &mut *host_ptr }.dispatch_child_window_event( + unsafe { &mut *host_ptr }.dispatch_child_window_event_with_target_override( scope, child_handle, event_type, event, + matches!(event_type, "pagehide" | "unload"), ); } set_navigation_unload_event_active(scope, owner, false); diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs index ae606a7aa08..89f5d8f6340 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs @@ -4,8 +4,7 @@ use super::history_runtime::{apply, results, traversal}; use super::navigation_entry::{history_entries, history_index, navigation_current_entry}; use super::navigation_events::{ NavigationDispatchOutcome, dispatch_beforeunload_for_runtime_owner, - dispatch_navigation_traverse_event_with_outcome, dispatch_pagehide_for_runtime_owner, - dispatch_unload_for_runtime_owner, + dispatch_navigation_traverse_event_with_outcome, }; use super::navigation_result::navigation_dom_exception; use super::navigation_seed::history_entry_seed_for_traversal; @@ -461,12 +460,8 @@ fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalA } } for participant in &cross_document { - dispatch_pagehide_for_runtime_owner(scope, participant.owner); - if validate(scope, admission).is_none() { - abort(scope, admission, None); - return; - } - dispatch_unload_for_runtime_owner(scope, participant.owner); + unsafe { &mut *host_ptr } + .dispatch_child_document_unload_after_traversal_check(scope, participant.handle); if validate(scope, admission).is_none() { abort(scope, admission, None); return; @@ -490,9 +485,6 @@ fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalA } for participant in &cross_document { let host = unsafe { &mut *host_ptr }; - let _ = host.mark_current_child_document_unload_dispatched_after_navigation_traversal( - participant.handle, - ); if !host.queue_deferred_child_browsing_context_navigation_from_entry_seed( scope, participant.handle, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs index 40a5a9ecf87..3ca96b2d495 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs @@ -874,18 +874,14 @@ impl PageScriptHost { } } - pub(crate) fn mark_current_child_document_unload_dispatched_after_navigation_traversal( + pub(crate) fn dispatch_child_document_unload_after_traversal_check( &mut self, + scope: &mut v8::PinScope<'_, '_>, handle: DomHandle, ) -> bool { - let Some(action) = self - .frame_owner_store - .begin_current_child_document_unload(handle) - else { - return false; - }; - self.frame_owner_store - .finish_current_child_document_unload(action) + // Traversal has already fired the root beforeunload before navigate. + // Descendants still need their checks before any document unloads. + self.dispatch_child_document_tree_unload_lifecycle(scope, handle, false) } pub(in crate::native_bridge::context_host) fn dispatch_child_browsing_context_unload_lifecycle_if_needed( @@ -893,6 +889,16 @@ impl PageScriptHost { scope: &mut v8::PinScope<'_, '_>, handle: DomHandle, ) -> bool { + self.dispatch_child_document_tree_unload_lifecycle(scope, handle, true) + } + + fn dispatch_child_document_tree_unload_lifecycle( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + handle: DomHandle, + include_root_beforeunload: bool, + ) -> bool { + let root_handle = handle; let documents = self.child_document_unload_tree_snapshot(handle); let mut unload_guards = Vec::new(); let mut actions = Vec::new(); @@ -926,7 +932,9 @@ impl PageScriptHost { }; unload_guards.push((document, self.enter_document_unload(document))); actions.push((document, parent_document, action)); - dispatch_beforeunload_for_runtime_owner(scope, window); + if include_root_beforeunload || handle != root_handle { + dispatch_beforeunload_for_runtime_owner(scope, window); + } } unload_guards.clear(); let dispatched = !actions.is_empty(); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_events.rs b/moli-renderer-v8/src/native_bridge/context_host/child_events.rs index 185df73f66a..829008bf81a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_events.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_events.rs @@ -552,6 +552,19 @@ impl PageScriptHost { handle: DomHandle, event_type: &str, event: v8::Local<'s, v8::Object>, + ) { + self.dispatch_child_window_event_with_target_override( + scope, handle, event_type, event, false, + ); + } + + pub(crate) fn dispatch_child_window_event_with_target_override<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + handle: DomHandle, + event_type: &str, + event: v8::Local<'s, v8::Object>, + legacy_target_override: bool, ) { if !self.child_window_event_requires_runtime_dispatch(handle, event_type) { return; @@ -564,7 +577,9 @@ impl PageScriptHost { }; let previous_active_child_window = enter_child_window_event_dispatch(scope, handle); self.push_child_subresource_request_scope(handle); - let target = if event_type == "unload" { + // The legacy flag changes event.target, while dispatch still takes + // place at Window. Script dispatch never sets this flag. + let target = if legacy_target_override { self.child_browsing_context_document_wrapper(scope, handle) .map(Into::into) .unwrap_or_else(|| window.into()) @@ -601,14 +616,6 @@ impl PageScriptHost { let Some(ready) = self .prepare_child_window_event_listener_invocation(scope, handle, event_type, slot) else { - if let Some(callback_id) = self.remove_child_window_event_registration_by_id( - handle, - event_type, - slot.registration_id, - ) { - self.unregister_abort_target_listener(callback_id); - self.release_event_callback(callback_id); - } continue; }; if ready.once diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_loads.rs b/moli-renderer-v8/src/native_bridge/context_host/host_loads.rs index bf0db679b0b..db432aaf13a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/host_loads.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/host_loads.rs @@ -403,7 +403,7 @@ impl PageScriptHost { action.owner(), DocumentLifecycleTiming::LoadStart, ); - self.dispatch_child_window_event(scope, handle, "load", event); + self.dispatch_child_window_event_with_target_override(scope, handle, "load", event, true); self.record_child_document_lifecycle_timing( scope, handle, @@ -460,7 +460,13 @@ impl PageScriptHost { let callback_dispatched = if let Some(event) = construct_original_page_transition_event(scope, "pageshow", false) { - self.dispatch_child_window_event(scope, action.child_handle(), "pageshow", event); + self.dispatch_child_window_event_with_target_override( + scope, + action.child_handle(), + "pageshow", + event, + true, + ); true } else { false diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rs index 9e399f8804f..e4d08b7dee3 100644 --- a/moli-renderer-v8/src/window_host.rs +++ b/moli-renderer-v8/src/window_host.rs @@ -11,6 +11,7 @@ use super::{ context_bootstrap::mark_event_trusted, context_bootstrap::performance_slot_number, context_bootstrap::resolve_event_target, + context_bootstrap::set_event_trusted, context_bootstrap::trusted_script_string_or_type_error, document_runtime::{DocumentContentSecurityPolicyViolation, DomHandle, EventTargetHandle}, native_bridge::{ @@ -45,7 +46,7 @@ use super::{ use crate::event_listener_args::{ AddEventListenerArgs, RemoveEventListenerArgs, parse_listener_args, }; -use crate::native_bridge::OwnerDispatchScope; + use crate::web_api_interfaces; pub(crate) use moli_webapi::idle_deadline::install_idle_deadline_template_bindings; use moli_webapi_declare::WebApiObject; @@ -429,6 +430,7 @@ pub(super) fn event_target_dispatch_event_callback<'s>( return; } + set_event_trusted(scope, event, false); let event_type = event_type_string(scope, event); if let Some(handle) = child_window_target { let event_type = event_type.as_deref().unwrap_or_default();