Cookies:
Cookies
suggest changeAdding 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.
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
1
Comments
8
Strings
11
Arrays
12
Objects
14
Classes
16
Map
17
Set
23
Conditions
24
Loops
25
Functions
27
Date
29
Scope
30
AJAX
31
Promises
34
Geolocation
35
Cookies
37
Generators
39
Strict mode
41
JSON
42
Binary Data
43
Web Storage
44
Fetch
45
Modules
46
Screen
47
Inheritance
48
Timestamps
50
Web Worker
51
Debugging
53
WebSockets
64
Console
67
Enumerations
68
Symbols
69
Localization
71
Callbacks
73
Modals
75
Event Loop
76
Events
79
Unit Testing
82
IndexedDB
86
Proxy
89
WeakMap
90
WeakSet
94
Namespacing
98
Context this
100
Vibration API
101
Fluent API
102
Tilde
103
Security issues
105
Contributors