Home  >  Article  >  Web Front-end  >  How JavaScript uses cookies to record temporary visitor information_javascript tips

How JavaScript uses cookies to record temporary visitor information_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:05:191174browse

The example in this article describes how JavaScript uses cookies to record temporary visitor information. Share it with everyone for your reference. The specific analysis is as follows:

When the user visits the webpage for the first time, the user will be prompted to enter a nickname and then write it into the cookie. When the user comes again, the cookie information will be read, the user's nickname will be extracted, and the user is welcome

<!DOCTYPE html>
<html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
 {
 c_start = c_value.indexOf(c_name + "=");
 }
if (c_start == -1)
 {
 c_value = null;
 }
else
 {
 c_start = c_value.indexOf("=", c_start) + 1;
 var c_end = c_value.indexOf(";", c_start);
 if (c_end == -1)
  {
  c_end = c_value.length;
  }
 c_value = unescape(c_value.substring(c_start,c_end));
 }
return c_value;
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) &#63; "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var 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>
</head>
<body onload="checkCookie()">
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn