79761704

Date: 2025-09-11 09:13:24
Score: 0.5
Natty:
Report link

This is one of those browser-safety limitations:
You cannot prevent or replace the native beforeunload confirmation popup with your own UI.

Why?

That’s why setting e.preventDefault() or e.returnValue just shows the default browser popup—you can’t override it with a React modal.


What you can do instead

If your goal is to warn users about unsaved form changes and show a custom modal, you’ll need to intercept navigation inside your app, not the hard reload:

  1. Intercept in-app navigation (Next.js Router):

    import { useRouter } from "next/router";
    import { useEffect } from "react";
    
    export default function MyForm() {
      const router = useRouter();
      const isDirty = true; // track whether form has unsaved changes
    
      useEffect(() => {
        const handleRouteChangeStart = (url: string) => {
          if (isDirty && !confirm("You have unsaved changes. Leave anyway?")) {
            router.events.emit("routeChangeError");
            // throw to cancel navigation
            throw "Route change aborted.";
          }
        };
    
        router.events.on("routeChangeStart", handleRouteChangeStart);
        return () => {
          router.events.off("routeChangeStart", handleRouteChangeStart);
        };
      }, [isDirty]);
    
      return <form>…</form>;
    }
    
    

    Here you can replace confirm with your own React modal state.

  2. For full page reload (F5, Ctrl+R, closing tab):

    • You’re stuck with the native confirmation dialog.

    • No way to cancel reload and show your React modal—browsers block this for security reasons.


Bottom line:

Reasons:
  • Blacklisted phrase (0.5): Why?
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: 63 - Vikas Kumar 4rd Sem.