JavaScript Cookies

As HTTP is stateless protocol i.e. all request to the server are treated as a new request and there in no way determine if a request comes from a user which already did a request before or it is a new user.

A cookie is a small piece of information that the server stores at client browser to recognize the user in future. A cookie is sent every time, the same client sends request to the server. JavaScript facilitates the features of both creating and retrieving cookie values.

How cookies works in JavaScript?

When a request comes to server. Application can attach a small information call cookie in response. If clients browser accept the cookie then it stores this information on clients machine as a plain text. When client sends a new request browser will attach this information to the server with request. Application can retrieve the cookie and can identify the user or client.

Restrictions of cookies

  • A cookie can store maximum 4 kb of data.
  • Cookies are specific to the domain.
  • A browser can store max 20 cookies per domain.

To Create a Cookie:

document.cookie = "key = value";

To Retrieve a Cookie:

document.cookie

Example:

<!DOCTYPE html>  
	<html>  
	<head>  
	</head>  
	<body>  
	<input type="button" value="set" onclick="setCookie()">  
	<input type="button" value="get" onclick="getCookie()">  
    	<script>  
    	function setCookie()  
         {  
          document.cookie="username=John Miller";  
         }  
        function getCookie()  
        {  
          if(document.cookie.length!=0)  
           {  
            var array=document.cookie.split("=");  
            alert("Name="+array[0]+" "+"Value="+array[1]);  
           }  
          else  
          {  
           alert("No cookie available");  
          }  
         }  
    	</script>  
 
	</body>  
	</html>

Related Topics

Please Share