Logout website when close browser

Woon Choon 1 Reputation point
2022-01-12T14:39:14.843+00:00

Hi All,

When user logout from website, system will able to update the datetime in database.

However, when user directly close the browser, how can we handle the updating in our database in c# ?

Sometime, user will open multiple tab, how can we handle if user close one tab will not update in our database ?

I am really appreciate for your help.

Developer technologies | ASP.NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2022-01-13T05:33:16.197+00:00

    Hi @Woon Choon ,
    I think you can try SessionStorage. SessionStorage is not cleared when the page reloads but closes. So basically you can set a key/value pair on page load, but before that you check if the key/value pair exists. If it is, it means the page has reloaded, if not, it means the user opened the page for the first time or opened the page in a new tab.
    https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

    if (sessionStorage.getItem('reloaded') != null) {  
        console.log('page was reloaded');  
    } else {  
        console.log('page was not reloaded');  
    }  
    sessionStorage.setItem('reloaded', 'yes');  
    

    This way you can doStuff() with the onunload event (user leaves the page), and otherStuff() if the key/value pair is set (user reloaded the page).
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2022-01-12T15:42:33.873+00:00

    This is usually a fools errand. There is no reliable way to detect closing the browser.

    Typically you write JavaScript to detect before page unload (navigation) and check the mouse location to see if outside the window. This fails if the keyboard was used,

    A more modern approach is to use a service worker that receives heartbeat pings from live pages. If heartbeats are not received you know all the pages are closed. The service worker would use a timer, and check is any heartbeats were received during the last interval.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.