I am currently developing an MVC5/ JQuery/ Bootstrap/ EF6 internet-facing website for a client. Due to the extremely high sensitivity of the data contained by the application, the client has asked if it is possible for the user session to be terminated when one of the browser tabs containing the application have been closed. It is imperative that The user must not be able to open a new tab and continue from where they left off - they must login again.
I have searched StackOverflow and found references to scripts using window.beforeunload and window.performance.navigation, and I ended up with the following derivative work, which fails when clicking the back button:
var endsession = {
ValidNavigation: false,
EndSession: function () {
var url = '/account/AjaxLogoff';
if (GetIEVersion() > 0) {
$.ajax({
type: "POST",
url: url,
async: false,
error: function (xhr, status, error) {
utilities.HandleAjaxErrors(xhr, status, error);
}
});
}
else {
navigator.sendBeacon(url, '');
}
}
};
$(document).ready(function () {
"use strict";
$(window).on("beforeunload", function () {
if (endsession.ValidNavigation)
return;
var navType = performance.navigation.type;
console.log("NavType: " + navType);
if (navType !== window.performance.navigation.TYPE_RELOAD &&
navType !== window.performance.navigation.TYPE_BACK_FORWARD) {
endsession.EndSession();
}
});
// Attach the event keydown to exclude the F5 refresh
$(document).bind('keydown', function (e) {
if (e.keyCode == 116) {
endsession.ValidNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function () {
endsession.ValidNavigation = true;
});
$("form").bind("submit", function () {
endsession.ValidNavigation = true;
});
});
This script fails when using the browser back button. (performance.navigation.type is set to 0 when back is clicked in Chrome, as well as when you input the URL directly)
I have also looked at onpopstate handler - didn't help.
Does anyone know what else I could try? Recommendations for 3rd party libraries are welcome.
Additional constraint: the code must work with IE11 as well as Chrome & Firefox. IE11 is not my choice.
Thanks in advance.