In react I tried to redirect user from current page to another page after reload by using onunload & onbeforeunload. but after first reload it shows the url changed and comeback to current page again. and after second reload it goes to redirected page.
These are some code I tried…
Test 001: Just after confirmation / "Leave Page" button clicked, it should redirect. Fact is it goes to the page and redirect 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 the timing issue and I set a timer. Now things goes worse! it doesn’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]);
2
Answers
Try this :
export default MyComponent;
The browser "bounce effect" or "double reload" issue, where the page reloads twice after attempting to redirect the user using the beforeunload event, can be challenging to prevent entirely due to browser security measures. However, you can employ certain techniques to minimize its impact.
One effective approach is to store a flag data to somewhere globally where you can trace that this user reload that page.
This guy solved this problem in a way
I have another solution, which is store a flag in localstorage / sessionStorage and later destroy it while redirection success. Here is the code bellow, you can use it in you own way.
Still you will face "bounce effect" but after that it will redirect you again due to flag match and this time "bounce effect" won’t work.