AJAX and user leaving a page

前端 未结 4 1652
心在旅途
心在旅途 2021-02-04 05:48

I\'m working on a chat and I\'m trying to figure out how I can detect that the user has left the page or not. Almost everything is being handled by the database to avoid the fro

相关标签:
4条回答
  • 2021-02-04 06:15

    Try this:

    $(window).unload(function(){
        $.ajax({
            type: 'POST',
            url: 'script.php',
            async:false,
            data: {key_leave:"289583002"}
        });
    });
    

    Note the async:false, that way the browser waits for the request to finish.

    Using $.post is asynchronous, so the request may not be quick enough before the browser stops executing the script.

    0 讨论(0)
  • 2021-02-04 06:29

    This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. Instead of this, what you can do is.

    1. Try connecting a socket so that you can know the user is disconnected when the socket is disconnected
    2. You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. If you didn't receive the request - even after 2 secconds - disconnect the user.
    0 讨论(0)
  • 2021-02-04 06:38

    This is related to the answer above. https://stackoverflow.com/a/10272651/1306144

    This will execute the ajax call every 1 sec. (1000)

    function callEveryOneSec() {
        $jx.ajax({}); // your ajax call
    }
    
    setInterval(callEveryOneSec, 1000);
    
    0 讨论(0)
  • 2021-02-04 06:41

    Try to add popup (prompt("leaving so early?")) after $.post. It may work. Tho it may be bad user experience. :)

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