Intercept browser back using App dir
Unanswered
Philippine Crocodile posted this in #help-forum
Philippine CrocodileOP
i have a page with a form; i want to prevent users from going back on their browser if the form is dirty, to avoid losing data (the form is not small)
what's the best way to achieve this using the App dir?
I was able to catch pretty much every event with this hook (using <a/> instead of <Link/> when navigating away)
but the back button is the only event missing
what's the best way to achieve this using the App dir?
I was able to catch pretty much every event with this hook (using <a/> instead of <Link/> when navigating away)
import { useEffect } from "react"
import Router from "next/router"
import { useBeforeUnload } from "react-use"
export const useLeavePageConfirm = (
isConfirm = true,
message = "Are you sure want to leave this page?"
) => {
useBeforeUnload(isConfirm, message)
useEffect(() => {
const handler = () => {
if (isConfirm && !window.confirm(message)) {
throw "Route Canceled"
}
}
Router.events.on("routeChangeStart", handler)
return () => {
Router.events.off("routeChangeStart", handler)
}
}, [isConfirm, message])
}but the back button is the only event missing
4 Replies
@Ray https://github.com/codeBelt/warn-unsaved-changes-leaving-web-page-nextjs/tree/main
oh nm, you are using app dir, this only work in page router
Philippine CrocodileOP
thanks, yep with the app router is trickier...
what I did now is use native anchors to navigate to and from the page that contains the form, so that it triggers the window event, but that's not ideal 🤷â€â™‚ï¸
what I did now is use native anchors to navigate to and from the page that contains the form, so that it triggers the window event, but that's not ideal 🤷â€â™‚ï¸
Sloth bear
Hello, I have a question about something similar. I want to intercept the browser's back button on a specific page. When the user is on that page and clicks the browser's back button, instead of going back to the previous page, they are redirected to another link.
I've tried something like:
useEffect(()=>{
window.onpopstate = function(){
... code;
}
});
But the browser back button click is never trigged on client server mode... How cha I go around that?
I've tried something like:
useEffect(()=>{
window.onpopstate = function(){
... code;
}
});
But the browser back button click is never trigged on client server mode... How cha I go around that?