Skip to content

Conversation

@sohamingle
Copy link

What?

Added support for handling browser back/forward navigation in the LeaveWithoutSaving component.

Why?

To improve user experience by preventing accidental navigation away from the page without confirmation when using the browser's back and forward buttons.

How?

Implemented a popstate event listener that prompts the user for confirmation when navigating away, and adjusted the route handling logic accordingly.

Additionally, ensured that the hasAccepted state is reset when the modal is closed or canceled.

Fixes #14957

Video Demo

Before

Arc.2026-01-02.17-31-07.mp4

After

Arc.2026-01-02.17-27-15.mp4

…andling

### What?

Added support for handling browser back/forward navigation in the LeaveWithoutSaving component.

### Why?

To improve user experience by preventing accidental navigation away from the page without confirmation when using the browser's back and forward buttons.

### How?

Implemented a popstate event listener that prompts the user for confirmation when navigating away, and adjusted the route handling logic accordingly.

Additionally, ensured that the hasAccepted state is reset when the modal is closed or canceled.
@rilrom
Copy link
Contributor

rilrom commented Jan 2, 2026

I attempted to implement this last week and ran into an issue with an extra history stack being inserted after confirming the back navigation. This leads to strange behaviour when the user clicks the browser forward button twice. This behaviour is also occurring in this PR.

Screen.Recording.2026-01-02.at.10.50.06.pm.mov

@sohamingle
Copy link
Author

Yes — this is an inherent side-effect of the sentinel history pattern used to intercept browser back/forward navigation.

Because popstate fires after the browser has already moved in the history stack, there’s no way to truly cancel the navigation. The only reliable approach is to insert a single sentinel history entry and bounce the user back while prevent === true. As a result, once the user explicitly accepts leaving, the history stack contains one additional entry, which can make the Forward button appear usable.

I did explore alternatives (such as replaceState-only or attempting to cancel popstate), but those approaches cannot reliably block browser navigation due to platform limitations.

To ensure this doesn’t lead to inconsistent routing or confirmation loops, the implementation resets the hasAccepted state once navigation completes. This allows the user to proceed normally (including using the Forward button) without breaking navigation. They just have to click it twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Leave without saving warning missing when using browser navigation

2 participants