Techcss
Javascript_page_menu

JavaScript Cookies

Cookie is a method of storing information of the pages visited by the user and restore those when recalled them by the user on the same browser.


The purpose of the cookie

The main purpose of the cookies is to maintain the state of the client and to know the user's previous actions on the page.


Set-Cookie

When the user requests a page for the first time, a cookie is stored in the browser using the Set-Cookie entry in the header of the response from the server. The entry includes information to be stored in the cookie along with expiry date for the cookie, path, server information to be stored in the cookie along with expiry date for the cookie, path, server information and security. In future, when the user requests a page, if a matching cookie is found, the browser sends a cookie field to the server in a request header. The set-cookie be expressed as following:

Set-Cookie: name=VALUE;expires=DATE;path=PATH;domain=DOMAIN;secure

The attributes for the Set-Cookie field
Attribute Name Description
expires = DATE Specifies the expiry date for the cookie. The cookie will not reside in the server or the client browser after the expiry date.
Path=PATH Specifies the path of the URLs for which the cookie is valid.
Domain=DOMAIN Specifies the domain portion of URLs for which the cookie is valid.
Secure Specifies that the cookie should be transmitted only over a secure link.

EXAMPLE:

<html>
<body>
<script>
 function cook(field)
{
document.cookie=field;
}
var thiscook = ((document.cookie != "") && (document.cookie !=null));
var cname = (thiscook)?document.cookie:"Hello";
alert(cname);
</script>
<form method=POST>
<input type =text size=15 value ="Example of Cookie" onFocus="this.blur();">
<br><br>Cookie Value:<input type=text size=15 onChange="cook(this.value);">
</body>
</html>