1👍
Sending the data onunload
may or may not work.
Another way would be to ping your server every x seconds, so you know that the use has the page still open.
setInterval(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://127.0.0.1:8000",false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}, 15);
The ping sends the session cookie along with it, so you know which user it is and can count the time on the server.
However, if you just want to know how much time each user spends on your pages, its probably easier to add Google Analytics (or a self-hosted alternative like Piwik) to your site and have the metrics collected and presented in a tested and reliable way.
👤C14L
Source:stackexchange.com