0

On my Asp.net MVC site, I want to logout user from the site automatically when I close the tab or browser. I mean when I close the site by closing the tab instead of using logout button. Is there any way to handle closing the tab in mvc, javascript or JQuery?

I have already tried using onbeforeunload and onunload, but it doesn't work!

Thank you in advance.

  • 1
    Does this answer your question? [How do I log a user out when they close their browser or tab in ASP.NET MVC?](https://stackoverflow.com/questions/23632725/how-do-i-log-a-user-out-when-they-close-their-browser-or-tab-in-asp-net-mvc) – Amirhossein Shahbazi Aug 16 '21 at 07:02
  • @AmirhosseinShahbazi This doesn't solve my problem – Avinash Sethu M V Aug 16 '21 at 09:26
  • @AmirhosseinShahbazi - I have a field **LoginStatus** in table which is set to 1 when a user is logged in. I want it set to 0 on browser or tab close. – Avinash Sethu M V Aug 16 '21 at 09:32
  • You can try the JavaScript approach from that answer to send an AJAX request to the server, it's the only way to know what's happening in the client. Alternatively, you can register a time stamp for every user interaction, and set that field to 0 if enough time has passed since the last interaction, using a background process. Both ways are not bulletproof. – Tsahi Asher Aug 16 '21 at 12:42
  • @TsahiAsher - Tried to send Ajax request but is not working properly – Avinash Sethu M V Aug 17 '21 at 09:12
  • How does it fail? If the page is unloaded before the AJAX call completes, you should delay the user using the `onbeforeunload` even or something similar until it completes. This is tricky, I admit. Maybe my second suggestion will work better, but it should account for the case of the user leaving the browser open for a while without activity. In that case you should do a complete log-out, except for that database field. – Tsahi Asher Aug 24 '21 at 07:39

0 Answers0