In react, I'm trying to use onunload and onbeforeunload to redirect the user from the current page to another page after reloading. But after the first reload it shows that the url has changed and returns to the current page again. After the second reload, it goes to the redirect page. These are some codes I've tried...
Test 001: After confirming/clicking the "leave page" button, it should redirect. In fact, it goes to that page and redirects to the previous page. >_<<
import { useEffect } from 'react'; import { useHistory } from 'react-router-dom'; const MyComponent = () => { const history = useHistory(); useEffect(() => { const handleBeforeUnload = (event) => { // Prevent the default dialog box from showing event.preventDefault(); // Redirect the user to the desired page history.push('/redirected-page'); }; window.addEventListener('beforeunload', handleBeforeUnload); return () => { window.removeEventListener('beforeunload', handleBeforeUnload); }; }, [history]); // Rest of your component code... return ( // JSX for your component... ); };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>
Test 002: Then I thought it might be a timing issue and I set a timer. Now things get worse! It won't go there.
useEffect(() => { const handleBeforeUnload = (event) => { event.preventDefault(); // Delay the redirection by 100 milliseconds setTimeout(() => { history.push('/Applicant-profile'); }, 100); }; window.addEventListener('beforeunload', handleBeforeUnload); return () => { window.removeEventListener('beforeunload', handleBeforeUnload); }; }, [history]);
Try this:
Export the default MyComponent;
The browser "bounce effect" or "double reload" issue, where a page reloads twice after trying to redirect the user using the beforeunload event, may be difficult to completely prevent due to browser security measures. However, there are certain techniques you can employ to minimize its impact. One effective approach is to store the flag data somewhere globally, where you can track that user reloading the page.
This guy somehow solved this problem
I have another solution which is to store a flag in localstorage/sessionStorage and then destroy it when the redirect is successful. Below is the code, you can use it any way you want.