JavaScript Cookies, Set, get, update and delete cookies

Today we will discuss JavaScript Cookies. The data in the cookie allows the server to continue a conversation, so to speak. Without the cookie, the server considers the browser a first-time visitor. So let’s learn more about JavaScript Cookies

What are JavaScript Cookies?

JavaScript Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem “how to remember information about the user”:

  • When a user visits a web page, his/her name can be stored in a cookie.
  • Next time the user visits the page, the cookie “remembers” his/her name.

Cookies are saved in name-value pairs like:

Example
document.cookie = “username=Max Brown”;

How to create a Cookie in JavaScript?

In JavaScript, we can create, read, update and delete a cookie by using document.cookie property.

The following syntax is used to create a cookie:

Syntax
document.cookie=”keyName1=value1;keyName2=value2;keyName3=value3;”;

Example

document.cookie="name=Ravi shukla";

Set cookies with expiry date

By default, cookies will be automatically deleted once the browser is closed. This prevents users from re-using the cookie values on subsequent visits to your page. You can override this by setting an expiration date for your cookie. This can be done easily by adding expires=expirationDate in UTC separated by a semicolon from the name=value, as seen in the following example:

Syntax
document.cookie = “username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC”;

Get Cookies

Getting all cookies is very simple. Cookies are stored as a set of strings separated by semicolons. You can access this value by calling document.cookie as seen in the example below:

function ReadCookie() {
   var allcookies = document.cookie;
   document.write ("All Cookies : " + allcookies );
   
   // Get all the cookies pairs in an array
   cookiearray = allcookies.split(';');
   
   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++) {
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      document.write ("Key is : " + name + " and Value is : " + value);
   }
}

ReadCookie()

Delete a Cookie

Deleting a cookie is very simple.

You don’t have to specify a cookie value when you delete a cookie.

Just set the expires parameter to a past date, when you want to delete cookies. like this

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

Recommended Posts