MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Cookies

Test if cookies are enabled

If you want to make sure cookies are enabled before using them, you can use navigator.cookieEnabled:


if (navigator.cookieEnabled === false)
{
 alert("Error: cookies not enabled!");
}

Note that on older browsers navigator.cookieEnabled may not exist and be undefined. In those cases you won't detect that cookies are not enabled.

Adding and Setting Cookies

The following variables set up the below example:


var COOKIE_NAME = "Example Cookie"; /* The cookie's name. */
var COOKIE_VALUE = "Hello, world!"; /* The cookie's value. */
var COOKIE_PATH = "/foo/bar"; /* The cookie's path. */
var COOKIE_EXPIRES; /* The cookie's expiration date (config'd below). */
/* Set the cookie expiration to 1 minute in future (60000ms = 1 minute). */
COOKIE_EXPIRES = (new Date(Date.now() + 60000)).toUTCString();
document.cookie +=
 COOKIE_NAME + "=" + COOKIE_VALUE
 + "; expires=" + COOKIE_EXPIRES
 + "; path=" + COOKIE_PATH;

Reading cookies

var name = name + "=",
 cookie_array = document.cookie.split(';'),
 cookie_value;
for(var i=0;i<cookie_array.length;i++) {
 var cookie=cookie_array[i];
 while(cookie.charAt(0)==' ')
 cookie = cookie.substring(1,cookie.length);
 if(cookie.indexOf(name)==0)
 cookie_value = cookie.substring(name.length,cookie.length);
 }

This will set cookie_value to the value of the cookie, if it exists. If the cookie is not set, it will set cookie_value to null


Removing cookies


var expiry = new Date();
expiry.setTime(expiry.getTime() - 3600);
document.cookie = name + "=; expires=" + expiry.toGMTString() + "; path=/"

This will remove the cookie with a given name.



Conclusion

In this page (written and validated by ) you learned about Javascript Cookies . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Timestamps.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.