Click here to Skip to main content
15,881,745 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In my page I want to show an alert when user tries to close/ reload or go back.
I have two useEffects one for handling reloading and another for when user clicks on browser back button.

My problem is when user reloads that page, an unnecessary history.pushState will be added to history. so when user click on browser back button, two alerts show up instead of one alert. the number of alert increases as the number of reloading the page increases.

What should I do?

Here is my code:

Alert when user press browser go back button:
```
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!terminate) {
if (
window.confirm(
'Are you sure you want to go back?'
)
) {
setTerminate(true);
window.history.back();
} else {
window.history.replaceState(null, null, window.location.pathname);
setTerminate(false);
}
}
};

useEffect(() => {
window.history.pushState(null, null, window.location.pathname);

window.addEventListener('popstate', onBackButtonEvent);
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
};

}, []);
```

Alert when user tries to reload/ close the page:
```

useEffect(() => {
const unloadCallback = (event) => {
event.preventDefault();
event.returnValue = '';
return '';
};
window.addEventListener('beforeunload', unloadCallback);
return () => window.removeEventListener('beforeunload', unloadCallback);
}, []);
```

What I have tried:

this line only to trigger the popState listener. If i remove that line, alert on back button won't work. I actually copied that code from stackoverflow:
```
window.history.pushState(null, null, window.location.pathname);
```
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900