Stumbled upon a helpful article addressing this specific issue of not triggering code on page refresh.
The solution involves utilizing a localStorage
variable to store the timestamp of the last unload
event, determining if it's within a certain timeframe to classify it as a refresh.
The unload
event handler is as follows:
function unload(event) {
if (window.localStorage) {
// Marking the page as unloading
window.localStorage['myUnloadEventFlag'] = new Date().getTime();
}
askServerToDisconnectUserInAFewSeconds(); // Synchronous AJAX call
}
Upon 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 (cancel disconnection request)
askServerToCancelDisconnectionRequest(); // Asynchronous AJAX call
} else {
// Last unload event was for tab/window close => proceed with necessary actions
}
}
}
Hope this method proves useful in handling your scenario.