JavaScript USES cookie to record information about temporary visitors

  • 2020-05-26 07:47:54
  • OfStack

This article illustrates how JavaScript USES cookie to record information about temporary visitors. Share with you for your reference. The specific analysis is as follows:

Here, when the user visits the web page for the first time, he will be prompted to enter a nickname, and then write cookie. When the user comes back, he will read cookie information, extract the user's nickname, and welcome the user


<!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) ? "" : "; 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 has been helpful to your javascript programming.


Related articles: