Track Time Spent By User on Webpage Using JavaScript



To track time spent by website visitor on a given page, we will be using javascript's onbeforeunload event. The onbeforeunload event occurs when the document is about to be unloaded.

So as soon as the page loads, a start time is stored in a variable and just before unloading, the end time is stored in another variable whose difference is then stored in mysql database using Ajax.


Code

Database



db_connection.php

<?php
$server = 'localhost';
$username = 'root';
$password = '';
$db = 'your db name';
$conn = mysqli_connect($server,$username,$password,$db);
if(!$conn){
  die("Connection Failed: ".mysqli_connect_error());
}
?>


index.php

<?php include 'connection.php'; ?>
<html>
<head>
  <title>Duration</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script> startTime = new Date(); </script>
</head>
<body onbeforeunload="myFunc()">
  <h1>Finding Time spent on this page</h1>
  <br>
  <h3>Following are results:</h3>
  <?php
  $select = mysqli_query($conn,"SELECT * FROM duration");
  while($s = mysqli_fetch_array($select)){
    $dur = $s['time'];
    $dur = $dur/1000;
    echo $dur.' seconds <br>';
  }
  ?>
  <script>
  function myFunc(){
    endTime = new Date();
    $.ajax({
      url:'addDur.php',
      method:'POST',
      data:{
        duration:endTime - startTime,
      }
    });
  }
  </script>
</body>
</html>


addDur.php

<?php
include 'connection.php';
$duration = $_POST['duration'];
mysqli_query($conn,"INSERT INTO duration VALUES('','$duration')");
 ?>




Comments