Cookies are basically a storage facility of web browsers. It comes under the Web Storage of a browser which is a local or client storage facility. The data are in the browser even after the browser window is closed in many websites there is need of remembering session information, such as, when we log in to email, Facebook, etc many time from the same PC, also in another commercial site, for cookies we can log in easily in that sessions, also we are logged in for a time limit whether the browser was close all the time when we use that sites. Cookies are use in JavaScript using cookie property of Document object. This property is readable and writable both.
A cookie is an old technology used in web browsers as client-side storage which works by server-side scripting languages like ASP, PHP, etc. Cookies can be created, modified, and also accessed. Cookies were the part of CGI (Common Gateway Interface) programming, cookies are used CGI to transmit data between browser and server.
Working of Cookies: Cookies is stored as text like data in the local storage of a browser. Cookies are the data that sends from the server-side, with the information of visitors on any web page or website, and store them to the hard disk when the visitor leaves the web page. And after in the future when the visitor again visits the web site then the cookies are retrieved from the client-side and send a request with the cookies to the server-side, and the server remembers what was stored earlier. Cookies have some attribute by which the data or information are stored.
- Name & value: This the main mandatory thing of cookies. It is the main value of the session which is the store and retrieves during visiting in the web sites as key-value pair.
- Domain: Domain is the website’s domain in which we are surfing. It is not a mandatory thing, it does not need to declare the domain when writing the cookies. It can be declared by default by the web browser.
- Path: Path is nothing but the website, we are surfing. it also can be set by default by the web browser.
- Expires: It the attribute which define expiration time of the saved cookies. If it’s not declared at the time of setting the cookie, then the cookie will expire when the browser close.
- Secure: This field contains only one word, name as “secure”, if its blank then the cookies are retrieved in any non-secure server, but if the field is not blank then the cookies are retrieved only insecure server.
Some syntax of accessing cookie property in JavaScript:
- Writing cookie:
// For normal use without the optional fields document.cookie = "name= value";
- or
// For all the fields document.cookie = "name= value; expires=date; domain=domain_name; path=website_name; secure";
- Reading cookie: Cookies can be read using many ways, see below-
var cookieVal=document.cookie;
- or
console.log(document.cookie);
- or
alert(document.cookie);
Examples: Below is the examples of all the task can be performed on the cookies.
- Writing cookies: In this program we will be writing cookies.
javascript
<!DOCTYPE html> <html> <head> <title>neveropen</title> <script type= "text/javascript" > // Function to setting cookies function setCookies() { // Using cookie property cookieVal = document.cookieFrm.nameVal.value + ";" ; document.cookie = "name = " + cookieVal; } // Function to reading cookies function showCookies() { // Display the cookie value when pressing // the "showCookies" button document.getElementById( "ShowC" ).innerHTML = ( "Cookie value = " + cookieVal); } </script> </head> <body> <div style= "background-color:#7FFF00; width: 50%;" > <h2 style= "color:#006400;" >Writing Cookies</h2> <form action= "" name= "cookieFrm" > <!-- Write a value to store a cookie in Name box --> Name: <input type= "text" name= "nameVal" /> <br> <br> <!--Button for set cookies--> <input type= "button" value= "Set Cookie" onclick= "setCookies();" /> <!--Button for show cookies--> <input type= "button" value= "Show Cookie" onclick= "showCookies();" /> </form> <span id= "ShowC" > </span> <!--after the press the show cookie button the value of the cookie will appear here--> </div> </body> </html> |
- Output:
- Reading cookies: In this program we will be Reading cookies.
javascript
<!DOCTYPE html> <html> <head> <title>neveropen</title> <script type= "text/javascript" > // Function to setting cookies function setCookies() { document.cookie = "name = " + document.cookieFrm.nameVal.value + ";" ; document.cookie = "class = " + document.cookieFrm.cls.value + ";" document.cookie = "subject = " + document.cookieFrm.sub.value + ";" } //Function to reading cookies function showCookies() { var arrCookie = document.cookie.split( ";" ); /* To store the cookie value in an array separately here use "split()" method, which splits the values where ";" is located, such as arrCookie[0]="name=neveropen" arrCookie[1]="class=3rd year" */ for ( var i = 0; i < arrCookie.length; i++) { var valArr = arrCookie[i].split( "=" ); /* here "valArr" is use to store the actual value of a particular cookie field, such as valArr[0]=name valArr[1]=neveropen */ if (valArr[0].trim() == 'name' ) /* The "trim()" is used for remove unwanted white spaces, otherwise there maybe some mismatch in the values search for "name" */ { document.cookieFrm.nameVal.value = valArr[1]; } if (valArr[0].trim() == 'class' ) { document.cookieFrm.cls.value = valArr[1]; } if (valArr[0].trim() == 'subject' ) { document.cookieFrm.sub.value = valArr[1]; } } } </script> </head> <body> <div style= "background-color:#7FFF00; width: 50%;" > <h2 style= "color:#006400;" >Reading Cookies</h2> <form action= "" name= "cookieFrm" > <!--write value to store as cookie in Name box--> Name: <input type= "text" name= "nameVal" /> <br> <br> Class: <input type= "text" name= "cls" /> <br> <br> Subject: <input type= "text" name= "sub" /> <br> <br> <!-- Button for set cookies--> <input type= "button" value= "Set Cookie" onclick= "setCookies();" /> <!-- Button for show cookies--> <input type= "button" value= "Restore previous value using Cookie" onclick= "showCookies();" /> </form> <span id= "ShowC" > </span> </div> </body> </html> |
- Output:
Note: In the both example we can use escape() and unescape() method for write and read the cookie value respectively. The cookie value may not contain spaces or special character like semi-colon(;), in this case the we cannot separate the values of the cookies for store them so if we use those two method then this problems will be solve. The escape() is use when store the cookie values and unescape() is use when retrieving the cookie values. Just put the statement in escape() and unescape() method like below-
escape(document.cookieFrm.nameVal.value)
unescape(document.cookie)
Update and Delete existing cookies: Updating a cookie value is very easy, that replace the previous value with a new value. But delete a cookie value its not easy as update, but its also a easy thing. A cookie value is deleted automatically when expiration time of the cookie is reached. But if we want to delete a cookie value before the expiration, then we have to replace the expire field with a past date and time, then the cookie will delete.
- Updating cookies: In this program we will be Updating cookies.
javascript
<!DOCTYPE html> <html> <head> <title>neveropen</title> <script type= "text/javascript" > // Function to setting cookies function setCookies() { cookVal = "name = " + escape(document.cookieFrm.nameVal.value) + ";" ; document.cookie = cookVal; document.getElementById( "ShowC" ).innerHTML = ( "Cookie value : <br>" + document.cookie); } // Function to update cookies function updateCookies() { // Updating the cookie value upCoo = "name = " + escape(document.cookieFrm.updateCoo.value) + ";" ; document.cookie = upCoo; // Showing updated cookie value document.getElementById( "ShowCC" ).innerHTML = ( "<br><br>Updated Cookie value : <br>" + document.cookie); } </script> </head> <body> <div style= "background-color:#7FFF00; width: 60%;" > <h2 style= "color:#006400;" >Update Cookies</h2> <form action= "" name= "cookieFrm" > Enter a value to store: <input type= "text" name= "nameVal" /> <br> <br> Enter a value to update: <input type= "text" name= "updateCoo" /> <br> <br> <!-- Button for set cookies--> <input type= "button" value= "Set Cookie" onclick= "setCookies();" /> <input type= "button" value= "Update existing Cookie" onclick= "updateCookies();" /> </form> <span id= "ShowC" > </span> <span id= "ShowCC" > </span> </div> </body> </html> |
- Output:
- Deleting cookies: In this program we will be Deleting cookies.
javascript
<!DOCTYPE html> <html> <head> <title>neveropen</title> <script type= "text/javascript" > // Setting cookies function setCookies() { cookVal = "name = " + escape(document.cookieFrm.nameVal.value) + ";" ; document.cookie = cookVal + "expires = Sun, 01-May-2021 14:00:00 GMT" ; // Add expiration date &print the cookie value document.getElementById( "ShowC" ).innerHTML = ( "Cookie value : <br>" + document.cookie); } // Function to setting cookies function dltCookies() { document.cookie = cookVal + "expires = Sun, 01-May-2019 14:00:00 GMT" ; // Change the expiration date document.getElementById( "ShowC" ).innerHTML = ( "After delete, Cookie value : <br>" + document.cookie + "<br>" ); } </script> </head> <body> <div style= "background-color:#7FFF00; width: 55%;" > <h2 style= "color:#006400;" > Update & Delete Cookies </h2> <form action= "" name= "cookieFrm" > enter a cookie value: <input type= "text" name= "nameVal" /> <br> <br> <input type= "button" value= "Set Cookie" onclick= "setCookies();" /> <input type= "button" value= "Delete Cookie" onclick= "dltCookies();" /> </form> <span id= "ShowC" > </span> <span id= "ShowCC" > </span> </div> </body> </html> |
- Output: