Create and store cookies
In this example we will create a cookie that stores the visitor's name. When visitors visit the site for the first time, they are asked to fill in their names. The name is stored in a cookie. When visitors visit the site again, they receive a welcome word.
First, we'll create a function that stores the visitor's name in a cookie variable:
function Setcookie (c_name,value,expiredays) {var exdate=New Date () exdate.setdate ( Exdate.getdate ()+expiredays) document.cookie=c_name+ "=" +escape (value) +((expiredays= = Null)? "": "; expires=" +exdate.togmtstring ())}
The parameters in the above function contain the name of the cookie, the value, and the number of days to expire.
In the above function, we first convert the number of days to a valid date, and then we deposit the cookie name, value, and its expiration date into the Document.cookie object.
After that, we'll create another function to check if the cookie has been set:
function GetCookie (c_name) {if (document.cookie.length>0) { C_start= Document.cookie.indexOf (c_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length+1 c_end=document.cookie.indexof (";" , C_start) if (c_end==-1) c_end=document.cookie.length return unescape ( Document.cookie.substring (c_start,c_end)} }return ""}
The above function first checks whether a cookie exists in the Document.cookie object. If the Document.cookie object has certain cookies, it will continue to check whether the cookie we specified is stored. If we find the cookie we want, we return the value, otherwise we return an empty string.
Finally, we'll create a function that shows a welcome word if the cookie is set, or a prompt box to ask the user to enter a name.
function Checkcookie () {username=getcookie (' username ')if (username!=null && Username!= "") {alert (' Welcome again ' +username+ '! ') )}Else { username=prompt (' Please enter your name: ', "") If (username!=null && username!= "") { Setcookie (' username ', username , 365) }}}
This is all the code:
functionGetCookie (c_name) {if(document.cookie.length>0) {C_start=document.cookie.indexof (c_name + "=") if(C_start!=-1) {C_start=c_start + c_name.length+1C_end=document.cookie.indexof (";", C_start)if(c_end==-1) c_end=Document.cookie.lengthreturnunescape (document.cookie.substring (C_start,c_end))}}return""}functionSetcookie (c_name,value,expiredays) {varExdate=NewDate () exdate.setdate (Exdate.getdate ()+expiredays) Document.cookie=c_name+ "=" +escape (value) +((Expiredays==NULL) ? "": "; expires=" +exdate.togmtstring ())}functionCheckcookie () {username=getcookie (' username ')if(username!=NULL&& username!= "") {alert (' Welcome again ' +username+ '! ')}Else{username=prompt (' Please enter your name: ', ' "") if(username!=NULL&& username!= "") {Setcookie (' Username ', username,365) } }}</script>The Cookies inside JavaScript