Могу предложить свой API по работе с Cookie:
var Cookie = {
_params: {
domain: '',
path: '/',
expires: '',
maxAge: -1,
sameSite: false,
secure: false
},
_lastCookie: '',
setDefaultParams (params) {
this._params = {...this._params, ...params};
},
getDefaultParams () {
return this._params;
},
getLastCookie () {
return this._lastCookie;
},
set (key, value, params={}) {
value = encodeURIComponent(value);
params = {...this._params, ...params};
if (params.expires) {
if (params.expires instanceof Date) {
params.expires = params.expires.toUTCString();
} else if (typeof params.expires === 'string') {
const date = new Date(params.expires);
params.expires = date.toUTCString();
}
}
let cookie = `${key}=${value};`;
cookie += params.path ? ` Path=${params.path};` : '';
cookie += params.domain ? ` Domain=${params.domain};` : '';
cookie += params.expires ? ` Expires=${params.expires};` : '';
cookie += params.maxAge > -1 ? ` Max-Age=${params.maxAge};` : '';
cookie += params.sameSite !== false ? ` SameSite=${params.sameSite};` : '';
cookie += params.secure === true ? ` Secure;` : '';
this._lastCookie = cookie;
document.cookie = cookie;
return true;
},
has (key) {
return this.getAll().hasOwnProperty(key);
},
get (key) {
return this.getAll()[key];
},
getAll () {
const cookies = {};
this.getString().split(';').forEach(val => {
const params = val.split('=').map(el => el.trim());
cookies[params[0]] = params[1];
});
return cookies;
},
getString () {
return document.cookie;
},
delete (key) {
if (!this.has(key)) return false;
return this.set(key, '', { expires: 'Thu, 01 Jan 1970 00:00:01 GMT', maxAge: 0 });
}
};
if (!Cookie.has('key')) {
if (confirm('Are you want to save a cookie?')) {
Cookie.set('key', true, { expires: '2022-12-01T00:00:00' });
}
} else {
if (confirm('Are you want to delete a cookie?')) {
Cookie.delete('key');
}
}