fix(navigation): preserve iframe documents on src fragment updates

Route native iframe attribute writes through shared same-document navigation. Preserve initial-document history replacement and pending document loads, and cover namespace and Attr mutations plus canceled navigation.
This commit is contained in:
ldm0
2026-11-20 22:47:43 +08:00
parent aacf883a53
commit 6aa5cdd7be
10 changed files with 258 additions and 9 deletions
+1 -1
View File
@@ -213,7 +213,7 @@ pub(crate) use location_navigation::{
HyperlinkNavigationOptions, LocationNavigationKind,
dispatch_top_level_navigation_event_with_source_element,
history_entry_seed_for_cross_document_location, is_native_location, navigate_borrowed_location,
navigate_child_meta_refresh, navigate_location_object_for_form_fragment,
navigate_child_meta_refresh, navigate_location_object_for_element_fragment,
navigate_location_object_for_hyperlink, navigate_location_object_with_child_navigate_event,
navigate_location_object_with_source_element, navigate_top_level_meta_refresh,
navigate_top_level_same_document_from_browser, resolve_cross_window_location_target,
@@ -149,7 +149,7 @@ pub(crate) fn navigate_location_object<'s>(
);
}
pub(crate) fn navigate_location_object_for_form_fragment<'s>(
pub(crate) fn navigate_location_object_for_element_fragment<'s>(
scope: &mut v8::PinScope<'s, '_>,
location: v8::Local<'s, v8::Object>,
href: &str,
@@ -868,12 +868,18 @@ impl DocumentRuntime {
let is_navigation_attribute =
runtime.frame_owner_navigation_attribute_matches(handle, name);
if is_navigation_attribute || is_srcdoc {
runtime.clear_ignored_child_frame_navigation_attribute(handle);
runtime.clear_child_frame_navigation_attribute_state(handle);
}
if is_srcdoc {
runtime.clear_child_browsing_context_cached_snapshot_for_navigation(handle);
}
runtime.refresh_child_browsing_context_and_queue_ready_work(scope, handle);
if !removed
&& is_navigation_attribute
&& runtime.run_child_frame_attribute_fragment_navigation(scope, handle)
{
return true;
}
// A srcdoc attribute change only queues a navigation. Keep the live
// Document's History and Navigation objects intact until it commits.
if !is_srcdoc
@@ -63,6 +63,10 @@ pub(super) struct ChildBrowsingContextEntry {
// Rejected attributes remain reflected without replacing an admitted
// navigation. Wrapper refreshes must not retry them after an ancestor moves.
ignored_attribute_bootstrap: Option<ChildBrowsingContextBootstrap>,
// Fragment attributes update the live Document through Location's shared
// navigation machinery. Keep them separate from an admitted document load,
// which can still complete after the fragment change.
same_document_attribute_bootstrap: Option<ChildBrowsingContextBootstrap>,
pending_attribute_bootstrap_commit: bool,
pending_live_navigation: Option<ChildBrowsingContextBootstrap>,
pending_live_navigation_initiator_url: Option<Url>,
@@ -30,13 +30,14 @@ impl ChildFrameOwnerElementKind {
}
impl PageScriptHost {
pub(crate) fn clear_ignored_child_frame_navigation_attribute(&mut self, handle: DomHandle) {
pub(crate) fn clear_child_frame_navigation_attribute_state(&mut self, handle: DomHandle) {
if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) {
entry.ignored_attribute_bootstrap = None;
entry.same_document_attribute_bootstrap = None;
}
}
pub(crate) fn child_frame_src_attribute_navigation_is_ignored(
pub(crate) fn child_frame_src_attribute_navigation_is_handled(
&self,
handle: DomHandle,
) -> bool {
@@ -44,7 +45,50 @@ impl PageScriptHost {
|| self
.child_browsing_contexts
.get(&handle)
.is_some_and(|entry| entry.ignored_attribute_bootstrap.is_some())
.is_some_and(|entry| {
entry.ignored_attribute_bootstrap.is_some()
|| entry.same_document_attribute_bootstrap.is_some()
})
}
pub(crate) fn run_child_frame_attribute_fragment_navigation(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
) -> bool {
let Some(url) = self
.child_browsing_contexts
.get(&handle)
.and_then(|entry| entry.same_document_attribute_bootstrap.as_ref())
.and_then(Self::child_browsing_context_bootstrap_url)
else {
return false;
};
let kind = if self.child_frame_attribute_navigation_replaces_current_entry(handle, &url) {
crate::context_bootstrap::LocationNavigationKind::Replace
} else {
crate::context_bootstrap::LocationNavigationKind::Assign
};
let Ok(context) = self.ensure_prebootstrapped_child_default_context(scope, handle) else {
return false;
};
let scope = &mut v8::ContextScope::new(scope, context);
let window = context.global(scope);
let Some(location) = crate::context_bootstrap::window_location_for_holder(scope, window)
else {
return false;
};
// Every native attribute mutation uses this path, including Attr.value.
// The prior document load stays independent of this fragment update.
crate::context_bootstrap::navigate_location_object_for_element_fragment(
scope,
location,
url.as_str(),
kind,
None,
false,
);
true
}
pub(super) fn child_frame_attribute_bootstrap_repeats_ancestor(
@@ -182,7 +182,20 @@ impl PageScriptHost {
&attribute_bootstrap,
))
.then(|| attribute_bootstrap.clone());
let attribute_bootstrap = if ignored_attribute_bootstrap.is_some() {
let same_document_attribute_bootstrap = (!is_new
&& ignored_attribute_bootstrap.is_none()
&& self.dom_host().is_html_element_named(handle, "iframe")
&& (existing.as_ref().is_some_and(|entry| {
entry.same_document_attribute_bootstrap.as_ref()
== Some(&attribute_bootstrap)
}) || Self::child_browsing_context_bootstrap_url(&attribute_bootstrap)
.is_some_and(|url| {
self.child_frame_attribute_navigation_is_same_document(handle, &url)
})))
.then(|| attribute_bootstrap.clone());
let attribute_bootstrap = if ignored_attribute_bootstrap.is_some()
|| same_document_attribute_bootstrap.is_some()
{
existing
.as_ref()
.map_or(ChildBrowsingContextBootstrap::AboutBlank, |entry| {
@@ -581,6 +594,7 @@ impl PageScriptHost {
id: id.filter(|value| !value.is_empty()),
attribute_bootstrap,
ignored_attribute_bootstrap,
same_document_attribute_bootstrap,
pending_attribute_bootstrap_commit,
pending_javascript_initiator_origin,
pending_live_navigation: existing.as_ref().and_then(|entry| {
@@ -144,6 +144,19 @@ impl PageScriptHost {
.is_some_and(|(source, target)| source.has_same_origin(&target))
}
pub(in crate::native_bridge) fn child_frame_attribute_navigation_is_same_document(
&self,
handle: DomHandle,
destination: &Url,
) -> bool {
destination.fragment().is_some()
&& self
.child_browsing_context_current_url(handle)
.is_some_and(|current| {
current[..url::Position::AfterQuery] == destination[..url::Position::AfterQuery]
})
}
pub(in crate::native_bridge) fn child_frame_attribute_navigation_replaces_current_entry(
&self,
handle: DomHandle,
@@ -839,7 +839,7 @@ pub(in crate::native_bridge) fn apply_planned_form_navigation(
&& let Some(location) = window
.and_then(|window| crate::context_bootstrap::window_location_for_holder(scope, window))
{
crate::context_bootstrap::navigate_location_object_for_form_fragment(
crate::context_bootstrap::navigate_location_object_for_element_fragment(
scope,
location,
destination_url.as_str(),
@@ -19,7 +19,7 @@ pub(in crate::native_bridge) fn update_iframe_snapshot_navigation(
set_reflected_attribute(scope, runtime_ptr, handle, "src", value);
let runtime = unsafe { &mut *runtime_ptr };
if !runtime.dom_host().is_html_element_named(handle, "iframe")
|| runtime.child_frame_src_attribute_navigation_is_ignored(handle)
|| runtime.child_frame_src_attribute_navigation_is_handled(handle)
{
return;
}
@@ -4817,3 +4817,171 @@ async fn popup_document_location_tracks_its_active_browsing_context() {
"true"
);
}
#[tokio::test]
async fn iframe_src_fragment_preserves_document_and_initial_history_replacement() {
for mode in ["src", "setAttribute", "setAttributeNS", "attrValue"] {
for initial_document in [true, false] {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
"https://iframe-attribute-fragment.test/page.html",
&loader,
);
vm.exec(
r#"
const frame = document.createElement('iframe');
(document.body || document.documentElement || document).append(frame);
const initialDocument = frame.contentDocument;
"#,
None,
)
.expect("initial iframe should connect");
if !initial_document {
vm.exec(
"frame.contentWindow.location.replace('about:blank?committed');",
None,
)
.expect("non-initial document should navigate");
advance_page_task_executor_until_eval_equals(&mut vm, &loader,
"String(frame.contentDocument !== initialDocument && frame.contentDocument.readyState === 'complete')",
"true", "non-initial document should finish").await;
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 128)
.await
.unwrap();
}
let loader_id = vm.child_browsing_context_frame_tree_snapshot_for_protocol()[0]
.loader_id
.clone();
vm.exec(&format!(r#"
const savedDocument = frame.contentDocument;
const savedWindow = frame.contentWindow;
const beforeLength = history.length;
const beforeHref = savedWindow.location.href;
const fragmentHref = beforeHref + '#fragment';
const events = [];
savedWindow.addEventListener('hashchange', event => events.push('hash:' + event.oldURL + '>' + event.newURL));
savedWindow.addEventListener('unload', () => events.push('unload'));
frame.addEventListener('load', () => events.push('load'));
const setSrc = url => {{
if ('{mode}' === 'setAttribute') frame.setAttribute('src', url);
else if ('{mode}' === 'setAttributeNS') frame.setAttributeNS(null, 'src', url);
else if ('{mode}' === 'attrValue') {{
const attribute = frame.getAttributeNode('src');
if (attribute) attribute.value = url;
else {{
const created = document.createAttribute('src');
created.value = url;
frame.setAttributeNode(created);
}}
}} else frame.src = url;
}};
setSrc(fragmentHref);
"#), None).expect("attribute fragment navigation should start");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(events.some(event => event.startsWith('hash:') || event === 'load'))",
"true",
"attribute navigation must deliver its event",
)
.await;
assert_eq!(
vm.eval(
r#"[
savedDocument === frame.contentDocument,
savedWindow.location.href === fragmentHref,
events.join('|') === 'hash:' + beforeHref + '>' + fragmentHref,
history.length - beforeLength
].join('|')"#
)
.unwrap(),
format!("true|true|true|{}", i32::from(!initial_document)),
"{mode}, initial: {initial_document}"
);
assert_eq!(
vm.child_browsing_context_frame_tree_snapshot_for_protocol()[0].loader_id,
loader_id
);
vm.exec("setSrc(fragmentHref);", None).unwrap();
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 128)
.await
.unwrap();
assert_eq!(
vm.eval("String(savedDocument === frame.contentDocument && events.length === 1)")
.unwrap(),
"true"
);
vm.exec("frame.src = beforeHref;", None).unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(frame.contentDocument !== savedDocument && events.includes('load'))",
"true",
"the next real attribute navigation should commit",
)
.await;
assert_eq!(
vm.eval("history.length - beforeLength").unwrap(),
if initial_document { "0" } else { "2" },
"the initial Document must still be replaced after its fragment updates"
);
}
}
}
#[tokio::test]
async fn canceled_iframe_src_fragment_does_not_queue_document_replacement() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
"https://iframe-canceled-fragment.test/page.html",
&loader,
);
vm.exec(
r#"
const frame = document.createElement('iframe');
(document.body || document.documentElement || document).append(frame);
const initialDocument = frame.contentDocument;
frame.contentWindow.location.replace('about:blank?committed');
"#,
None,
)
.unwrap();
advance_page_task_executor_until_eval_equals(&mut vm, &loader,
"String(frame.contentDocument !== initialDocument && frame.contentDocument.readyState === 'complete')",
"true", "a committed Document should expose navigation events").await;
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 128)
.await
.unwrap();
vm.exec(
r#"
const savedDocument = frame.contentDocument;
const beforeLength = history.length;
let navigations = 0, loads = 0, hashes = 0;
frame.addEventListener('load', () => loads++);
frame.contentWindow.addEventListener('hashchange', () => hashes++);
frame.contentWindow.navigation.addEventListener('navigate', event => {
navigations++;
event.preventDefault();
});
frame.src = 'about:blank?committed#canceled';
"#,
None,
)
.unwrap();
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 128)
.await
.unwrap();
assert_eq!(
vm.eval(
r#"[
savedDocument === frame.contentDocument,
frame.contentWindow.location.href,
history.length === beforeLength, navigations, loads, hashes
].join('|')"#
)
.unwrap(),
"true|about:blank?committed|true|1|0|0"
);
}