October 8, 2011

Javascript to set cookies and get hold of a specific cookie

Write Javascript code to store a cookie and retrieve it - also check if cookies are enabled on the client.

Solution

<html>
<head>
<script type="text/javascript">

var cookieFunction = function() {
   
if (navigator.cookieEnabled) {
var name = prompt("Enter cookie name");
      var value= prompt("Enter cookie value");
      if ((name) && (value)) {
         var date = new Date("1 Jan 2015 11:30:00");
         document.cookie= name + "="+value+"; expires="+date.toGMTString()+";";
      }
   } else {
      alert("Cookies Not enabled");
   }
}

var getCookie = function() {
   var cookies=document.cookie;
   alert(cookies);
}

var getSpecificCookie = function() {
   var c_name = prompt("Enter cookie name");
   var all_cookies = document.cookie.split( ';' );
   for (i=0;i<all_cookies.length;i++) {
      x = all_cookies[i].substr(0, all_cookies[i].indexOf("="));
      y = all_cookies[i].substr(all_cookies[i].indexOf("=")+1);
      x = x.replace(/^\s+|\s+$/g,"");
      if (x == c_name) {
        alert( unescape(y));
        return;
     }
   }

   alert("Cookie does not exist");
}

window.onload = function() {
   document.getElementById("getCookieButton").onclick=getCookie;
   document.getElementById("getSpecificCookieButton").onclick=getSpecificCookie;
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="cookieButton">Set Cookie</button>
<button id="getCookieButton">Get Cookies</button>
<button id="getSpecificCookieButton">Get Specific Cookie</button>

</body>
</html>

No comments:

Post a Comment