fix(performance): report previous document unload timing

Observe each retiring Document's own unload event and transfer that record
only when its replacement commits. Expose modern and legacy timestamps
through the same native origin and redirect checks, including inherited
opaque origins. Keep pagehide and descendant unload handlers outside the
recorded interval.

Retain the accepted navigation clock for local child Documents so their
previous unload remains on the new timeline. Cover iframe and popup
replacement, cross-origin redirects, sandbox isolation and local srcdoc.
This commit is contained in:
ldm0
2026-11-20 22:48:01 +08:00
parent d828673e8f
commit 8e3b445a1c
17 changed files with 530 additions and 11 deletions
@@ -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", "<!doctype html><body><iframe src='/empty'></iframe>".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#"<!doctype html><body><iframe src='/unload-child'></iframe><script>
function busy(ms) {const end=performance.now()+ms;while(performance.now()<end){}}
addEventListener('pagehide',()=>busy(250));
addEventListener('unload',()=>busy(105));
addEventListener('load',()=> (opener||parent).postMessage({phase:'ready',token:new URL(location.href).searchParams.get('token')},'*'));
</script>"#.to_owned()),
"/unload-child" => ("text/html", r#"<!doctype html><script>
addEventListener('unload',()=>{const end=performance.now()+405;while(performance.now()<end){}});
</script>"#.to_owned()),
path if path.starts_with("/unload-report?") => ("text/html", format!(r#"<!doctype html><script>
{STATE_WAITER}
addEventListener('load',()=> (opener||parent).postMessage({{phase:'report',token:new URL(location.href).searchParams.get('token'),...snapshot(window),legacy:performance.timing.toJSON()}},'*'));
</script>"#)),
"/prefetch" => ("text/html", format!(r#"<!doctype html><body><script>
{STATE_WAITER}
(async () => {{
@@ -405,6 +420,219 @@ async fn frame_navigation_time_origin_follows_beforeunload_handlers() -> Result<
Ok(())
}
fn unload_navigation_cases_source() -> String {
r#"<!doctype html><body><script>
globalThis.runUnloadCases = async privacy => {
const messages = new Map(), waiters = new Map();
addEventListener('message', event => {
const data=event.data;
if (!data || !data.token || !data.phase) return;
const key=data.token+':'+data.phase;
messages.set(key,data);
if(waiters.has(key)) waiters.get(key)(data);
});
const waitFor=(token,phase)=>new Promise(resolve=> {
const key=token+':'+phase;
if(messages.has(key)) resolve(messages.get(key));
else waiters.set(key,resolve);
});
const remote=new URL(location.href);
remote.hostname=location.hostname==='127.0.0.1'?'localhost':'127.0.0.1';
const observations=[];
for (const kind of ['iframe','popup']) {
for (const mode of (privacy?['cross','redirect','opaque']:['same'])) {
if(mode==='opaque' && kind==='popup') continue;
const token=kind+'-'+mode;
globalThis.unloadStage=token+':ready';
const ready=waitFor(token,'ready'), report=waitFor(token,'report');
const old=(mode==='cross'?remote.origin:location.origin)+'/unload-previous?token='+token;
let win,frame;
if(kind==='iframe') {
frame=document.createElement('iframe');
if(mode==='opaque') frame.sandbox='allow-scripts';
frame.src=old;
document.body.appendChild(frame);win=frame.contentWindow;
} else win=window.open(old);
await ready;
globalThis.unloadStage=token+':navigate';
const destination=location.origin+'/unload-report?token='+token;
const target=mode==='redirect'?location.origin+'/redirect?to='+remote.origin+'/redirect?to='+destination:destination;
win.location=target;
const row={kind,mode,...await report};
observations.push(row);globalThis.unloadRows=observations;
if(frame) frame.remove();else win.close();
}
}
globalThis.observations=observations;
};
globalThis.runOpaqueUnloadCases = async () => {
globalThis.unloadStage='opaque-inherited:load';
const done=new Promise(resolve => addEventListener('message',event => {
if(event.data && event.data.phase==='report') resolve(event.data);
}));
const source=await (await fetch('/unload-opaque-host')).text();
const frame=document.createElement('iframe');
frame.src='data:text/html;charset=utf-8,'+encodeURIComponent(source);document.body.appendChild(frame);
globalThis.observations=[await done];frame.remove();
};
</script>"#
.to_owned()
}
fn opaque_unload_navigation_source() -> &'static str {
r#"<!doctype html><body><script>
function documentFor(fn) {return '<!doctype html><body><script>('+fn.toString()+')();<'+'/script>';}
addEventListener('load',async()=>{
const frame=document.createElement('iframe');
let oldAccess;
const ready=new Promise(resolve=>addEventListener('message',event=>{
if(event.source!==frame.contentWindow) return;
if(event.data.phase==='ready') {oldAccess=event.data.parentAccess;resolve();}
if(event.data.phase==='report') parent.postMessage({kind:'iframe',mode:'opaque-inherited',oldAccess,...event.data},'*');
}));
frame.srcdoc=documentFor(function(){
addEventListener('unload',()=>{const end=performance.now()+105;while(performance.now()<end){}});
addEventListener('load',()=>{
let parentAccess=false;try{parentAccess=Boolean(parent.document);}catch{}
parent.postMessage({phase:'ready',parentAccess},'*');
});
});
document.body.appendChild(frame);await ready;
frame.srcdoc=documentFor(function(){
addEventListener('load',()=>{
let parentAccess=false;try{parentAccess=Boolean(parent.document);}catch{}
parent.postMessage({phase:'report',parentAccess,timeOrigin:performance.timeOrigin,nav:performance.getEntriesByType('navigation')[0].toJSON(),legacy:performance.timing.toJSON()},'*');
});
});
});
</script>"#
}
async fn read_previous_document_unload_cases(script: &str) -> Result<serde_json::Value> {
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,
@@ -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);
}
@@ -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)
{
@@ -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;
};
@@ -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,
@@ -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 {
@@ -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 { .. }
@@ -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();
}
@@ -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);
@@ -172,6 +172,7 @@ pub struct DocumentResourceLoader {
authority: Arc<DocumentResourceLoaderAuthority>,
csp_reports: Arc<crate::content_security_policy::ContentSecurityPolicyReports>,
navigation_timing: Option<crate::network::navigation::NavigationTiming>,
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<crate::network::navigation::NavigationTiming>,
previous_document_unload: Option<super::DocumentUnloadTiming>,
}
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<super::DocumentUnloadTiming> {
self.unload_timings.own()
}
pub(crate) fn set_previous_document_unload_timing(
&self,
timing: Option<super::DocumentUnloadTiming>,
) {
self.unload_timings.set_previous(timing);
}
pub(crate) fn previous_document_unload_timing(&self) -> Option<super::DocumentUnloadTiming> {
self.unload_timings.previous()
}
pub(crate) fn navigation_time_origin(&self) -> Option<f64> {
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(),
}
}
@@ -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};
@@ -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<DocumentUnloadTiming>,
previous: Option<DocumentUnloadTiming>,
}
#[derive(Clone, Default)]
pub(super) struct DocumentUnloadTimings(Arc<Mutex<DocumentUnloadRecords>>);
impl DocumentUnloadTimings {
pub(super) fn record(&self, timing: DocumentUnloadTiming) {
self.0.lock().own.get_or_insert(timing);
}
pub(super) fn own(&self) -> Option<DocumentUnloadTiming> {
self.0.lock().own.clone()
}
pub(super) fn set_previous(&self, timing: Option<DocumentUnloadTiming>) {
self.0.lock().previous = timing;
}
pub(super) fn previous(&self) -> Option<DocumentUnloadTiming> {
self.0.lock().previous.clone()
}
}
@@ -68,6 +68,7 @@ impl ClientSecurityPolicy {
#[derive(Clone, Default)]
struct DocumentRequestContext {
navigation_timing_seed: Option<super::navigation::NavigationTiming>,
previous_document_unload_seed: Option<super::context::DocumentUnloadTiming>,
preloads: super::preloads::DocumentPreloads,
response_links: Option<super::context::DocumentResponseLinkObserver>,
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<super::context::DocumentUnloadTiming>,
) {
self.document_request_context_mut()
.previous_document_unload_seed = timing;
}
pub(crate) fn take_previous_document_unload_seed(
&mut self,
) -> Option<super::context::DocumentUnloadTiming> {
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
@@ -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),
@@ -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<crate::network::context::DocumentUnloadTiming>,
) {
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,
+12 -7
View File
@@ -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<crate::network::context::DocumentUnloadTiming> {
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,
+2
View File
@@ -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;