Working with cookies in JavaScript and jQuery

The main task: to find out whether the user is on the site for the first time or not. I read several manuals on javascript cookies, looked at examples, but all sorts of sophisticated constructions are used everywhere, and came to the conclusion that everything is much simpler in php. So, I want to find out how many times the user has been on the site:

<script type="text/javascript" language="javascript">
    var iscook = navigator.cookieEnabled;
    if (iscook == true) {
        iscook = "включены";
    } else {
        iscook = "выключены";
    }
    num = 0;
    var vis = document.cookie = "visit="+num;
    if(vis == "visit=0") {
        vis = "visit="+num++;
    }
    alert("Куки "+iscook+". Вы были тут "+vis+" раз");
</script>

What did I do wrong here? And how to make it better? And another question is whether the use of the object (I believe it is an object) Navigator is relevant and how it differs from Document?

Tests with the jQuery plugin did not lead to anything, why NULL?

<script src="js/jquery-1.5.1.min.js" type="text/javascript" language="javascript">
</script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>
<script>
    num = 0;
    $.cookie("visit",num);
    if($.cookie("visit") == 0) {
        alert("Вижу вы тут первый раз");
        $.cookie("visit", num++);
    }
    else {
        alert("Вижу вы тут уже " + $.cookie("visit") + " раз!");
    }
</script>

??

Author: Nicolas Chabanovsky, 2011-03-18

2 answers

Tests with the jQuery plugin did not lead to anything, why NULL?

Each time you run the code, you write 0,

num = 0;
$.cookie("visit",num);

Which resets the number of visits. Try this code here:

<script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>

<script type="text/javascript">
     /*
          Пытаемся прочитать куки, если функция $.cookie 
          вернула null, берем 0 как исходную величину. 
          К полученной величине добавляем 1 (новое посещение)
     */
     var num = parseInt($.cookie("visit") || 0) + 1; 
     $.cookie("visit", num); //записываем обновленную величину.
     if(num == 1)
          alert("Вижу вы тут первый раз");
     else
          alert("Вижу вы тут уже " + num + " раз!");
</script>

I haven't tested the code, but it should work. In general, the solution is not very successful, since each page update is also counted as a visit.

 1
Author: Pavel Azanov, 2011-03-19 19:27:46

I can give you a ready-made code for working with cookies, I wrote it for myself:

var CookieManager = {
    set: function (name, value, days) {
         var expires = "";
          if (days) {
              var d = new Date();
              d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
              expires = "; expires=" + d.toGMTString();
          }
          document.cookie = name + "=" + value + expires + "; path=/";
          return this.get(name);
    },
    get: function (name) {
          name += "=";
          var b = document.cookie.split(';'), c;
          for (var i = 0; i < b.length; i++) {
              c = b[i].replace(/(^\s+)|(\s+$)/g, "");
              while (c.charAt(0) == ' ') 
                   c = c.substring(1, c.length);
              if (c.indexOf(name) == 0) 
                   return c.substring(name.length, c.length);
          }
          return null;
    },
    remove: function (name) {
          this.set(name, "", -1);
    }
};

Usage example:

CookieManager.set('name', 'value'); // параметр days можно не указывать
alert(CookieManager.get('name'));
CookieManager.remove('name');

In your case:

var visits = CookieManager.set('visits', parseInt(CookieManager.get('visits') || 0) + 1);
alert("Количество посещений: "+ visits);
 5
Author: Pavel Azanov, 2015-01-23 14:52:12