A Cookie is nothing but a small text file that’s stored in your browser. It contains some data such as:
- A name value pair containing the actual data.
- An expiry date after which it is no longer valid.
- . The domain and path of the server it should be sent to.
We can use Cookie:
- State Maintenance/Persistence across different pages of the site, for Http is a state less protocol which means after sending any web page server forget which page he sent.
- To allow user-side customization of web information, to serve a personalized site.
In this demonstration we learn how to create cookie, delete cookie and read cookie.
Creating cookie
function createCookie() {
var date = new Date();
var days = 1;
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = "ck1" + "Hello Dear" + date.toGMTString();
document.write("Cookie created successfully.");
}
Reading Cookie
function readCookie() {
var cookName = "ck1" + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.subString(1, c.length);
if (c.indexOf(cookName) == 0)
document.write(c.subString(cookName.length , c.length);
}
}
Anonymous User
08-Apr-2019Thanks for the post.