Easy Tutorial
❮ Js Lib Prototype Javascript Json Parse ❯

JavaScript Cookie


Cookies are used to store user information for web pages.


What is a Cookie?

A cookie is some data stored in a text file on your computer.

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

The purpose of a cookie is to solve the problem of "how to record client user information":

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

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


Creating a Cookie with JavaScript

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

To create a cookie in JavaScript, you can do the following:

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

You can use the path parameter to tell the browser the path of the cookie. By default, the cookie belongs to the current page.


Reading a Cookie with JavaScript

In JavaScript, you can read cookies using the following code:

| | document.cookie will return all cookies in a string format: cookie1=value; cookie2=value; cookie3=value; | | --- | --- |


Modifying a Cookie with JavaScript

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

The old cookie will be overwritten.


Deleting a Cookie with JavaScript

Deleting a cookie is straightforward. You just need to set the expires parameter to a past time, as shown below, setting it to Thu, 01 Jan 1970 00:00:00 GMT:

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


Cookie String

The document.cookie property looks like a plain 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 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 like this:

cookie1=value; cookie2=value;

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


JavaScript Cookie Example

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

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

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

In this example, we will create three JavaScript functions:


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

The function parameters include the cookie name cname, the cookie value cvalue, and the cookie expiration time expires.

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


Function to Get Cookie Value

Next, 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 Analysis:

The parameter for the cookie name is cname.

A text variable is created to retrieve the specified cookie: cname + "=".

The document.cookie string is split with semicolons, and the resulting string array is assigned to ca (ca = document.cookie.split(';')).

The ca array is looped through (i = 0; i < ca.length; i++), and each value in the array is read and trimmed of leading and trailing spaces (c = ca[i].trim()).

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

If the cookie is not found, an empty string is returned.


Function to Check Cookie Value

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

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

If the cookie is not set, a prompt will appear 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("欢迎 " + user + " 再次访问");
  } else {
    user = prompt("请输入你的名字:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 30);
    }
  }
}

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

❮ Js Lib Prototype Javascript Json Parse ❯