image of track time spent by user on page using js

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

The above database is created using phpmyadmin.

To create one, Go to localhost/phpmyadmin/ in your browser.

Click on Databases and create your 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());
}
?>

The mysqli_connect() function opens the new connection the MySql server.

It usually takes four parameters, namely hostname, username, password and database name.

The above code establishes the connection between your page and the database. If it fails to connect then the consequent connection error gets displayed.

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>

The include statement inherits the code from the path provided. It eliminates the effort of writing same code multiple times.This is helpful when you have large number of pages that needs same set of code to execute.

This page will be making ajax calls. In order to make those calls, the ajax library has to be loaded from https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js. Make sure that you copy the latest version to avoid any vulnerabilities.

The statement startTime = new Date(); stores time when page loaded in startTime variable.

The onbeforeunload event occurs when the page/document is about to unload or closed. In this case, it triggers the function named myFunc() .

Since, myFunc() function is triggered when page is about to unload. The statement endTime = new Date(); captures the time when this function gets triggered.

Then we make an ajax call to addDur.php which stores the time spent by the user on that page into database. The time spent by user on that particular page is calculated by endTime-startTime.

addDur.php

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

The statement $duration = $_POST[‘duration’] stores the time spent by user on the page sent during ajax call into $duration variable.

Then we make a simple MySql INSERT statement to store it into database.

Video Demo of Track time spent by user on webpage using JavaScript without google analytics.

Github Link

Leave a Reply

Your email address will not be published. Required fields are marked *