I would like to detect when the user leaves the page. I count 3 ways of leaving a page:
router.back
, router.push
, etc...beforeunload
event is fired)I know this kind of issue has already been opened here or here, but they had been magically closed (using some duplicate
trick) without providing any solution.
Being able to detect when a page is leaved is very helpful for, for example, alerting the user some changes have not been saved yet.
I would like something like:
router.beforeLeavingPage(() => {
// my callback
})
+1 :+1: for this feature.
Have you seen the docs for Router events ?. It may do the trick.
Yes, I seen it. But it doesn't. There is no way to cancel a route.
Any updates about this feature request?
I want to prevent go to back when they click browser back button or mouse back button too.
Needed this feature just now.
I think this functionality is essential for any website with forms or editable content to prevent data loss.
React Router v6 has very convenient hooks for showing a window.confirm
dialog with a given message when the user tries to navigate away from the current page.
See usePrompt(message: string, when = true)
and useBlocker(blocker: Blocker, when = true)
.
How can such functionality be realized within Next.js?
I would have expected a very similar API in Next.js. I would contribute, but I'm not familiar with Next.js routing internals (React Router leverages React Context API).
I would certainly like this feature as well
A much needed feature 馃挴
This is becoming a growing issue, please vercel hear our cry.
but Have anyone tried this tool
useBeforeunload Hook (recommended)
//import { useBeforeunload } from 'react-beforeunload';
I expect it to do the work since it's built on react and I didn't seen any reliance on react-router
in a functional component
useEffect(() => {
return () => {
// do something
};
}, []);
Most helpful comment
+1 :+1: for this feature.