How to know when user closes browser? Chat application

前端 未结 6 1881
离开以前
离开以前 2020-12-20 02:15

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 pri

相关标签:
6条回答
  • 2020-12-20 02:53

    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

    0 讨论(0)
  • 2020-12-20 03:01

    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.

    0 讨论(0)
  • 2020-12-20 03:02

    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

    0 讨论(0)
  • 2020-12-20 03:04

    Use the onbeforeunload event.

    0 讨论(0)
  • 2020-12-20 03:07

    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.

    0 讨论(0)
  • 2020-12-20 03:11

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

    0 讨论(0)
提交回复
热议问题