BOM Cookies (JavaScript Cookies)

Cookies are used to store user information in web pages.


What are Cookies?

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 dsigned to solve this 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 below:

username = Jean Phillpe

How Cookies Works?

  • When a user sends a request to the server, then each of that request is behave as a new request sent by the different user.
  • So, to identify the old user, we need to add the cookie with the response from the server.
  • browser at the client-side.
  • Now, whenever a user sends a request to the server, the cookie is added with that request automatically. Due to the cookie, the server recognizes the users.

Note:- The examples below will work if your browser has local cookies support turned off.


Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the document.cookie property.

With JavaScript, a cookie can be created like this:

document.cookie = "username=Jean Phillpe";

An expiry date (in UTC time) can be added with cookie. By default, the cookie is deleted when the browser is closed:

document.cookie = "username=Jean Phillpe; expires=Mon, 15 Apr 2021 12:00:00 UTC";

By passing the path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=Jean Phillpe; expires=Mon, 15 Apr 2021 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

JavaScript, cookies can be read like below:

var cookieData = document.cookie;

Note:- document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;


Change a Cookie with JavaScript

By help of JavaScript, user can change a cookie the same way as you create it:

document.cookie = "username=Jean Smith; expires=Mon, 15 Apr 2021 12:00:00 UTC; path=/";

The old cookie will be overwritten in this case.


Delete a Cookie with JavaScript

Deleting a cookie is very simple by using Javascript.

To delete a cookie you just need to set the expires parameter to a passed date:

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

Note:-

To delete the right cookie user should define the cookie path.

Some browsers will not let user delete a cookie if you don’t specify the path


Cookie String

The document.cookie property looks like a normal text string. But it is not like that.

Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.

If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get all cookies key value pair something like:

cookie1 = value; cookie2 = value;


Cookie Example

In the example below, we will be creating a cookie that stores the name of a user coming to browser.

The first time when a user arrives to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie.

The next time when the same user arrives at the same page, he/she will get a welcome message.

For the example we will create 3 JavaScript functions:

  1. A function to set a cookie value
  2. A function to get a cookie value
  3. A function to check a cookie value

Function to Set a Cookie

First, we create a function that stores the name of the user in a cookie variable:

Input:-
<!DOCTYPE html>
<html>
<body>

<p>Example to Set Cookie</p>

<p>Click on button to set cookie</p>
<button onclick="setCookieData('name','Jean Phillpe', 3)">Click me</button>

<script>
function setCookieData(uname, uvalue, expdays) {
  var d = new Date();
  d.setTime(d.getTime() + (expdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = uname + "=" + uvalue + ";" + expires + ";path=/";
}
</script>

</body>
</html> 

Output :-

Example explained:

The parameters of the function above are the name of the cookie (uname), the value of the cookie (uvalue), and the number of days until the cookie should expire (expdays).

The function setCookieData sets a cookie by adding together the cookie name, the cookie value, and the expires string.


A Function to Get a Cookie

Below is the example function that returns the value of a specified cookie:

Input:-
<!DOCTYPE html>
<html>
<body>

<p>Example to Get Cookie</p>
<p>Click on button to get cookie</p>
<button onclick="getCookie('name')">Click me</button>
<p id="result"></p>

<script>

function readCookieData(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function getCookie(){
	var value = readCookieData('name');
	document.getElementById("result").innerHTML =  value;

}
</script>

</body>
</html>

Output (Before Click):-

Output (After Click):-

Function explained:

Take the cookiename as parameter (name).

Create a variable (nameEQ) with the text to search for (name + “=”).

Decode the cookie string, to handle cookies with special characters, e.g. ‘$’

Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(‘;’)).

Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).

If the cookie is found (c.indexOf(nameEQ) == 0), return the value of the cookie (c.substring(nameEQ.length, c.length).

If the cookie is not found, return “”.


A Function to Check a Cookie

Last, we create the function that checks if a cookie is set or not.

If the cookie is set it will display a welcome message.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 10 days, by calling the setCookieData function:

Input:-
<!DOCTYPE html>
<html>
<body>

<p>Example to Check Cookie</p>
<p>Click on button to check cookie</p>
<button onclick="checkCookie('name')">Click me</button>
<p id="result"></p>

<script>
	
function setCookieData(uname, uvalue, expdays) {
  var d = new Date();
  d.setTime(d.getTime() + (expdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = uname + "=" + uvalue + ";" + expires + ";path=/";
}


function readCookieData(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function checkCookie() {
  var uname = readCookieData("name");
  if (uname != "" && uname != null) {
   alert("Welcome again " + uname);
  } else {
    uname = prompt("Please enter your name:", "");
    if (uname != "" && uname != null) {
      setCookieData("name", uname, 365);
	  alert("Entered name - '"+uname+"' is stored in cookie.");
    }
  }
}
</script>

</body>
</html>

Output (After click on button if already name is set in cookie):-

Output (After click on button if name is not set in cookie):-

Output (After click on ok of prompt box the cookie will be set):-