I need event that will work on closing page or tab, but also will not trigger on refreshing page. I know for "beforeunload", but that still work on refreshing page.
Here is my code
@HostListener('window:beforeunload', ['$event'])
checkIsUserLogOut() {
if (ConfigurationModel.applicationOptions.autoLogOutWhenWebBrowserClosed) {
localStorage.removeItem('auth_token');
localStorage.removeItem('auth_token_expires_on');
}
}
Found an article for this exact problem (does not want to trigger code on refresh).
It uses a localStorage variable to save the datetime of the last unload event, and if its less than a preset amount of time it considers it a refresh.
the unload event handler:
function unload(event) {
if (window.localStorage) {
// flag the page as being unloading
window.localStorage['myUnloadEventFlag']=new Date().getTime();
}
askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call
}
on page load:
function myLoad(event) {
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)) t0=0;
var t1=new Date().getTime();
var duration=t1-t0;
if (duration<10*1000) {
// less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
} else {
// last unload event was for a tab/window close => do whatever
}
}
}
Hope it helps.