I have a little website using different routes and components (made with React and React Router). I am trying to prevent the user from refreshing in a specific form page, the problem: The Listener prevents the user from refreshing anywhere. But I want that listener only to trigger on that specific page. So how can I do that?
window.addEventListener('beforeunload', function (e) {
return "data will get lost"
});
^ This is the snippet I used in one component, that is not displayed permanently, but only on a specific route.
CodePudding user response:
This should be achievable by inserting this snippet inside the desired page component, as it will load it when the page component gets rendered.
However, I will quote @Nick_Craver answer in this question:
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
Instead, you should think of other ways of persisting data, instead of just preventing the refresh.
CodePudding user response:
You should use this useEffect
hook inside of your component, of which you want to prevent refreshing the page
Insert this code:
const preventRefresh = (e) => {
return "data will get lost"
});
useEffect(() => {
window.addEventListener('beforeunload', preventRefresh);
return () => {
window.removeEventListener('beforeunload', preventRefresh);
}
}, [])