Execute method on server when closing browser

3

I need the user to close the browser or the page tab, update the Logged status that is in the database (for user access control).

To do this use the following

Method JavaScript :

window.onbeforeunload = function (event) {
    PageMethods.LogOut();
}

And the following WebMethod :

[System.Web.Services.WebMethod]
public static void LogOut()
{
     //Atualiza status do usuário
}

The problem is that this method is called at all times, when I change pages, when I refresh the page ( F5 ), how do I solve this?

    
asked by anonymous 04.09.2015 / 16:50

2 answers

1

I know in a way to do what you want, but it consumes the application heavier.

The concept is basically the following:

The logged-in user has a javascript script running, setInterval, responding "call" to the server from time to time.

Every 4 seconds, for example, a record is inserted into the user_activity table with the user ID and a current datetime / timestamp. * Before the query, you can delete the previously inserted records, after all what matters is the most recent insert of the user.

The method that checks whether the user is online or does not search the user_activity table the last time the user replied "present" and checks the same query with a DATE_DIFF if the last time is more than 4 seconds in relation to the current date, for example.

NOTE: The time may vary according to your needs.

If necessary, I can post the code.

I hope I have helped.

    
06.09.2015 / 01:49
1

HTTP 1.4 protocol is by definition does not await connection status from client to server, in summary there is no way secure to ensure that a user actually disconnected from your server. But there are techniques that can help you with this task.

As our friend Renan quoted, perhaps the best known and easiest would be the long polling where the client queries the server from time to time and you specify a time between requests limit to consider it disconnected.

You can also mix this technique with the use of websockets or SSE.

This problem will be resolved with the HTTP2 protocol.

    
23.12.2015 / 04:14