From 09f93863d70565bf51990c872135c9aa15ef7569 Mon Sep 17 00:00:00 2001 From: Yuya Tanaka Date: Mon, 7 Oct 2024 22:50:47 +0900 Subject: [PATCH] Fix popstate event is not correctly accepted --- src/hooks/useInterceptPopState.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/hooks/useInterceptPopState.ts b/src/hooks/useInterceptPopState.ts index 8cf1510..8953b10 100644 --- a/src/hooks/useInterceptPopState.ts +++ b/src/hooks/useInterceptPopState.ts @@ -111,8 +111,17 @@ function createHandlePopState( // Wait for all callbacks to be resolved (async () => { + let i = -1; + for (const def of defs) { + i++; + if (!def.enabled({ to, type: "popstate" })) continue; + if (DEBUG) { + console.log( + `useInterceptPopState(): confirmation for listener index ${i}` + ); + } const confirm = await def.callback({ to, type: "popstate" }); // TODO: check cancel while waiting for navigation guard @@ -125,17 +134,21 @@ function createHandlePopState( ); } if (delta !== 0) { + // discard event window.history.go(-delta); } return; } + } - // accept - dispatchedState = nextState; - window.dispatchEvent( - new PopStateEvent("popstate", { state: nextState }) + if (DEBUG) { + console.log( + `useInterceptPopState(): Accept popstate event, ${nextIndex}` ); } + // accept + dispatchedState = nextState; + window.dispatchEvent(new PopStateEvent("popstate", { state: nextState })); })(); // Return false to call stopImmediatePropagation()