In Next.js, to detect when users leave a page, you can use the browser's beforeunload event. This event is fired when the window, tab, or browser is about to unload the current document.
First, you need to add an event listener to your Next.js component, typically within the useEffect hook to ensure the code executes when the component loads. Here's a simple example:
jsximport { useEffect } from 'react'; function MyComponent() { useEffect(() => { const handleBeforeUnload = (event) => { event.preventDefault(); // Perform cleanup operations or final save actions here // Set `returnValue` for compatibility with older browsers event.returnValue = ''; }; // Add the event listener window.addEventListener('beforeunload', handleBeforeUnload); // Remove the event listener when the component unmounts return () => { window.removeEventListener('beforeunload', handleBeforeUnload); }; }, []); return ( <div> <h1>Welcome to my page!</h1> </div> ); } export default MyComponent;
In the above code, the handleBeforeUnload function is called when the user attempts to leave the page. You can perform actions within this function, such as displaying a confirmation dialog to prompt the user to confirm if they really want to leave the page.
Note that modern browsers have restrictions on popups within the beforeunload event to prevent abuse and ensure user convenience. Therefore, if you attempt to use alert() or confirm() popups within this event, they may not work as expected.
Additionally, this method is primarily used to detect when users close tabs or the browser. If the user navigates away by clicking a link, you may need to handle it differently, such as detecting during route changes.
In Next.js, you can also leverage its routing capabilities (e.g., next/router) to detect route changes and further control when users leave the page. For example:
jsximport { useEffect } from 'react'; import { useRouter } from 'next/router'; function MyComponent() { const router = useRouter(); useEffect(() => { const handleRouteChange = (url) => { console.log('App is changing to:', url); }; router.events.on('routeChangeStart', handleRouteChange); return () => { router.events.off('routeChangeStart', handleRouteChange); }; }, [router]); return ( <div> <h1>Welcome to my page!</h1> </div> ); } export default MyComponent;
In this code, we listen for the start of route changes, which helps detect when users navigate away from the current page using Next.js's Link component or programmatic navigation.