JavaScript Cookie


Cookies are used to store user information on web pages.


What is a Cookie?

Cookies are some data stored in text files on your computer.

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

The role of cookies is to solve "how to record client-side user information":

  • When a user visits a web page, their name can be recorded in a cookie.
  • When the user visits the page next time, the user's visit record can be read from the cookie.

Cookies are stored in name/value pairs, as shown below:

username=John Doe

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


Using JavaScript to Create a Cookie

JavaScript can use thedocument.cookieproperty to create, read, and delete cookies.

In JavaScript, creating a cookie is as follows:

document.cookie="username=John Doe";

You can also add an expiration time for the cookie (in UTC or GMT time). By default, the cookie is 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 the browser the path of 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=/";

Using JavaScript to Read a Cookie

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

var x = document.cookie;

Note document.cookie will return all cookies as a string, in the format: cookie1=value; cookie2=value; cookie3=value;


Using JavaScript to Modify a Cookie

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

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

The old cookie will be overwritten.


Using JavaScript to Delete a Cookie

Deleting a cookie is very simple. You only need to set the expires parameter to a past time, as shown below, set to Thu, 01 Jan 1970 00:00:00 GMT:

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

Note that you do not need to specify the cookie value when deleting it.


Cookie String

The document.cookie property looks like an ordinary text string, but it is not.

Even if you write a complete cookie string into document.cookie, when you read the cookie information again, the cookie information is displayed in the form of name/value pairs.

If you set a new cookie, the old cookie will not be overwritten. The new cookie will be added to document.cookie, so if you read document.cookie again, you will get data as shown below:

cookie1=value; cookie2=value;

     

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


JavaScript Cookie Examples

In the following examples, we will create cookies to store visitor names.

First, when a visitor visits a web page, they will be asked to fill in their name. The name will be stored in a cookie.

The next time the visitor visits the page, they will see a welcome message.

In this example, we will create 3 JavaScript functions:

  1. Function to set cookie value
  2. Function to get cookie value
  3. Function to check cookie value

Function to Set Cookie Value

First, we 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 breakdown:

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

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


Function to Get Cookie Value

Then, we create a function to return the value of a 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 breakdown:

The cookie name parameter is cname.

Create a text variable to search for the specified cookie: cname + "=".

Use semicolons to split the document.cookie string, and assign the resulting string array to ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), then read each value in the array, and remove leading and trailing spaces (c=ca[i].trim()).

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

If the cookie is not found, return "".


Function to Check Cookie Value

Finally, we can create a function to check whether a cookie has been created.

If the cookie is set, a greeting message will be displayed.

If the cookie is not set, a popup will be displayed to ask 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); } } }


Full 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 Yourself »

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

Other Extensions