Reading cookies in javascript
Reading cookies in javascript
Because the cookie is the value of the document.cookie object, reading a cookie is as straightforward as creating one. This string may be used to access the cookie at any time. The string has a list of name=value pairs separated by semicolons, where name is the cookie name and value is the string value.
Cookies may be read in JavaScript using the following syntax: 1 var x = document.cookie; Example: By giving the cookie name, you can simply read the cookie using the below method.
var ca = document.cookie.split(';');
/processing to obtain the content 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(nameEQ) == 0) {
//returning actual content
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
Example: Using a cookie to store the user's name.
if (cookies == 'yes') {
jQuery('document').ready(function () {
//reading cookie
var cook = readCookie('YourWebsite');
if (cook != 'true') {
If the cookie isn't discovered, it'll be created.
createCookie('YourWebsite', 'user_name=akash', 30);
}
});
}