0

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
},[]);
asked Apr 10, 2025 at 7:34

1 Answer 1

0

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.

answered Apr 10, 2025 at 10:31
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.