fix(navigation): cancel stopped window subtrees

Resolve Window.stop() through the receiver's captured Window binding and
cancel intercepted fragment/reload navigations as well as descendant
frame navigations. Preserve cross-document traversal handling and guard
ancestor stops against reentrant abort listeners. Keep Window identity
valid across document.open() without targeting replacement LocalWindows.

Import the corrected upstream stop-before-commit WPT and cover receiver,
shadow-frame, history, promise, and callback reentrancy behavior.
This commit is contained in:
ldm0
2026-11-24 14:31:23 +08:00
parent 57f48f103e
commit 2bfd23809a
10 changed files with 518 additions and 43 deletions
+1
View File
@@ -172,6 +172,7 @@ wpt_compat_cases! {
wpt_compat_case_history_go_nan_reload_basic => "history-go-nan-reload-basic",
wpt_compat_case_navigation_currententrychange_hash_navigation => "navigation-currententrychange-hash-navigation",
wpt_compat_case_navigation_reload_basic => "navigation-reload-basic",
wpt_compat_case_upstream_navigation_api_precommit_handler_precommithandler_window_stop_before_commit => "upstream-navigation-api-precommit-handler-precommithandler-window-stop-before-commit",
wpt_compat_case_upstream_navigation_api_precommit_handler_precommithandler_push => "upstream-navigation-api-precommit-handler-precommithandler-push",
wpt_compat_case_upstream_navigation_api_precommit_handler_precommithandler_reload => "upstream-navigation-api-precommit-handler-precommithandler-reload",
wpt_compat_case_upstream_navigation_api_precommit_handler_precommithandler_replace => "upstream-navigation-api-precommit-handler-precommithandler-replace",
@@ -480,6 +480,7 @@ async fn precommit_rejections_preserve_promise_and_event_order() {
("top", "navigate", "stop"),
("top", "navigate", "navigate"),
("top", "reload", "reject"),
("top", "reload", "stop"),
("top", "reload", "navigate"),
("top", "location", "reject"),
("top", "location", "stop"),
@@ -500,15 +501,19 @@ async fn precommit_rejections_preserve_promise_and_event_order() {
("child", "navigate", "stop"),
("child", "navigate", "navigate"),
("child", "reload", "reject"),
("child", "reload", "stop"),
("child", "reload", "navigate"),
("child", "download", "reject"),
("child", "download", "stop"),
("child", "download", "navigate"),
("popup", "navigate", "reject"),
("popup", "navigate", "stop"),
("popup", "navigate", "navigate"),
("popup", "reload", "reject"),
("popup", "reload", "stop"),
("popup", "reload", "navigate"),
("popup", "download", "reject"),
("popup", "download", "stop"),
("popup", "download", "navigate"),
("top", "navigate", "primitive"),
("top", "reload", "primitive"),
@@ -623,6 +628,270 @@ async fn precommit_rejections_preserve_promise_and_event_order() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn window_stop_preserves_cancellation_during_reentrant_callbacks() {
for action in [
"window.stop()",
"child.stop()",
"sibling.frameElement.remove()",
"sibling.document.open(); sibling.document.write('<!doctype html><p>replacement</p>'); sibling.document.close()",
] {
let mut page = SameDocumentPage::new().await;
let script = r###"(async()=>{
const tick=()=>new Promise(r=>setTimeout(r,0));
async function frame(w,name,shadow=false){const f=w.document.createElement('iframe');const loaded=new Promise(r=>f.onload=r);f.src='history.html?'+name;let root=w.document.body;if(shadow){const h=w.document.createElement('div');root.appendChild(h);root=h.attachShadow({mode:'closed'});}root.appendChild(f);await loaded;return f.contentWindow;}
const child=await frame(window,'child'),sibling=await frame(window,'sibling'),grand=await frame(child,'grand'),shadow=await frame(window,'shadow',true);
const popup=open('history.html?popup');await new Promise(r=>popup.onload=r);await tick();
const worlds={top:window,child,sibling,grand,shadow,popup};
const events=[],signals={},transitions={},releases={},results={},states={},before={};
for(const [name,w] of Object.entries(worlds)){
before[name]={href:w.location.href,length:w.navigation.entries().length,entry:w.navigation.currentEntry};
w.navigation.addEventListener('navigate',e=>{signals[name]=e.signal;e.signal.addEventListener('abort',()=>events.push('abort:'+name));e.intercept({precommitHandler(){transitions[name]=w.navigation.transition;transitions[name].committed.catch(()=>{});transitions[name].finished.catch(()=>{});return new Promise(r=>releases[name]=r);}});},{once:true});
w.navigation.addEventListener('navigateerror',()=>events.push('error:'+name),{once:true});
results[name]=w.navigation.navigate('?requested='+name);
states[name]='pending';results[name].committed.then(()=>states[name]='fulfilled',e=>states[name]=e.name);results[name].finished.catch(()=>{});
}
signals.grand.addEventListener('abort',()=>{ ACTION; },{once:true});
await tick();
const snap=()=>({states:{...states},aborted:Object.fromEntries(Object.entries(signals).map(([n,s])=>[n,s.aborted])),events:[...events]});
window.stop();
const sync=snap();await Promise.resolve();const micro=snap();await tick();await tick();const stopped=snap();
const retained={};
Object.values(releases).forEach(r=>r());await Promise.allSettled(Object.values(results).map(r=>r.finished));await tick();
const final=snap();popup.close();return{sync,micro,stopped,retained,final};
})()"###.replace("ACTION", action);
let result = page.evaluate(&script).await;
assert_eq!(
result["stopped"]["aborted"],
json!({
"top": true, "child": true, "sibling": true,
"grand": true, "shadow": true, "popup": false,
}),
"{action}: {result}"
);
assert_eq!(
result["final"]["states"],
json!({
"top": "AbortError", "child": "AbortError", "sibling": "AbortError",
"grand": "AbortError", "shadow": "AbortError", "popup": "fulfilled",
}),
"{action}: {result}"
);
let expected_events = if action == "sibling.frameElement.remove()" {
vec![
"abort:grand",
"abort:sibling",
"error:sibling",
"error:grand",
"abort:child",
"error:child",
"abort:shadow",
"error:shadow",
"abort:top",
"error:top",
]
} else {
vec![
"abort:grand",
"error:grand",
"abort:child",
"error:child",
"abort:sibling",
"error:sibling",
"abort:shadow",
"error:shadow",
"abort:top",
"error:top",
]
};
assert_eq!(
result["stopped"]["events"],
json!(expected_events),
"{action}: {result}"
);
assert_eq!(
result["final"]["events"], result["stopped"]["events"],
"cancellation must not repeat after releasing the precommit gates"
);
page.assert_history(&[""], 0).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn window_stop_validates_receivers_and_ignores_discarded_windows() {
for (action, detached) in [
("window.stop.call({})", false),
("window.stop.call(Object.create(window))", false),
("window.stop.call(new Proxy(child, {}))", false),
(
"let p = Proxy.revocable(child, {}); p.revoke(); window.stop.call(p.proxy)",
false,
),
("f.remove(); oldStop.call(child)", true),
("f.remove(); window.stop.call(child)", true),
] {
let mut page = SameDocumentPage::new().await;
let script = r###"(async()=>{
const tick=()=>new Promise(r=>setTimeout(r,0));
const f=document.createElement('iframe');f.src='history.html?old';const loaded=new Promise(r=>f.onload=r);document.body.appendChild(f);await loaded;await tick();
const child=f.contentWindow, oldStop=child.stop, results={}, states={}, signals={}, releases={};
for(const [name,w] of [['top',window],['child',child]]){
w.navigation.addEventListener('navigate',e=>{signals[name]=e.signal;e.intercept({precommitHandler(){return new Promise(r=>releases[name]=r);}});},{once:true});
results[name]=w.navigation.navigate('?requested='+name);results[name].committed.then(()=>states[name]='fulfilled',e=>states[name]=e.name);results[name].finished.catch(()=>{});
}
let outcome;
try{ACTION;outcome='ok';}catch(e){outcome=e.name;}
await tick();const stopped={outcome,states:{...states},topAborted:signals.top.aborted,childAborted:signals.child.aborted};
releases.top();releases.child();await Promise.allSettled(Object.values(results).map(r=>r.finished));return stopped;
})()"###.replace("ACTION", action);
let result = page.evaluate(&script).await;
assert_eq!(
result,
json!({
"outcome": if detached { "ok" } else { "TypeError" },
"states": if detached { json!({"child": "AbortError"}) } else { json!({}) },
"topAborted": false,
"childAborted": detached,
}),
"{action}: {result}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn window_stop_cancels_receiver_and_descendant_precommit_navigations() {
for operation in ["query", "fragment", "reload"] {
for call in [
"top",
"child",
"borrow-child",
"borrow-top",
"popup",
"borrow-popup",
] {
let mut page = SameDocumentPage::new().await;
let script = r###"(async () => {
const operation = OPERATION, call = CALL;
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
async function frame(w, name, shadow = false) {
const element = w.document.createElement('iframe');
const loaded = new Promise(resolve => element.onload = resolve);
element.src = 'history.html?' + name;
let root = w.document.body;
if (shadow) {
const host = w.document.createElement('div');
root.appendChild(host);
root = host.attachShadow({mode: 'closed'});
}
root.appendChild(element);
await loaded;
return element.contentWindow;
}
const child = await frame(window, 'child');
const sibling = await frame(window, 'sibling');
const grandchild = await frame(child, 'grandchild');
const shadow = await frame(window, 'shadow', true);
const popup = open('history.html?popup');
await new Promise(resolve => popup.addEventListener('load', resolve, {once: true}));
await tick();
const windows = {top: window, child, sibling, grandchild, shadow, popup};
const checks = {}, records = {}, events = [];
for (const [name, w] of Object.entries(windows)) {
const nav = w.navigation;
const record = records[name] = {
nav, before: w.location.href, entry: nav.currentEntry,
length: nav.entries().length, states: {}, handlers: 0, errors: 0, successes: 0,
};
const observe = (name, promise) => promise.then(
() => record.states[name] = 'fulfilled',
error => { record.states[name] = error.name; record.reasons.push(error); },
);
record.reasons = [];
nav.addEventListener('navigateerror', event => {
record.errors++; record.reasons.push(event.error); events.push('error:' + name);
});
nav.addEventListener('navigatesuccess', () => record.successes++);
nav.addEventListener('navigate', event => {
record.signal = event.signal;
event.signal.addEventListener('abort', () => events.push('abort:' + name));
event.intercept({
precommitHandler() {
record.transition = nav.transition;
record.observed = [
observe('transition committed', nav.transition.committed),
observe('transition finished', nav.transition.finished),
];
return new Promise(resolve => record.release = resolve);
},
handler() { record.handlers++; },
});
}, {once: true});
const result = operation === 'reload' ? nav.reload()
: nav.navigate(operation === 'fragment' ? '#requested' : '?requested');
record.observed.push(observe('method committed', result.committed), observe('method finished', result.finished));
// Public frame properties must not determine the native cancellation scope.
Object.defineProperty(w, 'frames', {configurable: true, value: {get length() {throw new Error('frames accessed');}}});
}
await tick();
const stopped = call.includes('popup') ? ['popup']
: call.includes('child') ? ['child', 'grandchild']
: ['top', 'child', 'sibling', 'grandchild', 'shadow'];
const stop = () => {
if (call === 'top') window.stop();
else if (call === 'child') child.stop();
else if (call === 'borrow-child') window.stop.call(child);
else if (call === 'borrow-top') child.stop.call(window);
else if (call === 'popup') popup.stop();
else child.stop.call(popup);
};
stop(); stop();
for (const [name, record] of Object.entries(records)) {
const canceled = stopped.includes(name), w = windows[name];
checks[name + ' synchronous abort'] = record.signal.aborted === canceled;
checks[name + ' synchronous transition'] = canceled ? record.nav.transition === null : record.nav.transition === record.transition;
checks[name + ' retained entry'] = w.location.href === record.before && w.document.URL === record.before
&& record.nav.currentEntry === record.entry && record.nav.entries().length === record.length;
}
await tick();
for (const record of Object.values(records)) record.release();
checks.settled = await Promise.race([
Promise.all(Object.values(records).flatMap(record => record.observed)).then(() => true),
new Promise(resolve => setTimeout(() => resolve(false), 900)),
]);
await tick();
for (const [name, record] of Object.entries(records)) {
const canceled = stopped.includes(name), w = windows[name];
checks[name + ' promise states'] = Object.keys(record.states).length === 4
&& Object.values(record.states).every(value => value === (canceled ? 'AbortError' : 'fulfilled'));
checks[name + ' events'] = record.errors === (canceled ? 1 : 0) && record.successes === (canceled ? 0 : 1);
checks[name + ' handler'] = record.handlers === (canceled ? 0 : 1);
checks[name + ' transition cleared'] = record.nav.transition === null;
checks[name + ' error identity'] = !canceled || record.reasons.length === 5
&& record.reasons.every(error => error === record.signal.reason && error instanceof w.DOMException);
checks[name + ' stopped history'] = !canceled || w.location.href === record.before
&& w.document.URL === record.before && record.nav.currentEntry === record.entry && record.nav.entries().length === record.length;
}
popup.close();
return {checks, events, states: Object.fromEntries(Object.entries(records).map(([name, record]) => [name, record.states]))};
})()"###
.replace("OPERATION", &json!(operation).to_string())
.replace("CALL", &json!(call).to_string());
let result = page.evaluate(&script).await;
assert!(
result["checks"]
.as_object()
.unwrap()
.values()
.all(|value| value == true),
"{operation}/{call}: {result}"
);
if matches!(call, "top" | "borrow-top") {
page.assert_history(&[""], 0).await;
}
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn asynchronous_precommit_controllers_apply_final_redirects() {
for (owner, operation, mode) in [
@@ -42,9 +42,8 @@ pub(super) use accessors::{
};
pub(super) use navigation::{
cancel_active_intercepted_same_document_navigation,
cancel_pending_precommit_same_document_navigation,
cancel_pending_precommit_same_document_navigation_for_window_stop,
commit_navigation_navigate_same_document, navigation_entries_callback,
navigation_navigate_callback, navigation_update_current_entry_callback,
queue_pending_precommit_same_document_navigation, settle_intercepted_same_document_navigation,
cancel_pending_precommit_same_document_navigation, commit_navigation_navigate_same_document,
navigation_entries_callback, navigation_navigate_callback,
navigation_update_current_entry_callback, queue_pending_precommit_same_document_navigation,
settle_intercepted_same_document_navigation,
};
@@ -977,33 +977,6 @@ pub(in crate::context_bootstrap) fn cancel_pending_precommit_same_document_navig
);
}
pub(in crate::context_bootstrap) fn cancel_pending_precommit_same_document_navigation_for_window_stop<
's,
>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
) -> bool {
let Some(data) = navigation_pending_precommit_commit(scope, navigation) else {
return false;
};
if !precommit_commit_active(scope, data) {
return false;
}
let Some(data) = pending_precommit_commit_data(scope, data.into()) else {
return false;
};
let current = url::Url::parse(&data.current_href).ok();
let target = url::Url::parse(&data.effective_href).ok();
if target
.as_ref()
.is_some_and(|target| is_same_document_fragment_navigation(current.as_ref(), target))
{
return false;
}
cancel_pending_precommit_same_document_navigation(scope, navigation);
true
}
fn pending_precommit_commit_is_active<'s>(
scope: &mut v8::PinScope<'s, '_>,
data: v8::Local<'s, v8::Value>,
@@ -2,16 +2,172 @@ use super::{
history_runtime::cancel_pending_precommit_history_traversal,
navigation_callbacks::{
cancel_active_intercepted_same_document_navigation,
cancel_pending_precommit_same_document_navigation_for_window_stop,
cancel_pending_precommit_same_document_navigation,
},
navigation_events::cancel_active_navigation_event,
navigation_result::{
cancel_active_cross_document_navigation,
cancel_pending_same_document_navigation_finishes_including_reentrant,
},
navigation_window::{runtime_window_dispatch_scope, window_navigation_for_holder},
navigation_window::{
navigation_unload_event_active, runtime_window_dispatch_scope, window_navigation_for_holder,
},
};
use crate::util::context_host_ptr_from_global_bridge;
use crate::native_bridge::{
OwnerDispatchScope, PageScriptHost, WindowDocumentTaskTarget, WindowExecutionContextBinding,
};
use crate::util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value};
const WINDOW_STOP_ACTIVE_SLOT: &str = "__lmWindowStopActive";
struct WindowNavigationStop {
target: WindowDocumentTaskTarget,
binding: Option<WindowExecutionContextBinding>,
window: Option<v8::Global<v8::Object>>,
children: Vec<Self>,
}
impl WindowNavigationStop {
fn capture_children(
scope: &mut v8::PinScope<'_, '_>,
host: &PageScriptHost,
document: crate::document_runtime::DomHandle,
seen: &mut std::collections::HashSet<crate::document_runtime::DomHandle>,
) -> Vec<Self> {
if !seen.insert(document) {
return Vec::new();
}
host.child_browsing_context_direct_frame_handles_for_document(document)
.into_iter()
.filter_map(|handle| {
let dispatch_scope = OwnerDispatchScope::Child(handle);
let target =
host.current_window_document_task_target_for_dispatch_scope(dispatch_scope)?;
let binding = host
.current_window_execution_context_owner(dispatch_scope)
.and_then(|owner| {
host.clone_window_execution_context_binding(scope, owner, dispatch_scope)
});
let window = binding.as_ref().map(|binding| {
let context = binding.context(scope);
let window = context.global(scope);
v8::Global::new(scope, window)
});
let children = host
.child_browsing_context_document_handle(handle)
.map(|document| Self::capture_children(scope, host, document, seen))
.unwrap_or_default();
Some(Self {
target,
binding,
window,
children,
})
})
.collect()
}
fn stop(&self, scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost) {
let (Some(binding), Some(window)) = (&self.binding, &self.window) else {
// A pending child load need not have materialized a Window realm.
// In that case only its captured Document generation may be stopped.
if unsafe { &*host_ptr }.current_window_document_task_target_for_dispatch_scope(
self.target.dispatch_scope(),
) == Some(self.target)
&& let OwnerDispatchScope::Child(handle) = self.target.dispatch_scope()
{
unsafe { &mut *host_ptr }.cancel_pending_child_browsing_context_navigation(handle);
}
return;
};
binding.with_current_scope(scope, host_ptr, |scope, _| {
let window = v8::Local::new(scope, window);
if navigation_unload_event_active(scope, window)
|| get_private_value(scope, window, WINDOW_STOP_ACTIVE_SLOT)
.is_some_and(|value| value.is_true())
{
return;
}
// Keep ancestors guarded while stopping children: an abort listener
// may synchronously call stop() on this Window again.
set_private_value(
scope,
window,
WINDOW_STOP_ACTIVE_SLOT,
v8::Boolean::new(scope, true).into(),
);
for child in &self.children {
child.stop(scope, host_ptr);
}
// document.open() can replace Document task ownership without
// replacing this Window. A genuinely retired LocalWindow must not
// cancel a new Window installed behind the same frame handle.
if binding.is_current(unsafe { &*host_ptr }) {
stop_navigation_for_window(scope, window);
}
set_private_value(
scope,
window,
WINDOW_STOP_ACTIVE_SLOT,
v8::Boolean::new(scope, false).into(),
);
});
}
}
pub(super) fn stop_navigation_for_window_and_descendants<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
binding: WindowExecutionContextBinding,
) {
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
return;
};
let host = unsafe { &*host_ptr };
let dispatch_scope = binding.dispatch_scope();
let Some(target) = host.current_window_document_task_target_for_dispatch_scope(dispatch_scope)
else {
return;
};
let document = match dispatch_scope {
OwnerDispatchScope::Top => Some(host.document_handle()),
OwnerDispatchScope::Child(handle) => host.child_browsing_context_document_handle(handle),
OwnerDispatchScope::LightweightPopup(id) => host.lightweight_popup_document_handle(id),
};
// Snapshot native children before any author callback. Shadow-tree frames
// participate even though they are absent from the public Window.frames.
let children = document
.map(|document| {
WindowNavigationStop::capture_children(
scope,
host,
document,
&mut std::collections::HashSet::new(),
)
})
.unwrap_or_default();
let stop = WindowNavigationStop {
target,
binding: Some(binding),
window: Some(v8::Global::new(scope, window)),
children,
};
stop.stop(scope, host_ptr);
}
fn stop_navigation_for_window<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
) {
if navigation_unload_event_active(scope, window) {
return;
}
inform_about_canceled_navigation_for_window(
scope,
window,
NavigationCancellationReason::WindowStop,
);
}
pub(crate) enum NavigationCancellationReason {
WindowStop,
@@ -34,7 +190,7 @@ pub(crate) fn inform_about_canceled_navigation_for_window<'s>(
if matches!(reason, NavigationCancellationReason::WindowStop) {
cancel_pending_precommit_history_traversal(scope, navigation);
}
cancel_pending_precommit_same_document_navigation_for_window_stop(scope, navigation);
cancel_pending_precommit_same_document_navigation(scope, navigation);
cancel_pending_same_document_navigation_finishes_including_reentrant(scope, navigation);
clear_pending_cross_document_navigation_for_window(
scope,
@@ -1,6 +1,6 @@
use super::super::{
location_navigation::{LocationNavigationKind, navigate_location_object_with_source_element},
navigation_cancellation::inform_about_canceled_navigation_for_window,
navigation_cancellation::stop_navigation_for_window_and_descendants,
};
use crate::{
context_bootstrap::{CHILD_BROWSING_CONTEXT_HANDLE_SLOT, is_window_receiver},
@@ -136,14 +136,18 @@ pub(crate) fn window_stop_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
if super::super::navigation_window::navigation_unload_event_active(scope, args.this()) {
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
return;
}
inform_about_canceled_navigation_for_window(
};
let receiver = crate::native_bridge::WindowOperationReceiver::capture_after_access_check(
scope,
args.this(),
super::super::NavigationCancellationReason::WindowStop,
unsafe { &*host_ptr },
);
let Some(binding) = receiver.resolve_live_binding(unsafe { &*host_ptr }) else {
return;
};
stop_navigation_for_window_and_descendants(scope, args.this(), binding);
}
pub(in crate::context_bootstrap) fn window_confirm_callback<'s>(
@@ -90,7 +90,7 @@ struct WindowEarlyTemplateMethodsDeclaration {
#[webapi(method, length = 0, callback = window_noop_callback)]
clear_immediate: (),
#[webapi(method, length = 0, callback = window_stop_callback)]
#[webapi(method, length = 0, callback = window_stop_callback, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)]
stop: (),
#[webapi(method, length = 0, callback = window_noop_callback)]
@@ -108,7 +108,7 @@ impl PageScriptHost {
.collect()
}
fn child_browsing_context_direct_frame_handles_for_document(
pub(crate) fn child_browsing_context_direct_frame_handles_for_document(
&self,
document: DomHandle,
) -> Vec<DomHandle> {
@@ -22230,6 +22230,23 @@ tags = ["navigation-api", "ordering-and-transition", "navigation", "precommit-ha
notes = "Unmodified upstream test for precommit rejection and transition/Promise ordering, including this explicit query variant."
query = "currententrychange"
[[test]]
id = "upstream-navigation-api-precommit-handler-precommithandler-window-stop-before-commit"
upstream = "web-platform-tests/navigation-api/precommit-handler/precommitHandler-window-stop-before-commit.html"
upstream_commit = "86f7d9f9f3656576f8c32aed865efda91e531eae"
local_path = "upstream/navigation-api/precommit-handler/precommitHandler-window-stop-before-commit.html"
type = "testharness"
global = "window"
status = "pass"
wait_until = "load"
timeout_ms = 5000
suite = "broad"
source = "upstream-wpt"
source_path = "navigation-api/precommit-handler/precommitHandler-window-stop-before-commit.html"
source_commit = "86f7d9f9f3656576f8c32aed865efda91e531eae"
tags = ["navigation-api", "precommit-handler", "navigation", "window-stop"]
notes = "Unmodified upstream test including the June 2026 correction requiring Window.stop() to cancel intercepted fragment navigations."
[[test]]
id = "testharness-dom-exception-assertions"
upstream = "local WPT harness DOMException assertion overload and realm canary"
@@ -0,0 +1,56 @@
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../navigation-methods/return-value/resources/helpers.js"></script>
<body>
<script>
promise_test(async t => {
// Wait for after the load event because window.stop() hangs the test harness
// if called before the load event.
await new Promise(resolve => window.onload = () => t.step_timeout(resolve, 0));
}, "Setup");
promise_test(async t => {
navigation.onnavigate = e => {
e.intercept({ precommitHandler: async () => {} });
};
navigation.onnavigatesuccess = t.unreached_func("navigatesuccess must not fire");
let navigateerror_called = false;
navigation.onnavigateerror = t.step_func(() => {
navigateerror_called = true;
assert_equals(location.hash, "");
});
let promises = navigation.navigate("?ShouldNotCommit");
assert_equals(location.hash, "");
window.stop();
await assertBothRejectDOM(t, promises, "AbortError");
assert_equals(location.hash, "");
assert_true(navigateerror_called);
}, " precommitHandler with window.stop() before navigation commit");
promise_test(async t => {
navigation.onnavigate = e => {
e.intercept({ precommitHandler: async () => {} });
};
navigation.onnavigateerror = t.unreached_func("onnavigateerror must not fire");
navigation.onnavigatesuccess = t.unreached_func("onnavigatesuccess must not fire");
navigation.onnavigateerror = t.step_func(() => {
navigateerror_called = true;
});
let promises = navigation.navigate("#ShouldCommit");
assert_equals(location.hash, "");
window.stop();
await assertBothRejectDOM(t, promises, "AbortError");
assert_equals(location.hash, "");
assert_true(navigateerror_called);
}, " precommitHandler with window.stop() before fragment navigation commit");
</script>
</body>