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 all the rows. So it's basically a chat client.
I'd like to keep a list of who's online. How can I do this? How can I sense when someone has closed the browser?
Right now I'm pulling the username as
$name = $_COOKIE["name"];
and if this value is empty, I know they left. But once they left, it's too late to know what their username was so I c开发者_StackOverflowan't keep track of who exactly left.
Ideas? I'm fairly new to php, javascript, and html, so keep that in mind :)
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.
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.
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(), interval 40 SECOND)
hope this helps
Use the onbeforeunload
event.
You could possibly attach to the onunload event in javascript. Have a look at http://help.dottoro.com/ljflhicd.php for full details.
Refer these links. Sure this is a light for ur darkness.
Link1: http://www.daniweb.com/forums/thread252828.html
Link2: http://phpeasystep.com/phptu/9.html
精彩评论