What are cookies?
A cookie is a variable that is stored on a visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values.
Cookie usage scenarios:
Name cookie
When a visitor visits the page for the first time, he or she may fill in his/her name. The name will be stored in a cookie. When visitors return to the site, they receive a welcome message like "Welcome John Doe!" The name is retrieved from the cookie.
Password cookie
When a visitor visits a page for the first time, he or she may fill in his/her password. Passwords can also be stored in cookies. When they visit the site again, the password is retrieved from the cookie.
Date cookie
When a visitor first visits your website, the current date can be stored in a cookie. When they visit the site again, they receive a message similar to this: "Your last visit was on Tuesday August 11, 2005!". The date is also retrieved from the cookie.
Creating and storing cookies
In this example we are going to create a cookie that stores the visitor's name. When visitors first visit the site, they are asked to fill in their name. The name will be stored in a cookie. When visitors return to the website, they receive a welcome message.
First, we’ll create a function that stores the visitor’s name in a cookie variable:
Creating a cookie is actually spelling a String:
"username=amosli;expires=Mon, 16 Dec 2013 16:20:04 GMT"
Then document.cookie=the above String.
The parameters in the above function store the name, value and expiration days of the cookie.
In the above function, we first convert the number of days into a valid date, then, we store the cookie name, value and its expiration date into the document.cookie object.
After that, we want to create another function to check if the cookie has been set:
The core of getCookie() is just one sentence, document.cookie, and the rest is the processing of strings.
The above function will first check whether there is a cookie in the document.cookie object. If the document.cookie object stores certain cookies, it will continue to check whether the cookie we specify has been stored. If the cookie we want is found, a value is returned, otherwise an empty string is returned.
Finally, we need to create a function. The function of this function is: if the cookie has been set, display the welcome message, otherwise display a prompt box to ask the user to enter a name.
This is all the code: