I have a banking website and I am implementing as case where, when a user tries to refresh browser it should show a warning popup which states that you will be sign out and if user click on that button it should logout that user. I am using react and below is my code. But this gives me only option for Reload and Cancel which is predefined and the alert is not working. I want to add my functionality of logout.
useEffect(() => {
window.onbeforeunload = function () {
alert("This will logout.. ")
return "Leaving this page will reset the wizard";
};
// eslint-disable-next-line react-hooks/exhaustive-deps
},[]);
1 Answer 1
There is no way to prevent a page from reloading using the browser's refresh button or to apply custom logic to it.
Keep in mind that the beforeunload event has limited support according to MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
I’d advice you to focus instead on how user data is managed or saved on your website.
If you're currently using localStorage for example, consider using alternatives to store user session data, such as a context where the user is required to enter their authentication info on the initial mount of the site. This way, the data will be cleared automatically on refresh, and simply showing a beforeunload warning would be enough, since logout functionality shouldn’t rely on the event listener and the logout functionality is implemented somewhere else.
Edit: even for this solution, put in mind beforeunload has a limited availability.