Type Here to Get Search Results !
×
Hi ,

We always try to serve you better. Please enter the institute name, you belong to.

×
Hello ,

Your daily download limit has been exhausted. Share it with your friends to download more.

JavaScript Code to get and set cookie function for 2 hours

JavaScript cookie Set code

This code defines a function setCookie that sets a cookie with the given name, value, and number of days until it expires. The function takes in three parameters: cname is the name of the cookie, cvalue is the value to be stored, and exdays is the number of days until the cookie expires. The function creates a new date object and sets its time to the current time plus the number of days multiplied by the number of milliseconds in a day. This is the expiration date of the cookie. It then creates a string in the format "expires=date" where "date" is the expiration date of the cookie. Finally, it sets the cookie by assigning the name, value, and expiration date to the document.cookie object.


function setCookie(cname, cvalue, exdays) {

  var d = new Date();

  d.setTime(d.getTime() + (exdays*24*60*60*1000));

  var expires = "expires="+ d.toUTCString();

  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";

}

setCookie("exampleCookie", "exampleValue", 24);


JavaScript cookie Get code

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 "";
}

var cookieValue = getCookie("exampleCookie");
console.log(cookieValue);

This code defines a function getCookie that retrieves the value of a cookie with the given name. The function takes in one parameter: cname which is the name of the cookie you want to retrieve the value.
The function first declares a variable name which is the name of the cookie plus an equal sign. It then decodes the document.cookie and splits it into an array of individual cookies using the ; as the separator. The function then loops through the array and compares the name of each cookie to the name passed to the function. If the name of the cookie matches, it returns the value of the cookie. If no match is found, it returns an empty string.

In the last line it is calling the function and storing the value returned by the function in the variable cookieValue and then logging it in the console.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.