I want to manage logout event when user click on page leave so when come back on same page it redirect to login page.
On browser tab close i want to perform some session clear function.
Currently in my code issue happen that on page reload also this event triggered and session logout but i don’t need to call this event on page refresh/reload i want only for browser close event handle message prompt with Leave/Cancel when user click on leave then i want to call logout event.
Below code i have perform :
useEffect(() => {
const handleBeforeUnload = (event: any) => {
const customMessage = 'You are attempting to leave the agent screen without logging out. This may result in lost information. Are you sure you want to exit this page?';
event.preventDefault();
event.returnValue = customMessage;
};
const handleUnload = () => {
// Clear data on page close
reduxDispatch(onSelectCampaign(""));
RemoveCookiesData();
clearAllData(reduxDispatch);
};
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('unload', handleUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('unload', handleUnload);
};
}, []);
2
Answers
Here’s an example of how you can modify your code:
Javascript doesn’t have different unload events between reloading a page or closing a tab. What you can do is using the
Session Storage
. This storage will be cleared, when the user closes the tab.Set a key/value pair into the session storage all the time when the events
unload/beforeunload
get triggered.Check this special key/value pair in your
useEffect
hook, when the component gets mounted the next time. In case the key/value pair is still available you know that the user just reloaded the page on the other hand if the key/value pair is empty you can be sure that the user opened your page in a new tab.