Skip to content Skip to sidebar Skip to footer

How To Know When User Closes Browser? Chat Application

I have a simple chat client set up that allows users to login with a username and stores the messages they write in an sql database. Every 3 seconds, the database simply prints of

Solution 1:

It is hard to send a last request to the server when someone closes the window, since Browsers usually don't wait for JS execution to finish when the user wants the window closed (as is the case with onbeforeunload).

Whenever I am confronted with a situation like this, I tend to use onbeforeunload to send a final request (which happens fast and usually finishes before browser window is closed), but also implement a timeout feature. The timeout feature would work as follows:

Everytime the user sends something to the server, the server recognizes this as 'still there'. At the same time, the client sets a timer of, say, 45 seconds. If the user does not type anything for 45 seconds, the client sends a 'still alive' signal on its own to stay connected.

Now, the server should execute a removeInactive() routine every 60 seconds (allow 15 seconds slow-connection margin, hence the 45/60 seconds) which removes any users who haven't sent a 'still alive' signal in the last 60 seconds.

This system worked fine for me so far, you could try it out for yourself.

Solution 2:

Assuming your using AJAX to pull in the chat messages every X seconds, update your table of users at the time with the current timestamp for that user. Then anyone who has a timestamp say older than 10 seconds, you will know they have left the page.

Solution 3:

put online users in a table that will have a field named like 'lastSeen' update this field every few seconds with ajax call..

ajax call be made someting like this :

window.setInterval(function() {
    $.ajax({      
      url: _URL_ENGINE + "/updateLastSeen/?userid=" + userID,
      success: function(data) {

      }
    }); 
}, 2000); // 2000 means 2 seconds

now to query the list of online players u can query them like

select*from players WHERE lastSeen > DATE_SUB(NOW(), interval40SECOND) 

hope this helps

Solution 4:

Use the onbeforeunload event.

Solution 5:

You could possibly attach to the onunload event in javascript. Have a look at http://help.dottoro.com/ljflhicd.php for full details.

Post a Comment for "How To Know When User Closes Browser? Chat Application"