Js Cookies
---
Cookie is used to store user information of web pages.
---
## What is Cookie?
Cookie is some data, stored in a text file on your computer.
When the web server sends a web page to the browser, after the connection is closed, the server does not record the user's information.
The purpose of Cookie is to solve 'how to record client user information':
* When the user visits a web page, his name can be recorded in the cookie.
* When the user visits the page again, the user's visit record can be read from the cookie.
Cookie is stored in name/value pairs, as shown below:
username=John Doe
When the browser requests a web page from the server, the cookie belonging to that page is added to the request. The server obtains user information in this way.
---
## Using JavaScript to Create Cookie
JavaScript can use the **document.cookie** property to create, read, and delete cookies.
In JavaScript, creating a cookie is shown as follows:
document.cookie="username=John Doe";
You can also add an expiration time to a 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 cookie's path. 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 Cookie
In JavaScript, you can use the following code to read a cookie:
var x = document.cookie;
| {var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + "; " + expires; }
**Function explanation:**
In the function parameters above, the cookie's name is cname, the cookie's value is cvalue, and the cookie's expiration time is set to expires.
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.trim(); if(c.indexOf(name)==0)return c.substring(name.length,c.length); }return""; }
**Function explanation:**
The parameter for cookie name is cname.
Create a text variable to retrieve the specified cookie: cname + "=".
Use semicolon 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 trim leading/trailing spaces (c=ca.trim()).
If cookie is found (c.indexOf(name) == 0), return the cookie's value (c.substring(name.length,c.length).
If cookie
YouTip