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

前端 未结 9 884
梦毁少年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:26

    Years after posting the question I made a way better implementation including nodejs and socket.io (https://socket.io) (you can use any kind of socket for that matter but that was my personal choice).

    Basically I open up a connection with the client, and when it hangs up I just save data / do whatever I need. Obviously this cannot be use to show anything / redirect the client (since you are doing it server side), but is what I actually needed back then.

     io.on('connection', function(socket){
          socket.on('disconnect', function(){
              // Do stuff here
          });
     });
    

    So... nowadays I think this would be a better (although harder to implement because you need node, socket, etc., but is not that hard; should take like 30 min or so if you do it first time) approach than the unload version.

提交回复
热议问题