Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript Cookies


May 06, 2021 JavaScript


Table of contents


JavaScript Cookies


Cookies are used to store user information on web pages.

Because JavaScript is a script that runs on the client, you can use JavaScript to set cookies that run on the client.


What are cookies?

Cookies are data stored in text files on your computer.

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

The purpose of cookies is to address "how to record user information on the client":

  • 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 a name/value pair, as follows:

username=John Doe

When a browser requests a web page from a server, cookies that belong to that page are added to the request. In this way, the service side obtains the user's information.


Create cookies using JavaScript

JavaScript can use the document.cookie property 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 removed when the browser is closed:

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

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 2013 12:00:00 GMT; path=/";

Use JavaScript to read cookies

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

var x = document.cookie;

JavaScript Cookies document.cookies will return all cookies in a string format: cookie1-value; c ookie2=value; cookie3=value;


Use JavaScript to modify cookies

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

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

Old cookies will be overwritten.


Use JavaScript to delete cookies

Removing cookies is easy. All you need to do is set the expires parameter to the previous time, set to Thu, 01 Jan 1970 00:00:00 GMT as follows:

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

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


Cookie string

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

Even if you write a complete string of cookies in document.cookies, when you re-read the cookie information, the cookie information is displayed as a name/value pair.

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 the document.cookie, you will get the following data:

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.


An instance of a JavaScript cookie

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

First, the visitor visits the web page and will be asked to fill in his name. The name is stored in the cookie.

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

In this example, we'll create three JavaScript functions:

  1. The function that sets the value of the cookie
  2. The function that gets the value of the cookie
  3. A function that detects the value of a cookie

The function that sets the value of the cookie

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

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

The function sets the cookie name, the cookie value, and the time the cookie expires.


The function that gets the value of the cookie

We then create a function where the user returns the value of the 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 parsing:

The parameter of the cookie name is cname.

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

Use a sign to split the document.cookie string and assign the split string array to ca (ca s document.cookie.split ('; '))。

Loop ca array (i=0; i <ca.length; i)), then read each value in the array and remove the front and rear spaces (c-ca.i.trim().)

If a cookie (c.indexOf(name) is found, the value of the cookie (name.length, c.length) is returned.

If no cookie is found, return "".


A function that detects the value of a cookie

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

If a cookie is set, a greeting message is displayed.

If no cookie is set, a screen window is displayed to ask the visitor's name and the setcookie function is 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);
}
}
}


The full instance

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 again " + user);
}
else
{
user = prompt("Please enter your name:","");
if (user!="" && user!=null)
{
setCookie("username",user,365);
}
}
}

Try it out . . .

The following example performs the checkCookie() function when the page is loaded.


Related articles

JavaScript Notes: JavaScript Operation Cookies