Cookies in javascript

Expert User Verified
Cookies in javascript
 function setCookie(cname,cvalue,exdays)
 {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  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 "";
  }

First, we need to set the value of cookies after setting the cookie then we can retrieve the value of cookies.  I have made a function to set cookies that accept three-parameter. The first parameter accepts the name of the cookie, the second parameter accepts the value of the cookie and the third parameter accepts no. of expiration days after which cookies will expire.

setCookie("ChatCookie", eid, 30);

For getting the value of the cookie, we will call a function getcookie which accepts one parameter "cookie name".

var x = getCookie("ChatCookie");

Comments

Leave a Comment