Getting and setting Cookies via JavaScript feels a little odd like this:
Set: document.cookie = \"
You can use some simple functions like setCookie()
and getCookie()
.
You can set a cookie using the call:
setCookie('myName','value', 3);
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Note: Source is from quirksmode. Please have a look at the docs if you want to know more about cookies.
ES6 approach is:
const setCookie = (cookieKey, cookieValue, expirationDays) => {
let expiryDate = '';
if (expirationDays) {
const date = new Date();
date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`);
expiryDate = `; expiryDate=" ${date.toUTCString()}`;
}
document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`;
}
const getCookie = (cookieKey) => {
let cookieName = `${cookieKey}=`;
let cookieArray = document.cookie.split(';');
for (let cookie of cookieArray) {
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(cookieName) == 0) {
return cookie.substring(cookieName.length, cookie.length);
}
}
}