Developer Snippet Diary

COOKIE In javascript

Cookie is used to store data in browser. cookie saved only if we our connection is with server ie localhost.

A cookie has 

  • Name (user_name_un)
  • Content (rizi)
  • Domain (localhost)
  • Path ( / )
  • Send for ( Any kind of connection)
  • Accessible to script ( Yes )
  • Created (Wednesday, April 29, 2020 at 6:12:45 PM)
  • Expires (Friday, May 29, 2020 at 6:12:45 PM)

CREATE

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

READ

var x = document.cookie;

DELETE

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

 

function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  //d.setTime(d.getTime() + (exdays*24*60*60*1000));
  d.setTime(d.getTime() + (exdays*30*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 "";
}

function checkCookie() {
  var user=getCookie("ip_address");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
     user = "192.168.1.1";
     if (user != "" && user != null) {
       setCookie("ip_address", user, 1);
     }
  }
}
Posted by: R GONDAL
Email: rizikmw@gmail.com