JavaScript Tutorial

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 Phillipe

How Cookies Work?

  • When a user sends a request to the server, each request is treated as if it were sent by a different user. To identify returning users, cookies are used.
  • Cookies are small pieces of data sent by the server and stored on the user's browser at the client side. When the server responds to a request, it includes a cookie in the response.
  • The browser automatically attaches the cookie to subsequent requests made by the user. This allows the server to recognize and identify the user based on the cookie.

In summary, cookies enable the server to maintain user identification across multiple requests by storing a small piece of data on the client's browser and associating it with the user's session.

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

With the help of JavaScript, the user can change a cookie the same as it is created:

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 a user delete the cookie if you don't specify the path

Cookie String

The document.cookie property appears as a regular text string, but it functions differently.

Although you can assign a complete cookie string to document.cookie, when you retrieve its value again, you will only see the name-value pair of the cookie.

When setting a new cookie, it does not overwrite older cookies. Instead, the new cookie is appended to the document.cookie property. Thus, when you read document.cookie again, you will obtain all the cookies in the form of key-value pairs, for example:

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 the browser.

The first time when a user arrives at 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 on 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:-

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 expiration string.

A Function to Get a Cookie

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

Input:-

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 a 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:-

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):-

Go back to Previous Course