WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Cookies


Cookies let you store client data in web pages.


What are Cookies?

Cookies are information, put away in little content records, on your computer.

When a web server has sent a site page to a program, the association is shut down, and the server overlooks everything about the user.

Cookies were concocted to tackle the issue "how to recollect data about the user":

  • When a client visits a site page, his name can be put away in a cookie.
  • Next time the client visits the page, the treat "remembers" his name.

Cookies are spared in name-esteem sets like:

username=John Doe

When a program ask for a website page from a server, treats having a place with the page is added to the demand. Along these lines the server gets the important information to "remember" data about users.


Create a Cookie with JavaScript

JavaScript can make, read, and erase treats with the document.cookie property.

With JavaScript, a treat can be made like this:

document.cookie="username=John Doe";

You can likewise include an expiry date (in UTC time). As a matter of course, the treat is erased when the program is closed:

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

With a way parameter, you can tell the program what way the treat has a place with. As a matter of course, the treat has a place with the current page.

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

Read a Cookie with JavaScript

With JavaScript, treats can be perused like this:

var x = document.cookie;

Change a Cookie with JavaScript

With JavaScript, you can change a treat indistinguishable route from you make it:

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 a treat is straightforward. Simply set the terminates parameter to a passed date:

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

Note that you don't need to determine a treat esteem when you erase a cookie.


The Cookie String

The document.cookie property resembles an ordinary content string. In any case, it is not.

Even in the event that you compose an entire treat string to document.cookie, when you read it out once more, you can just observe the name-esteem pair of it.

If you set another treat, more established treats are not overwritten. The new treat is added to document.cookie, so on the off chance that you read document.cookie again you will get something like:

cookie1=value; cookie2=value;

     

If you need to discover the estimation of one indicated treat, you should compose a JavaScript work that scans for the treat an incentive in the treat string.


JavaScript Cookie Example

In the guide to pursue, we will make a treat that stores the name of a visitor.

The first time a guest lands to the website page, he will be approached to fill in his name. The name is then put away in a cookie.

The next time the guest lands at a similar page, he will get a welcome message.

For the precedent we will make 3 JavaScript functions:

  1. A capacity to set a treat value
  2. A capacity to get a treat value
  3. A capacity to check a treat value

A Function to Set a Cookie

First, we make a capacity that stores the name of the guest in a treat variable:

Example

work 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;
}

Example explained:

The parameters of the capacity above are the name of the treat (cname), the estimation of the treat (cvalue), and the quantity of days until the treat ought to lapse (exdays).

The work sets a treat by including the cookiename, the treat esteem, and the lapses string.


A Function to Get a Cookie

Then, we make a capacity that profits the estimation of a predetermined cookie:

Example

work 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 explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the content to look for (cname + "=").

Split document.cookie on semicolons into a cluster called (ca = document.cookie.split(';')).

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

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

If the treat isn't discovered, return "".


A Function to Check a Cookie

Last, we make the capacity that checks if a treat is set.

If the treat is set it will show a greeting.

If the treat isn't set, it will show a brief box, requesting the name of the client, also, stores the username treat for 365 days, by calling the setCookie function:

Example

work 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);
        }
    }
}

All Together Now

Example

work 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 model above runs the checkCookie() work when the page loads.