On the web page when the user clicks on the logout button, I have a JavaScript function which clears the user session which is stored on the MongoDB. It works fine.
Also I would like to clear the user session when the user closes the browser. Here is the issue I am facing : when the user clicks on the refresh icon the logout function is getting called. I only want this function to be called when the browser is closed.
Can I prevent this function from calling on the page refresh?
My logic here is to clean up the session when the browser is closed. I am deleting the session which is on MongoDB. Is there a better way to manage the session?
var isRefresh = false;
$(window).keydown(function (event) {
if (event.keyCode == 116) { // User presses F5 to refresh
refresh = true;
}
});
// Calls the logout function when you close the browser thus cleans the session data.
var windowsCloseEventListener = window.attachEvent || window.addEventListener;
var chkForBrowserCloseEvents = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
windowsCloseEventListener(chkForBrowserCloseEvents, function (e) { // For >=IE7, Chrome, Firefox
if (!isRefresh) {
$scope.logout();
}
});
So far as I know, you can't actually test for the browser being closed; you can only test for a window (or tab) being closed. That generally suffices, unless of course a page-refresh happens, since it counts as both closing and re-opening a web page inside a window or tab. What is needed is an event-handler for a click on the browser's page-refresh button, but I'm not sure such exists. Here is something:
How to show the "Are you sure you want to navigate away from this page?" when changes committed?
and also
Handling Browser close event and Page Refresh
One thing I've encountered in trying to find something about a page-refresh event-handler is the notion of using "local storage". You could, as part of the on-before-unload handler, put a small data item, time-stamped, into local storage. Activate a kind of timer on the Server, and wait for that time to expire before erasing the session. When your page is loaded, test local storage for that data item. If it exists and the time-stamp was very recent, you know the page was refreshed and can can do appropriate things based on knowing that --like sending an AJAX message to the Server telling it to not erase the session just yet.
To better manage a session and work around user pressing a browser refresh, you need to
This InActivity monitor can be a good starting point. https://github.com/HackedByChinese/ng-idle/blob/develop/src/angular-idle.js. I have done all the above in my angular project. Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With