diff --git a/moli-core/tests/scripts/navigation_resource_timing.rs b/moli-core/tests/scripts/navigation_resource_timing.rs index b80e620d180..64c6b7c5cea 100644 --- a/moli-core/tests/scripts/navigation_resource_timing.rs +++ b/moli-core/tests/scripts/navigation_resource_timing.rs @@ -110,6 +110,21 @@ impl NavigationTimingServer { "/queued-service-worker" => ("text/html", queued_navigation_source(true)), "/beforeunload" => ("text/html", beforeunload_navigation_source()), "/with-nested" => ("text/html", "".to_owned()), + "/unload-cases" => ("text/html", unload_navigation_cases_source()), + "/unload-opaque-host" => ("text/html", opaque_unload_navigation_source().to_owned()), + path if path.starts_with("/unload-previous?") => ("text/html", r#""#.to_owned()), + "/unload-child" => ("text/html", r#""#.to_owned()), + path if path.starts_with("/unload-report?") => ("text/html", format!(r#""#)), "/prefetch" => ("text/html", format!(r#""# + .to_owned() +} + +fn opaque_unload_navigation_source() -> &'static str { + r#""# +} + +async fn read_previous_document_unload_cases(script: &str) -> Result { + let server = NavigationTimingServer::spawn().await; + let browser = Browser::new(AppConfig::default())?; + let mut page = tokio::time::timeout( + Duration::from_secs(30), + browser.fetch(&format!("{}/unload-cases", server.origin)), + ) + .await??; + page.evaluate_runtime_expression_by_value_async(&format!( + "void ({script}).catch(error => globalThis.caseError=String(error))" + )) + .await?; + let waited = tokio::time::timeout( + Duration::from_secs(35), + browser.wait_for_script_truthy( + &mut page, + "Boolean(globalThis.observations || globalThis.caseError)", + Duration::from_secs(30), + ), + ) + .await; + let result = read_json( + &mut page, + "JSON.stringify({observations:globalThis.observations,error:globalThis.caseError,stage:globalThis.unloadStage,rows:globalThis.unloadRows})", + ) + .await?; + assert!(matches!(waited, Ok(Ok(()))), "{waited:?}: {result}"); + assert!(result.get("error").is_none(), "{result}"); + Ok(result) +} + +async fn check_previous_document_unload_timing(privacy: bool) -> Result<()> { + let result = read_previous_document_unload_cases(&format!("runUnloadCases({privacy})")).await?; + let rows = result["observations"].as_array().unwrap(); + assert_eq!(rows.len(), if privacy { 5 } else { 2 }, "{result}"); + for row in rows { + let nav = &row["nav"]; + let legacy = &row["legacy"]; + if privacy { + for field in ["unloadEventStart", "unloadEventEnd"] { + assert_eq!( + nav[field], 0, + "cross-origin unload timing must be hidden: {row}" + ); + assert_eq!(legacy[field], 0, "{row}"); + } + } else { + let start = nav["unloadEventStart"].as_f64().unwrap(); + let end = nav["unloadEventEnd"].as_f64().unwrap(); + assert!( + start > 0.0, + "previous document unload timing must be observed: {row}" + ); + assert!( + end - start >= 100.0, + "the root unload handler must be measured: {row}" + ); + assert!( + end - start < 250.0, + "pagehide and descendant unload must be excluded: {row}" + ); + for (field, relative) in [("unloadEventStart", start), ("unloadEventEnd", end)] { + let absolute = legacy[field].as_f64().unwrap(); + assert!( + absolute >= legacy["navigationStart"].as_f64().unwrap(), + "{row}" + ); + assert!( + (absolute - row["timeOrigin"].as_f64().unwrap() - relative).abs() < 1.1, + "modern and legacy unload timing must describe the same event: {row}" + ); + } + } + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn previous_document_unload_timing_measures_only_the_root_event() -> Result<()> { + check_previous_document_unload_timing(false).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn previous_document_unload_timing_hides_cross_origin_and_redirects() -> Result<()> { + check_previous_document_unload_timing(true).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn previous_document_unload_timing_preserves_inherited_opaque_origins() -> Result<()> { + let result = read_previous_document_unload_cases("runOpaqueUnloadCases()").await?; + let rows = result["observations"].as_array().unwrap(); + assert_eq!(rows.len(), 1, "{result}"); + let row = &rows[0]; + assert_eq!( + row["oldAccess"], true, + "old srcdoc must inherit its parent's opaque origin: {row}" + ); + assert_eq!( + row["parentAccess"], true, + "new srcdoc must inherit the same opaque origin: {row}" + ); + let start = row["nav"]["unloadEventStart"].as_f64().unwrap(); + let end = row["nav"]["unloadEventEnd"].as_f64().unwrap(); + assert!( + start > 0.0 && end - start >= 100.0, + "inherited opaque origin must retain its real previous unload timing: {row}" + ); + assert!( + row["legacy"]["unloadEventStart"].as_f64().unwrap() > 0.0, + "{row}" + ); + for (field, relative) in [("unloadEventStart", start), ("unloadEventEnd", end)] { + let absolute = row["legacy"][field].as_f64().unwrap(); + assert!( + absolute >= row["legacy"]["navigationStart"].as_f64().unwrap(), + "{row}" + ); + assert!( + (absolute - row["timeOrigin"].as_f64().unwrap() - relative).abs() < 1.1, + "{row}" + ); + } + Ok(()) +} + async fn read_json( page: &mut moli_core::page::Page, expression: &str, diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs index b64cb0115d4..c8b8fd82c8d 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs @@ -620,6 +620,21 @@ fn dispatch_unload_lifecycle_event_for_runtime_owner<'s>( .map(|document| host.enter_document_unload(document)) }); let previous_unload = replace_navigation_unload_event_active(scope, owner, true); + let unload_observation = (event_type == "unload") + .then(|| { + let host_ptr = context_host_ptr_from_global_bridge(scope)?; + let host = unsafe { &*host_ptr }; + let dispatch = runtime_window_dispatch_scope(scope, owner)?; + let loader = host.document_resource_loader_for_dispatch_scope(dispatch)?; + let origin = host.window_message_source_security(dispatch)?; + Some(( + loader, + origin, + std::time::Instant::now(), + moli_time::unix_epoch_millis(), + )) + }) + .flatten(); if runtime_window_is_global(scope, owner) { if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) { let host = unsafe { &mut *host_ptr }; @@ -648,6 +663,11 @@ fn dispatch_unload_lifecycle_event_for_runtime_owner<'s>( unsafe { &mut *host_ptr } .dispatch_lightweight_popup_window_event(scope, popup_id, event_type, event); } + if let Some((loader, origin, started, start)) = unload_observation { + loader.record_document_unload_timing( + crate::network::context::DocumentUnloadTiming::finish(origin, started, start), + ); + } replace_navigation_unload_event_active(scope, owner, previous_unload); } diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs index 9e21604c750..74e316ee8fd 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs @@ -653,6 +653,12 @@ fn performance_timing_snapshot<'s>( let time_origin = performance_slot_number(scope, performance, PERFORMANCE_TIME_ORIGIN_SLOT).unwrap_or(0.0); let mut snapshot = PerformanceTimingSnapshot::new(time_origin); + if let Some((start, end)) = + super::navigation_timing::previous_document_unload_times(scope, performance) + { + snapshot.unload_event_start = legacy_timing_epoch_millis(start); + snapshot.unload_event_end = legacy_timing_epoch_millis(end); + } if let Some(timestamp) = performance_lifecycle_timestamp(scope, performance, DOM_CONTENT_LOADED_START_INDEX) { diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/navigation_timing.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/navigation_timing.rs index a013bef97a7..06b438033ea 100644 --- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/navigation_timing.rs +++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/navigation_timing.rs @@ -1,6 +1,58 @@ use super::*; use crate::util::context_host_ptr_from_global_bridge; +pub(super) fn previous_document_unload_times<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> Option<(f64, f64)> { + let context = object.get_creation_context(scope)?; + let scope = &mut v8::ContextScope::new(scope, context); + let host_ptr = context_host_ptr_from_global_bridge(scope)?; + let host = unsafe { &*host_ptr }; + let dispatch = host.window_dispatch_scope_for_context(scope, context)?; + host.current_runtime_window_execution_context_identity_for_dispatch_scope(scope, dispatch)?; + let loader = host.document_resource_loader_for_dispatch_scope(dispatch)?; + if let Some(timing) = loader.navigation_timing() { + let snapshot = timing.snapshot()?; + let origin = moli_url::WebOrigin::from_url(&snapshot.head.final_url); + if snapshot.head.url_list().has_cross_origin_url(&origin) { + return None; + } + } + let origin = host.window_message_source_security(dispatch)?; + loader + .previous_document_unload_timing()? + .for_origin(&origin) +} + +pub(super) fn refresh_navigation_unload_timing<'s>( + scope: &mut v8::PinScope<'s, '_>, + entry: v8::Local<'s, v8::Object>, +) { + let Some((start, end)) = previous_document_unload_times(scope, entry) else { + return; + }; + let Some(context) = entry.get_creation_context(scope) else { + return; + }; + let scope = &mut v8::ContextScope::new(scope, context); + let Some(time_origin) = super::window_state::current_window_performance_time_origin_seed(scope) + else { + return; + }; + for (slot, absolute) in [ + (install::NAV_UNLOAD_EVENT_START_SLOT, start), + (install::NAV_UNLOAD_EVENT_END_SLOT, end), + ] { + set_performance_entry_slot_number( + scope, + entry, + slot, + moli_time::coarsened_dom_time_millis((absolute - time_origin).max(0.0)), + ); + } +} + /// Refresh the entry in its own Window realm. Borrowed prototype getters must /// not pick up the caller's navigation or a replacement Window's Document. pub(in crate::context_bootstrap) fn refresh_navigation_timing<'s>( @@ -12,6 +64,7 @@ pub(in crate::context_bootstrap) fn refresh_navigation_timing<'s>( { return; } + refresh_navigation_unload_timing(scope, entry); let Some(context) = entry.get_creation_context(scope) else { return; }; diff --git a/moli-renderer-v8/src/document_runtime/timing.rs b/moli-renderer-v8/src/document_runtime/timing.rs index f67626ede42..15d9cbfe686 100644 --- a/moli-renderer-v8/src/document_runtime/timing.rs +++ b/moli-renderer-v8/src/document_runtime/timing.rs @@ -58,6 +58,26 @@ impl DocumentRuntime { } impl DocumentTiming { + pub(crate) fn from_navigation( + navigation: &crate::network::navigation::NavigationTiming, + ) -> Self { + Self { + time_origin: navigation.time_origin(), + started: navigation.started_at(), + lifecycle: [None; 4], + } + } + pub(crate) fn from_navigation_start(started: Instant, start: std::time::SystemTime) -> Self { + Self { + time_origin: start + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() + * 1000.0, + started, + lifecycle: [None; 4], + } + } pub(crate) fn snapshot(&self) -> DocumentTimingSnapshot { DocumentTimingSnapshot { time_origin: self.time_origin, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs index 3bcfbfe4f26..6f9bd44d3d5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs @@ -246,6 +246,7 @@ impl PageScriptHost { document_credentialless, credentialless_storage_nonce, ); + entry.set_performance_navigation_start(navigation_start); } let snapshot = self.cache_child_snapshot_with_current_document_policy(handle, snapshot)?; @@ -299,6 +300,7 @@ impl PageScriptHost { document_credentialless, credentialless_storage_nonce, ); + entry.set_performance_navigation_start(navigation_start); } let result = if let Some(snapshot) = cached_snapshot { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index 2571c713d4a..6b6cb796ccd 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -335,6 +335,12 @@ impl PageScriptHost { ); return None; } + let previous_unload = expected_current_owner + .filter(|_| { + local_window_transition == FrameDocumentLocalWindowTransition::ReplaceLocalWindow + }) + .and_then(|owner| self.document_resource_loader_for_owner(owner)) + .and_then(|loader| loader.document_unload_timing()); // Synthetic child Documents inherit the exact parent authority that // existed at the commit boundary. Capture it before retiring the old // child generation; never fall back to the ambient main Document. @@ -466,6 +472,13 @@ impl PageScriptHost { resource_authority, client_policy, ); + document_loader.set_previous_document_unload_timing(previous_unload); + if let Some(navigation) = document_loader.navigation_timing() { + self.child_browsing_contexts + .get_mut(&handle) + .expect("committed child Document retains its browsing context") + .set_performance_navigation_timing(&navigation); + } if matches!( owner_transition.local_window_owner_transition(), FrameLocalWindowOwnerTransition::Preserved { .. } 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 47e766fcfc9..275e5c07f5b 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 @@ -1055,6 +1055,22 @@ impl ChildBrowsingContextEntry { self.performance_time_origin = ChildPerformanceTimeOrigin::now(); } + pub(super) fn set_performance_navigation_start( + &mut self, + start: (std::time::Instant, std::time::SystemTime), + ) { + self.performance_time_origin = + ChildPerformanceTimeOrigin(DocumentTiming::from_navigation_start(start.0, start.1)); + } + + pub(super) fn set_performance_navigation_timing( + &mut self, + navigation: &crate::network::navigation::NavigationTiming, + ) { + self.performance_time_origin = + ChildPerformanceTimeOrigin(DocumentTiming::from_navigation(navigation)); + } + pub(super) fn clear_script_execution_state(&mut self) { self.clear_child_classic_script_document_state(); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index d2678076cd4..0ab99d232d7 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -2407,6 +2407,14 @@ impl PageScriptHost { }; let changed_document = current_document.owner != commit.owner; let was_initial_empty = current_document.is_initial_empty_document; + let previous_unload = (changed_document && !was_initial_empty) + .then(|| { + self.document_resource_loader_for_window_owner( + super::WindowDocumentOwner::LightweightPopup(current_document.owner), + ) + }) + .flatten() + .and_then(|loader| loader.document_unload_timing()); let previous_local_window_id = current_document.local_window_id; let document_domain_was_set = current_document .access_origin @@ -2593,7 +2601,8 @@ impl PageScriptHost { ), resource_authority, client_policy, - ); + ) + .set_previous_document_unload_timing(previous_unload); } if let Some(retired_local_window_id) = transition.retired_local_window_id { self.retire_lightweight_popup_local_window(scope, popup_id, retired_local_window_id); diff --git a/moli-renderer-v8/src/network/context/document.rs b/moli-renderer-v8/src/network/context/document.rs index 3ea3cbded27..0c0c03b5656 100644 --- a/moli-renderer-v8/src/network/context/document.rs +++ b/moli-renderer-v8/src/network/context/document.rs @@ -172,6 +172,7 @@ pub struct DocumentResourceLoader { authority: Arc, csp_reports: Arc, navigation_timing: Option, + unload_timings: super::unload_timing::DocumentUnloadTimings, } /// Inputs that exist before the initial committed Document owner is known. @@ -185,6 +186,7 @@ pub(crate) struct DocumentResourceLoaderBootstrap { request_client: ResourceRequestClient, task_runner: RendererResourceTaskRunner, navigation_timing: Option, + previous_document_unload: Option, } impl DocumentResourceLoaderBootstrap { @@ -194,6 +196,7 @@ impl DocumentResourceLoaderBootstrap { ) -> Self { Self { navigation_timing: request_client.take_navigation_timing_seed(), + previous_document_unload: request_client.take_previous_document_unload_seed(), request_client, task_runner, } @@ -203,6 +206,7 @@ impl DocumentResourceLoaderBootstrap { let mut loader = DocumentResourceLoader::new(self.request_client, self.task_runner, context); loader.navigation_timing = self.navigation_timing; + loader.set_previous_document_unload_timing(self.previous_document_unload); loader } @@ -284,6 +288,7 @@ impl DocumentResourceLoader { creation_url, csp_reports: Default::default(), navigation_timing: None, + unload_timings: Default::default(), authority, } } @@ -352,6 +357,25 @@ impl DocumentResourceLoader { self.navigation_timing.clone() } + pub(crate) fn record_document_unload_timing(&self, timing: super::DocumentUnloadTiming) { + self.unload_timings.record(timing); + } + + pub(crate) fn document_unload_timing(&self) -> Option { + self.unload_timings.own() + } + + pub(crate) fn set_previous_document_unload_timing( + &self, + timing: Option, + ) { + self.unload_timings.set_previous(timing); + } + + pub(crate) fn previous_document_unload_timing(&self) -> Option { + self.unload_timings.previous() + } + pub(crate) fn navigation_time_origin(&self) -> Option { self.navigation_timing .as_ref() @@ -442,6 +466,7 @@ impl DocumentResourceLoader { creation_url: self.creation_url.clone(), csp_reports: self.csp_reports.clone(), navigation_timing: self.navigation_timing.clone(), + unload_timings: self.unload_timings.clone(), } } diff --git a/moli-renderer-v8/src/network/context/mod.rs b/moli-renderer-v8/src/network/context/mod.rs index 6782e67db38..5758d023d70 100644 --- a/moli-renderer-v8/src/network/context/mod.rs +++ b/moli-renderer-v8/src/network/context/mod.rs @@ -1,6 +1,7 @@ mod document; mod registry; mod request_context; +mod unload_timing; mod worker; #[cfg(test)] @@ -15,6 +16,7 @@ pub use document::{ }; pub(crate) use registry::DocumentResourceLoaderRegistry; pub(crate) use request_context::{DocumentFetchContext, SubresourceRequestEnvironment}; +pub(crate) use unload_timing::DocumentUnloadTiming; #[cfg(test)] pub(crate) use worker::WorkerResourceLoaderState; pub(crate) use worker::{WorkerResourceLoader, WorkerResourceOwner}; diff --git a/moli-renderer-v8/src/network/context/unload_timing.rs b/moli-renderer-v8/src/network/context/unload_timing.rs new file mode 100644 index 00000000000..0f7460292c8 --- /dev/null +++ b/moli-renderer-v8/src/network/context/unload_timing.rs @@ -0,0 +1,67 @@ +use std::{sync::Arc, time::Instant}; + +use parking_lot::Mutex; + +use crate::context_bootstrap::RuntimeMessageSourceSecurity; + +/// One retiring Document's own unload event, with its immutable native origin. +/// Descendant events and lifecycle authority are deliberately not retained. +#[derive(Clone, Debug)] +pub(crate) struct DocumentUnloadTiming { + origin: RuntimeMessageSourceSecurity, + start: f64, + end: f64, +} + +impl DocumentUnloadTiming { + pub(crate) fn finish( + origin: RuntimeMessageSourceSecurity, + started: Instant, + start: f64, + ) -> Self { + Self { + origin, + start, + end: start + started.elapsed().as_secs_f64() * 1000.0, + } + } + + pub(crate) fn for_origin(&self, origin: &RuntimeMessageSourceSecurity) -> Option<(f64, f64)> { + let same_origin = match (self.origin.serialized_origin(), origin.serialized_origin()) { + (Some("null"), Some("null")) => matches!( + (self.origin.opaque_origin(), origin.opaque_origin()), + (Some(left), Some(right)) if left == right + ), + (Some(left), Some(right)) => left == right, + _ => false, + }; + same_origin.then_some((self.start, self.end)) + } +} + +#[derive(Default)] +struct DocumentUnloadRecords { + own: Option, + previous: Option, +} + +#[derive(Clone, Default)] +pub(super) struct DocumentUnloadTimings(Arc>); + +impl DocumentUnloadTimings { + pub(super) fn record(&self, timing: DocumentUnloadTiming) { + self.0.lock().own.get_or_insert(timing); + } + + pub(super) fn own(&self) -> Option { + self.0.lock().own.clone() + } + + pub(super) fn set_previous(&self, timing: Option) { + self.0.lock().previous = timing; + } + + pub(super) fn previous(&self) -> Option { + self.0.lock().previous.clone() + } +} diff --git a/moli-renderer-v8/src/network/request_client.rs b/moli-renderer-v8/src/network/request_client.rs index 8b230d7f7bc..3913a66b99e 100644 --- a/moli-renderer-v8/src/network/request_client.rs +++ b/moli-renderer-v8/src/network/request_client.rs @@ -68,6 +68,7 @@ impl ClientSecurityPolicy { #[derive(Clone, Default)] struct DocumentRequestContext { navigation_timing_seed: Option, + previous_document_unload_seed: Option, preloads: super::preloads::DocumentPreloads, response_links: Option, client_security_policy: ClientSecurityPolicy, @@ -156,6 +157,22 @@ impl ResourceRequestClient { .and_then(|context| Arc::make_mut(context).navigation_timing_seed.take()) } + pub(crate) fn set_previous_document_unload_seed( + &mut self, + timing: Option, + ) { + self.document_request_context_mut() + .previous_document_unload_seed = timing; + } + + pub(crate) fn take_previous_document_unload_seed( + &mut self, + ) -> Option { + self.document_requests + .as_mut() + .and_then(|context| Arc::make_mut(context).previous_document_unload_seed.take()) + } + // Standalone clients must return their thread-affine lifetime owner; the // owner dereferences to this request-side handle for existing call sites. #[allow(clippy::new_ret_no_self)] @@ -511,6 +528,12 @@ impl ResourceRequestClient { client.document_request_context_mut().navigation_timing_seed = Some(timing); } client + .document_request_context_mut() + .previous_document_unload_seed = self + .document_requests + .as_ref() + .and_then(|context| context.previous_document_unload_seed.clone()); + client } /// Creates a Worker-owned adapter while retaining the creator Document's diff --git a/moli-renderer-v8/src/runtime/owner_local_store/entry.rs b/moli-renderer-v8/src/runtime/owner_local_store/entry.rs index ea235f6b619..efd4002b069 100644 --- a/moli-renderer-v8/src/runtime/owner_local_store/entry.rs +++ b/moli-renderer-v8/src/runtime/owner_local_store/entry.rs @@ -115,7 +115,9 @@ impl CommittedNavigationEntry { pub(super) fn commit_source(&mut self, commit: PageVmSourceDocumentCommit) { let reused_initial_window = match commit { PageVmSourceDocumentCommit::ReplaceWindow(commit) => { - commit.unload_and_detach(); + let previous_unload = commit.unload_and_detach(); + self.navigation + .set_previous_document_unload(previous_unload); None } PageVmSourceDocumentCommit::ReuseInitialWindow(window) => Some(window), diff --git a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs index f688cc1c084..09087a1c84e 100644 --- a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs +++ b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs @@ -617,6 +617,29 @@ pub(in crate::runtime) struct PageVmCommittedNavigationBootstrap { } impl PageVmCommittedNavigationBootstrap { + pub(in crate::runtime) fn set_previous_document_unload( + &mut self, + timing: Option, + ) { + match self + .payload + .as_mut() + .expect("committed bootstrap retains its payload") + { + PageVmCommittedNavigationBootstrapPayload::Followed(payload) => { + payload + .request_client + .set_previous_document_unload_seed(timing); + } + PageVmCommittedNavigationBootstrapPayload::PreparedResponse(payload) => { + payload + .request + .loader + .set_previous_document_unload_seed(timing); + } + } + } + #[cfg(test)] pub(in crate::runtime) fn inject_commit_panic_for_test(&self, injection_header: &str) { if self.payload.as_ref().is_some_and(|payload| match payload { @@ -1569,9 +1592,12 @@ impl PageVm { env.history_policy_container = history_policy_container; let mut runtime_hooks = self.runtime_hooks.clone().for_cross_document_commit(); runtime_hooks.web_mcp_navigation = web_mcp_invocation; + let mut request_client = self.request_client.clone(); if runtime_hooks.has_renderer_page_script_environment() { - self.prepare_main_window_proxy_navigation(self.page_id)? + let previous_unload = self + .prepare_main_window_proxy_navigation(self.page_id)? .unload_and_detach(); + request_client.set_previous_document_unload_seed(previous_unload); self.record_main_navigation_commit(); self.retire_committed_main_script_vm(); } else { @@ -1586,7 +1612,7 @@ impl PageVm { bootstrap_committed_followed_location_navigation( self.page_id, self.local_executor.clone(), - self.request_client.clone(), + request_client, env, runtime_hooks, navigation_bootstrap_entry, diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs index cb897acd5a1..a18eea6fa3b 100644 --- a/moli-renderer-v8/src/script_vm.rs +++ b/moli-renderer-v8/src/script_vm.rs @@ -71,32 +71,36 @@ pub(crate) struct MainWindowProxyNavigationCommit { } impl MainWindowProxyNavigationCommit { - pub(crate) fn unload_and_detach(self) { - let Some(context) = self.context else { - return; - }; - self.renderer_document_isolate + pub(crate) fn unload_and_detach(self) -> Option { + let context = self.context?; + let _unload_callbacks = self.devtools_target.pause_ref().begin_unload_callbacks(); + let previous_unload = self + .renderer_document_isolate .with_renderer_document_isolate_mut(|isolate| { let scope = pin!(v8::HandleScope::new(isolate)); let scope = &mut scope.init(); let context = v8::Local::new(scope, &context); - { + let previous_unload = { let scope = &mut v8::ContextScope::new(scope, context); // Unload sees the attached WindowProxy, and its outgoing // Document remains associated after execution retirement. let host_ptr = (*self.context_host).as_ptr(); + let loader = unsafe { &*host_ptr }.current_main_document_resource_loader(); PageScriptHost::dispatch_main_document_unload_for_navigation_commit( scope, host_ptr, ); crate::context_bootstrap::retain_window_document_in_retired_realm(scope); - } + loader.and_then(|loader| loader.document_unload_timing()) + }; context.detach_global(); + previous_unload }); tracing::debug!( page_id = self.page_id, isolate_identity_key = self.renderer_document_isolate.identity_key(), "detached committed main WindowProxy for replacement context" ); + previous_unload } } @@ -2885,6 +2889,7 @@ impl ScriptVm { let Some(runtime) = self.current_main_world() else { return Ok(MainWindowProxyNavigationCommit { context: None, + devtools_target: self.devtools_target(), context_host: self._context_host.clone(), renderer_document_isolate: self.renderer_document_isolate.clone(), page_id, diff --git a/moli-webapi/src/performance/legacy.rs b/moli-webapi/src/performance/legacy.rs index 9b5e0dece70..ef8e35977df 100644 --- a/moli-webapi/src/performance/legacy.rs +++ b/moli-webapi/src/performance/legacy.rs @@ -296,6 +296,7 @@ pub fn performance_navigation_timing_attribute_getter_callback<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { + crate::embedding::refresh_performance_entry(scope, args.this()); let Some(slot) = callback_data_item( scope, &args, @@ -421,6 +422,7 @@ pub fn performance_navigation_timing_to_json_callback<'s>( args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { + crate::embedding::refresh_performance_entry(scope, args.this()); let Some(output) = super::entries::resource_timing_json_snapshot(scope, args.this()) else { throw_type_error(scope, "Illegal invocation"); return;