JavaScript Cookies
- Previous Page JS Timing
- Next Page Introduction to Web API
Cookies allow you to store user information on web pages.
What is a cookie?
Cookies are small text files stored on your computer.
After the web server sends a web page to the browser and the connection is closed, the server will forget everything about the user.
Cookies were invented to solve the problem of "how to remember user information":
- When a user visits a web page, his name can be stored in a cookie.
- When the user visits the page again, the cookie will "remember" his name.
Cookies are stored in name-value pairs, such as:
username = Bill Gates
When the browser requests a web page from the server, the cookies belonging to that page are added to the request. This way, the server gets the necessary data to "remember" the user's information.
If the browser has disabled local cookie support, the following examples will not work.
Creating cookies with JavaScript
JavaScript can be used to document.cookie
Properties to create, read, and delete cookies.
You can create cookies like this with JavaScript:
document.cookie = "username=Bill Gates";
You can also add an effective date (UTC time). By default, cookies are deleted when the browser is closed:
document.cookie = "username=Bill Gates; expires=Sun, 31 Dec 2017 12:00:00 UTC";
Through path
Parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.
document.cookie = "username=Bill Gates; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";
Read cookie through JavaScript
Through JavaScript, you can read the cookie like this:
var x = document.cookie;
document.cookie
It will return all cookies in one string, like: cookie1=value; cookie2=value; cookie3=value;
Change cookie through JavaScript
By using JavaScript, you can change it just like you create a cookie:
document.cookie = "username=Steve Jobs; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";
Old cookie is overwritten.
Delete cookie through JavaScript
Deleting a cookie is very simple.
When deleting a cookie, it is not necessary to specify the cookie value:
Directly put expires
Set the parameter to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
You should define the cookie path to ensure that the correct cookie is deleted.
Some browsers will not allow you to delete a cookie if you do not specify a path.
Cookie string
document.cookie
The attribute looks like a normal text string. But it is not.
Even if you are document.cookie
Write a complete cookie string, and when you read it again, you can only see its name-value pair.
If a new cookie is set, the old cookie will not be overwritten. The new Cookie will be added to document.cookie, so if you read document.cookie, what you get will be like this:
cookie1 = value; cookie2 = value;
If you want to find the value of a specified cookie, you must write 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.
When a visitor arrives at the web page for the first time, they will be asked to fill in their name. Then, this name is stored in the cookie.
When the next visitor arrives at the same page, they will receive a welcome message.
For example, we will create 3 JavaScript functions:
- Function to set the value of the cookie
- Function to retrieve the value of the cookie
- Function to check the value of the cookie
Cookie setting function
First, we create a function to store the visitor's name in the cookie variable:
Example
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
Example explanation:
The parameters of this function are: the name of the cookie (cname), the value of the cookie (cvalue), and the number of days the cookie is known to expire (exdays).
By adding the cookie name, cookie value, and expiration string together, this function sets the cookie.
Cookie retrieval function
Then, we create a function that returns the value of a specified cookie:
Example
function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.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 explanation:
Pass the cookie as a parameter (cname).
Create a variable (name) and the text to be searched (CNAME"=").
Decode the cookie string, handle cookies with special characters, such as "$".
Split document.cookie into an array named ca (decodedCookie.split(';')) with semicolons.
Traverse the ca array (i = 0; i < ca.length; i++) and then read out each value c = ca[i].
If the cookie is found (c.indexOf(name) == 0), it will return the value of the cookie (c.substring(name.length, c.length)).
If the cookie is not found, it will return "".
Cookie detection function
Finally, we create a function to check if the cookie is set.
If the cookie is already set, it will display a greeting.
If the cookie is not set, it will display a prompt box to ask for the user's name and store the username cookie for 365 days by calling setCookie
Function:
Example
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
Now combine them together
Example
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } 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 user = getCookie("username"); if (user != "") { alert("Welcome again " + user); } user = prompt("Please enter your name:", ""); if (user != "" && user != null) { setCookie("username", user, 365); } } }
The above example will run the checkCookie() function after the page is loaded.
- Previous Page JS Timing
- Next Page Introduction to Web API