0
3.0kviews
Write a code in JavaScript to set a cookie.
1 Answer
written 6.3 years ago by |
document.cookie
property.document.cookie = "username=abc xyz";
document.cookie = "username=abc xyz; expires=Thu, 29 feb 2013 12:00:00 UTC";
document.cookie = "username=abc xyz; expires=Thu, 29 feb 2013 12:00:00 UTC; path=/";
JavaScript Cookie Example
First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
Then, we create a function that returns the value of a specified cookie:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
(cname + "=")
.ca (ca = decodedCookie.split(';')).
ca array (i = 0; i < ca.length; i++),
and read out each value c = ca[i]).
(c.indexOf(name) == 0),
return the value of the cookie (c.substring(name.length, c.length).
If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }