JavaScript Cookies


Cookies are used to store user information about web pages.


What is a cookie?

Cookies are data that is stored in a text file on your computer.

when the web server sends a web page to the browser, the server does not record the user's information after the connection is closed.

The role of cookies is to solve the problem of "how to record the user information of the client":

  • when a user visits a web page, his name can be recorded in a cookie.

  • the next time the user visits the page, the user's visit record can be read in a cookie.

Cookies are stored as name/value pairs as follows:

username=John Doe

when a browser requests a web page from the server, cookies belonging to that page are added to the request. in this way, the server obtains the user's information.


Use JavaScript to create cookies

JavaScript can use the document.cookie attribute to create, read, and delete cookies.

In JavaScript, the cookie is created as follows:

document.cookie="username=John Doe";

You can also add an expiration time (in UTC or GMT time) to the cookie. By default, cookies are deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT";

you can use the path parameter to tell your browser the path to the cookie. by default, the cookie belongs to the current page.

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


Use JavaScript to read cookies

In JavaScript, you can use the following code to read cookies:

var x = document.cookie;

Notedocument.cookie will return all cookies as strings, type format: cookie1=value; cookie2=value; cookie3=value;

Use JavaScript to modify cookies

In JavaScript, modifying a cookie is similar to creating a cookie, as follows:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";

old cookies will be overwritten.


Use JavaScript to delete cookies

Deleting cookies is very simple. You just need to set the expires parameter to the previous time as follows, set to Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

Note: you do not have to specify a value for cookie when you delete.


Cookie string

the document.cookie attribute looks like a normal text string, but it is not.

even if you write a complete cookie string in the document.cookie, when you re-read the cookie information, the cookie information is presented as a name/value pair.

if you set a new cookie, the old cookie will not be overwritten. the new cookie will be added to the document.cookie, so if you re-read the document.cookie, you will get data like this:

cookie1=value; cookie2=value;

If you need to find a specified cookie value, you must create a JavaScript function to look up the cookie value in the cookie string.


JavaScript cookie example

In the following example, we will create a cookie to store the visitor name.

First, when a visitor visits a web page, he will be asked to fill in his or her name. the name is stored in the cookie.

Next time the visitor visits the page, he sees a welcome message.

In this example we will create 3 JavaScript functions:

  1. a function that sets the value of a cookie

  2. a function that gets the value of the cookie

  3. a function that detects the value of a cookie


A function that sets the value of a cookie

First, let's create a function to store the visitor's name:

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

Function parsing:

In the above function parameters, the name of the cookie is cname, the value of the cookie is cvalue, and the expiration time of the cookie is set to expires.

This function sets the cookie name, cookie value, and cookie expiration time.


A function that gets the value of the cookie

Then we create a function that returns the value of the specified cookie:

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) 
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) 
        return c.substring(name.length,c.length);
  }
  return "";
}

Function parsing:

The parameter for the cookie name is cname.

Creates a text variable to retrieve the specified cookie: cname + "=".

Use a semi-colon to split the document.cookie string and assign the split string array to ca (ca = document.cookie.split(';')).

Looping ca array (i=0; i<ca.length; i++), then read each value in the array and strip away the before and after spaces (c=ca[i].trim()).

If a cookie is found(c.indexOf(name) == 0), the value of the cookie (c.substring(name.length,c.length) is returned.

If no cookie is found, return "".


A function that detects the value of a cookie

Finally, we can create a function that detects whether a cookie was created or not.

if a cookie is set, a greeting message is displayed.

If no cookie is set, a pop-up window will be displayed asking for the visitor's name and the setCookie function will be called to store the visitor's name for 365 days:

function checkCookie()
{
  var username=getCookie("username");
  if (username!="")
  {
    alert("Welcome again " + username);
  }
  else 
  {
    username = prompt("Please enter your name:","");
    if (username!="" && username!=null)
    {
      setCookie("username",username,365);
    }
  }
}

Complete Example

Example

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

function getCookie(cname){
     var name = cname + "=";
     var ca = document.cookie.split(';');
     for(var i=0; i<ca.length; i++) {
         var c = ca[i].trim();
         if (c.indexOf(name)==0) {return c.substring(name.length,c.length);}
     }
     return "";
}

function checkCookie(){
     var user=getCookie("username");
     if (user!=""){
         alert("Welcome" + user + "Visit again");
     }
     else {
         user = prompt("Please enter your name:","");
           if (user!="" && user!=null){
             setCookie("username",user,30);
         }
     }
}

Try It! 

The following example executes the checkCookie() function when the page loads.