0

I have a scenario when user clicks on browser refresh, the page routing has to be changed. I have tried using the below code during mounting/unmounting phase, but no luck.

useEffect(()=>{
  window.addEventListiner("beforeUnload", changeRoute);
  return()=>{
    window.removeEventListiner("beforeUnload", changeRoute);
  }
},[])
const changeRoute = (e) =>{
  e.prevantDefault();
  pros.history.push('/somepage');
}

With this code, I can see the url is changing to '/somepage' and re-navigating to the same page again. It is not moving to '/somepage'. Can anyone advice me please?

user1122
  • 47
  • 1
  • 6
  • 2
    At the point where the URL is changed, the refresh is already in progress. One approach I would try would be: Store a "closed date time" in local storage/cookies (during your `beforeUnload`), then whenever the app is opened, check if that date is within the last e.g. 5 seconds, and automatically redirect at that point. – DBS Jan 28 '22 at 10:33
  • If the user is reloading the page, or closing the tab/window, why are you trying to change the default behavior? Why not instead just redirect to `"/somepage"` when the app mounts? – Drew Reese Jan 28 '22 at 16:37
  • I don't know if it's just a typo in your question, but `pros.history.push` seems like it should be `props.history.push`. Anyway, does something like my [answer here](https://stackoverflow.com/a/68933242/8690857) help? – Drew Reese Feb 02 '22 at 08:47
  • I think DBS has a sound suggestion and approach. Most browsers are making it more difficult to override any "unloading" behavior as a way to prevent nag screens and other undesirable behaviors as it ultimately effects the users of their browser. – Drew Reese Feb 05 '22 at 01:15

0 Answers0