JavaScript, browsers, window close - send an AJAX request or run a script on window closing

前端 未结 9 858
梦毁少年i
梦毁少年i 2020-11-22 04:40

I\'m trying to find out when a user left a specified page. There is no problem finding out when he used a link inside the page to navigate away but I kind of need to mark up

9条回答
  •  有刺的猬
    2020-11-22 05:22

    There are unload and beforeunload javascript events, but these are not reliable for an Ajax request (it is not guaranteed that a request initiated in one of these events will reach the server).

    Therefore, doing this is highly not recommended, and you should look for an alternative.

    If you definitely need this, consider a "ping"-style solution. Send a request every minute basically telling the server "I'm still here". Then, if the server doesn't receive such a request for more than two minutes (you have to take into account latencies etc.), you consider the client offline.


    Another solution would be to use unload or beforeunload to do a Sjax request (Synchronous JavaScript And XML), but this is completely not recommended. Doing this will basically freeze the user's browser until the request is complete, which they will not like (even if the request takes little time).

提交回复
热议问题