I have an ASP.NET Core 8.0 project using Razor Pages where I’m logging user login and logout times. Currently, I’m facing an issue where if the user closes the browser/tab directly, the logout time isn’t recorded because the logout page isn’t accessed. To address this, I’ve tried implementing a JavaScript beforeunload event listener to prompt the user to confirm logout when closing the tab or browser. Here’s my current approach:
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
</script>
However, this script triggers an alert on any navigation within the page, including button clicks, which is not the desired behavior. I want the alert to only appear when the user attempts to close the tab or browser directly.
Additionally, I attempted to use Ajax to call a logout method when the user confirms they want to leave:
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
// Ajax call to log out the user
$.get("/Logout");
});
</script>
But this approach doesn’t seem to work reliably.
Objective:
I need a solution that triggers the logout mechanism (logs out the user and records the logout time) when the user closes the tab or browser directly, without prompting an alert on every page action. How can I achieve this in an ASP.NET Core Razor Pages application?
I expect that when the user attempts to close the tab or browser directly, they should be prompted with a confirmation dialog (via beforeunload), and upon confirmation, an Ajax request should log out the user by recording the logout time in the database (/LogOut).