Skip to content
Snippets Groups Projects

3525019-new-js-cookie-jsdelivr/Philip: Deprecate, remove, and replace...

1 unresolved thread
2 files
+ 51
14
Compare changes
  • Side-by-side
  • Inline
Files
2
(function ($, Drupal, Cookies, once) {
(function ($,Drupal, once) {
'use strict';
/**
* Convert document.cookie string to JSON object.
*
* @returns {Object}
*/
function cookieToJSON() {
return Object.fromEntries(
document.cookie.split('; ')
.map(cookie => cookie.split('='))
.map(([key, value]) => [key, decodeURIComponent(value)])
);
}
/**
* Set a cookie with given name, value and optional days until expiration.
*
* @param {string} name
* The cookie name.
* @param {string} value
* The cookie value.
* @param {number} [days]
* Optional number of days until cookie expires.
*/
function setCookie(name, value, days) {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = `; expires=${date.toUTCString()}`;
}
document.cookie = `${name}=${encodeURIComponent(value)}${expires}; path=/`;
Please register or sign in to reply
}
/**
* Read cookie data.
*
@@ -10,9 +43,14 @@
* @returns {any}
*/
function readCookieData(name) {
let cookieData = Cookies.get(name);
const cookies = cookieToJSON();
let cookieData = cookies[name] || null;
if (typeof cookieData === "string") {
return JSON.parse(cookieData);
try {
return JSON.parse(cookieData);
} catch (e) {
return cookieData;
}
}
return cookieData;
}
@@ -20,26 +58,26 @@
/**
* Merge cookie data.
*
* @param name
* @param {string} name
* The cookie name.
* @param data
* @param {*} data
* The cookie data.
*/
function mergeCookieData(name, data) {
let cookieData = readCookieData(name) || [];
let mergedData = $.merge([data], cookieData);
Cookies.set(
name,
JSON.stringify(mergedData.filter(function (element, index, self) {
return index === self.indexOf(element);
}))
);
// Remove duplicates and store
const uniqueData = mergedData.filter(function (element, index, self) {
return index === self.indexOf(element);
});
setCookie(name, JSON.stringify(uniqueData), 365); // Set cookie to expire in 1 year
}
Drupal.behaviors.notificationMessage = {
attach: function (context) {
once('notificationMessage', 'html', context).forEach(function () {
let cookieData = readCookieData('notificationMessagesClosed') || [];
$('.notification-messages .message').each(function () {
@@ -81,4 +119,4 @@
}
}
}(jQuery, Drupal, window.Cookies, once));
}(jQuery, Drupal, once));
Loading