Tracking website visits using JavaScript cookies

Is there a way to track the number of times a user visits a page, but only increment the visit count if more than 30 minutes have passed since their last visit?

If so, how can this be accomplished?

Currently, I am using the following code snippet to set and get the cookie:


getCookie('xVisitors');
setCookie('xVisitors', 1, 120);

function setCookie(name, value, expiry) {
    var expires = "";
    if (expiry > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiry * 60 * 1000);
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/;";
};

function getCookie(name) {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        while (cookie.charAt(0) == " ") {
            cookie = cookie.substring(1);
        }
        if (cookie.indexOf(name) == 0) {
          return cookie.substring(name.length + 1, cookie.length);
        }
    }
    return "";
}

Answer №1

let currentTime = new Date().getTime();
let numberOfVisits = 1;
let visitorsInfo = getCookie('visitorsInfo').split('|');
if ( typeof visitorsInfo[1]!='undefined' ) {
  numberOfVisits = ( (currentTime-parseInt(visitorsInfo[1])) > (30*60) ) ? (visitorsInfo[0]+1) : visitorsInfo[0];
}
setCookie('visitorsInfo',numberOfVisits+"|"+currentTime,120);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting a function key, such as F2, to quickly rename a tab is a convenient way to

Looking at the screenshot provided, it is clear that renaming a selected tab requires clicking on it, while deleting an unselected tab necessitates a mouse hover. Unfortunately, these actions are not accessible via keyboard shortcuts. To address this issue ...

Raphael JS Path Animation: Wiping Away

I have successfully created a line animation using RaphaelJS, which can be viewed on this jsfiddle link - http://jsfiddle.net/7n040zdu/. My next challenge is to create an erasing animation that follows the initial one. This erasing animation should mimic t ...

Utilizing a Search feature with Express and Node within the MVC framework

On the customers page of my website, I have implemented a search bar that sends the admin's input as a GET request. The goal is to find all data in the MySQL database that includes the entered string within the fullname field. The website is built us ...

Searching for a way to programmatically uncheck a radio button based on a specific condition

Is there a way for me to deselect the radio button under specific conditions? <input type="radio" name="XXX" value="add" data-ng-model="XXX"/>Add I am looking to have this radio button unchecked when certain conditions are met, like so: <input ...

javascript code producing incorrect HTML

I created a script to populate a selectbox with various options. Initially, the data is in the form of a string like this: "key=value;key2=value2;etc...": //splitting the string to separate different options for the selectbox var values = data.split(&apo ...

Modify the name format using an AngularJS directive

I've been struggling to understand how to effectively write AngularJS directives, even after reading various blogs. The issue I am facing is with an array of names in the format "lastname, firstname". My goal is to create a directive that will display ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

Display jpg images while authenticating using nextauth version 4.22.1

Hello everyone, I am currently working on displaying images with authentication using nextauth 4.22.1, as mentioned in the title. I have set up the new /app directory within the /src directory. While it occasionally works, most of the time it does not. H ...

Having trouble with innerHTML.value functionality?

Recently, I've been delving into creating a JavaScript program that fetches Wikipedia search results. Initially, everything seemed to be working fine as I was able to display the searched item using the alert() method. However, for some reason, it now ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

how to manipulate checkbox selection and deselection with reactive forms in Angular 8

Hey there! I'm currently working with an array of objects that contain IDs and values. I'm using reactive forms to bind these objects to HTML, but when I try to select and deselect all, I'm not getting the desired output without any errors. ...

Updating Content in HTML Code Generated by JavaScript

My goal is to change the innerHTML of a div when it's clicked. I have an array of dynamically generated divs, and I want to target the specific table that the user clicks on. I attempted to set the IDs of the tables dynamically in my JavaScript code: ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

How can the service-worker and cache storage API handle caching a redirect with an HTTP 302?

I need help with my website that is served over https from Tomcat and includes a service worker for fetching and storing resources in the cache. Everything works well when Tomcat is running, but I have run into an issue. My Tomcat configuration includes ...

Choose the final field that is visible when the function is applied

This is the issue I am facing: On our website, we have 5 input fields all sharing the same class name, for example class="inputfield". When the page loads, only the first input field is visible. Next to each field, there is a button that reveals the next ...

Nightwatch.js feature not functioning properly in a 'closing' manner

I'm facing an issue where I need to execute a function at the beginning of my test before proceeding with the rest of the test steps. Here is the custom command I am using, named internalAdviceLinksHtml: const solr = require('solr-client') ...

Plupload is not compatible with ng-dialog

I'm currently attempting to integrate plupload into a modal window that is generated by ng-dialog. Here is the code I am using: $scope.showManager = function(){ ngDialog.open({ template: '/template/fmanager.html', controller: &apo ...