Is there some classes in JS to work with cookie? Something like…
let foo = Cookie.get('foo');
Is there some classes in JS to work with cookie? Something like…
let foo = Cookie.get('foo');
Hi @igor_g, the DOM only has document.cookie
to work with, but you might have a look at the js-cookie
library for a more convenient way.
And if you are wanting a simpler way, there are some fundamental cookie-handling functions at https://snipplr.com/view/45954/cookie-handling-functions
Hi @Paul_Wilkins. There is no problem to write self-made parser for cookie. But I’ve hoped on standard JS feature.
JavaScript has no built-in features for handling cookies.
The above code that I posted is the closest to “official” cookie-handling code that you’ll come across, because it’s a cleaned-up version of code that comes from Quirksmode, who investigated all of the corner cases that existed in JavaScript.
I would clean the code up even further these days, using JSLint to tidy it up to the following code instead:
function createCookie(name, value, days) {
var expires = "";
var date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var allCookies = document.cookie.split(";");
allCookies.forEach(function (cookie) {
while (cookie.charAt(0) === " ") {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
});
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Actually, as I know, cookie attribute expires
yet deprecated due max-age
. Is that correct for all current browsers?
I wasn’t aware that any part of it has been or will be deprecated. Can you please give further details about that?
According to caniuse.com, both are still supported, though max-age has less support than expires.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.