How to know when user closes browser? Chat application

大城市里の小女人 提交于 2019-11-29 12:18:26

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!