0

I can find the start time of the user when visit the page but not getting the end time.

I tried below jquery event to get the time when user leaves the page but it is not working for me. Could you help me to get the end time of the visitor?

        $(document).ready(function() { 
            $(window).unload(function() { 
                alert("you are leaving from page"); 
            }); 
        }); 
    </script>
$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});
Qirel
  • 25,449
  • 7
  • 45
  • 62
Gulshan kumar
  • 399
  • 3
  • 8
  • Not sure there is a sure fire way to detect when they leave. This might be the best information out there on the best possible solution. https://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page – FSDford Nov 03 '20 at 07:42

2 Answers2

1

try like this:

$(document).ready(function() {
  var start = new Date();

  $(window).unload(function() {
      var end = new Date();
      $.ajax({ 
        url: "log.php",
        data: {'timeSpent': end - start},
        async: false
      })
   });
});
1

The best solution is to use navigator.sendBeacon:

var navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
  var client = new XMLHttpRequest();
  client.open("POST", url, false); // third parameter indicates     sync xhr
  client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  client.send(data);
};
Nbody
  • 1,168
  • 7
  • 33