What are Cookies?
Cookies are stored in small text files, on your computer i.e., cookies are the data.
To create a cookie in javascript let us look at the code below :
document.cookie="username= Ramesh";
whenever a browser request a server for the web page it always bind the cookies to the request.
JavaScripts can create, delete and read the cookies with the property document.cookie. we can add the expiry date to the cookies as :
document.cookie="username=Ramesh; expires=Thu, 24 Dec 2016 12:00:00 UTC";
By default, the cookie is deleted when the browser is closed:
We can also read the cookies as :
var x = document.cookie;
Same way we can use these properties and create functions that sets, read, delete the cookies like
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
0 Comment(s)