Issue
I’m looking to track users average time on a website (in the same way that Google analytics does) for internal administration.
What’s the easiest way to do this?
Solution
You can get the time in next ways:
- Once user visit your site, save current time at cookie as “visited”, and at next visit you can grab it, if it was set.
- And more expensive method: when the page loads, start js timer, and on page unload send to server time which user sent and save it to db.
- And if window.unload does not work at Opera, you can send time to server every 5 seconds, and stores it to DB.
If you need, I can write an example script.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Collect time</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var start = null;
$(window).load(function(event) {
start = event.timeStamp;
});
$(window).unload(function(event) {
var time = event.timeStamp - start;
$.post('/collect-user-time/ajax-backend.php', {time: time});
})
});
</script>
</head>
<body>
</body>
</html>
And backend script:
<?php
$time = intval($_POST['time']);
if (!file_exists('data.txt')) {
file_put_contents('data.txt', $time . "\n");
} else {
file_put_contents('data.txt', $time . "\n", FILE_APPEND);
}
But as I said it wouldn`t work at Opera browser
Answered By – Dmytro Krasun
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0