I am trying to calculate how much time a web page is being viewed by a user. But I am facing two problems.
Using window.location.href I am able to pass my calculated time to my PHP page and update my DB for that page. But this is also redirecting to me that PHP page which I don't want. I want to go backwards or refresh the page or do anything else but also passing the calculated time in my DB when I unload the current page without redirecting.
Click The function showElapsedTime is calculating the value of elapsed time, but the js func is only running when Click button is pressed. I want to run this function whenever I unload the current page or refresh the page
Code:
<body onload="startTimer()" >
<button onclick="showElapsedTime()>Click</button>
</body>
<script>
var id;
var start;
var end;
function startTimer() {
start = window.performance.now();
console.log(start);
}
function showElapsedTime() {
end = window.performance.now();
console.log(end - start);
var seconds = (end - start) / 1000;
window.location.href="timer.php?second=" + seconds.toFixed(2) + "&id=" + id;
}
</script>
If anyone can give me complete solutions to my issues it will be very much helpful.