Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent "back button" navigation #452

Open
joecarl opened this issue May 29, 2024 · 5 comments
Open

Prevent "back button" navigation #452

joecarl opened this issue May 29, 2024 · 5 comments
Labels

Comments

@joecarl
Copy link

joecarl commented May 29, 2024

I'm developing an app where I need to prevent "back button" in some cases, (e.g.: when I'm editing a form and I click back button I should receive a confirmation dialog before the navigation occurs).

I tried adding the well known beforeunload event. But it only works when the navigation was not made via pushState/setLocation.
Is it possible to achieve the behavior I need with wouter?

@molefrog
Copy link
Owner

You can try creating a custom hook that wraps default useBrowserLocation and checks for unsaved changes before actual navigate is called. Here, I found the demo that was initially written for V2 but I think it still works:

https://codesandbox.io/s/wouter-demo-interruptible-transition-v3-phrcz4?file=/src/index.js

@joecarl
Copy link
Author

joecarl commented May 30, 2024

Thanks for your reply, but the provided link is not loading :(
Anyway, are you sure that navigation caused by "browser's back button" can be prevented?
I tried to create the custom hook as you suggested but I'm definetely missing some info.

@molefrog
Copy link
Owner

Hmm... I changed the sandbox visibility, could you try again?

@joecarl
Copy link
Author

joecarl commented May 30, 2024

Thankyou.

Ok I tried the sandbox and it doesn't seem to address my issue. I followed these steps:

  1. Go to "About us".
  2. Dialog appears (nice), click confirm.
  3. Go to "Form" again.
  4. Then hit back button. At this point I would expect a confirmation dialog, but navigation occurs without confirmation. This is the issue I'm facing.

@ColonelThirtyTwo
Copy link

Back button won't go through the navigate function that's overwritten in the snippet above.

react-router seems to handle back/forward by immediately undoing the navigation via history.go(delta * -1), but that approach is hard to do with wouter's design where every useLocation call adds another listener to the history popstate event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants