WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Cookies


Cookies are used to store user information for web pages.


What are Cookies?

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

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

The purpose of cookies is to solve "how to record client user information":

  • When a user visits a web page, his name can be recorded in a cookie.
  • The next time a user visits the page, the user's visit history 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 a server, the cookies that belong to that page are added to the request. The server obtains user information in this way.


Create a Cookie with JavaScript

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

In JavaScript, create a cookie 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 2018 12:00:00 UTC";

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

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

Read a Cookie with JavaScript

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

var x = document.cookie;
document.cookie will return all cookies as a string, type format: cookie1 = value; cookie2 = value; cookie3 = value;

Change a Cookie with JavaScript

In JavaScript, modifying cookies is similar to creating cookies, as follows:

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

The old treat is overwritten.


Delete a Cookie with JavaScript

Deleting cookies is easy. You just need to set the expires parameter to the previous time, as shown below, set to Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=; expires=Thu, 01 Jan 2018 00:00:00 UTC";

Note that you do not have to specify the value of the cookie when you delete it.


The Cookie String

document.cookie property looks like a normal text string, but it's not.

Even if you write a complete cookie string in document.cookie, when you re-read the cookie information, the cookie information is displayed as 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 re-read 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 find 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, the visitor visits the web page and he will be asked to fill in his name. The name is stored in a cookie.

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

In this example we will create 3 JavaScript functions:

  1. A function to set the cookie value
  2. Function to get cookie value
  3. A function to detect cookie values

Function to set cookie value

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

Example

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var terminates = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
Function analysis: In the above function parameters, the name of the cookie is cname, the value of cookie is cvalue, and the cookie expiration time expires is set. This function sets the cookie name, cookie value, and cookie expiration time.

A Function to Get a Cookie

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

Example

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

Function analysis:

The parameter for cookie name is cname.

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

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

Cycle ca array (i=0;i<ca.length;i++), Then read each value in the array and strip the leading and trailing spaces (c = ca [i] .trim ()).

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

If no cookie is found, return "".


A Function to Check a Cookie

Finally, we can create a function that checks whether a cookie was created.

If cookies are set, a greeting message will be displayed.

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

Example

function checkCookie() {
    var username=getCookie("username");
    if (username!="") {
        alert("Welcome again " + username);
    }else{
        username = prompt("Please enter your name:", "");
        if (username != "" && username != invalid) {
            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 lapses = "expires="+d.toUTCString();
    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];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var client = getCookie("username");
    if (client != "") {
        alert("Welcome again " + user);
    } else {
        client = prompt("Please enter your name:", "");
        if (client != "" && client != invalid) {
            setCookie("username", client, 365);
        }
    }
}
Try it yourself »

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