0

Is it possible to create a session number of page view/visit like PHP, but in JavaScript?

$_SESSION['views'] = 0;

Is it possible to keep track of the number even when user quite the page and get back again?

halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

2 Answers2

2

You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist

Example:

<p id="yolo"> </p>

<script>
    var numberOfVisits = function getCookie('numberOfVisits');

    if (numberOfVisits == "")
    {
        setcookie('numberOfVisits', 1, 100);
    }
    else
    {
        numberOfVisits++;
        setcookie('numberOfVisits', numberOfVisits, 100);
    }

    document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');

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

    function setcookie(name, value, days)
    {
        if (days)
        {
            var date = new Date();
            date.setTime(date.getTime()+days*24*60*60*1000);
            var expires = "; expires=" + date.toGMTString();
        }
        else
        {
            var expires = "";
        }
        document.cookie = name+"=" + value+expires + ";path=/";added
    }
</script>
dustytrash
  • 1,568
  • 1
  • 10
  • 17
0

If you only need the data on the client side then use window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.

<script>

var varname = "VISIT_COUNTER";
 if (localStorage.getItem(varname) === null) {
        localStorage.setItem(varname, 1);
 } else { 
        var visits_count = parseInt(localStorage.getItem(varname)) + 1;
        localStorage.setItem(varname, visits_count);
        console.log("Total visits: " + visits_count);
 }

</script>
fortesp
  • 11
  • 1
  • 5