Javascript DOM Cookie set

Description

Javascript DOM Cookie set

View in separate window


<!DOCTYPE html>
<html>
<head>
   <title>Working with Cookies</title>
   <script language="JavaScript">
      function SetCookie(Name, Value, Expiration)
      {//w w  w .  j  av  a 2  s  .c o  m
         // Create a date variable that contains
         // the expiration date.
         var ExpDate = new Date();
         if (Expiration != null)
            ExpDate.setDate(ExpDate.getDate() +
                            Expiration);
            
         // Encode the data for storage.
         var CookieValue = escape(Value) +
            "; expires=" + ExpDate.toUTCString();
            
         // Store the cookie.
         document.cookie = Name + "=" + CookieValue;
      }
      
      function GetCookie(Name)
      {
         var Cookies=document.cookie.split(";");
         for (var i=0; i<Cookies.length; i++)
         {
            // Obtain the name of the cookie.
            var CName = Cookies[i].substr(0,Cookies[i].indexOf("="));
            var CValue = Cookies[i].substr(Cookies[i].indexOf("=") + 1);
            CName = CName.replace(/^\s+|\s+$/g, "");
            if (Name == CName){
               return unescape(CValue);
            }
         }
         return null;
      }
      function CheckName()
      {
         var UserName = GetCookie("Username");
         if ((UserName == null) || (UserName == "")){
            UserName = prompt("Please type your name: ");
            SetCookie("Username", UserName, 365);
         }else{
            UserName = "Back " + UserName;
         }
         
         // Display the user's name on screen.
         var SetName = document.getElementById("Name");
         SetName.innerHTML = UserName;
      }
   </script>
</head>

<body onload="CheckName()">
   <h1>Working with Cookies</h1>
   <p>Welcome <span id="Name"></span></p>
</body>
</html>



PreviousNext

Related