Javascript Cookies Store user identification data

Description

Javascript Cookies Store user identification data

View in separate window


<html>
   <head> 
      <title>Using Cookies</title>
      <script type = "text/javascript">
let now = new Date(); // current date and time
let hour = now.getHours(); // current hour (0-23)
let name;/*from   w  w w  . j av  a  2s .  c  om*/

if ( hour < 12 ) // determine whether it is morning
   console.log( "<h1>Good Morning, " );
else
{
   hour = hour - 12; // convert from 24-hour clock to PM time

   // determine whether it is afternoon or evening            
   if ( hour < 6 )
      console.log( "<h1>Good Afternoon, " );
   else
      console.log( "<h1>Good Evening, " );
}

// determine whether there is a cookie
if ( document.cookie )
{
   // convert escape characters in the cookie string to their 
   // English notation
   let myCookie = unescape( document.cookie );

   // split the cookie into tokens using = as delimiter
   let cookieTokens = myCookie.split( "=" );

   // set name to the part of the cookie that follows the = sign
   name = cookieTokens[ 1 ];
}
else
{
   // if there was no cookie, ask the user to input a name
   name = "Paul";

   // escape special characters in the name string
   // and add name to the cookie
   document.cookie = "name=" + escape( name );
}

console.log(
   name + ", welcome to JavaScript programming! </h1>" );
console.log( "<a href = 'javascript:wrongPerson()'>" + 
   "Click here if you are not " + name + "</a>" );

// reset the document's cookie if wrong person
function wrongPerson()
{
   // reset the cookie 
   document.cookie= "name=null;" +           
      " expires=Thu, 01-Jan-95 00:00:01 GMT";

   // reload the page to get a new name after removing the cookie
   location.reload();                        
}

         // -->
      </script>
   </head>
   <body>
      <p>Click Refresh (or Reload) to run the script again</p>
   </body>
</html>



PreviousNext

Related