-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathez-consent.js
More file actions
325 lines (324 loc) · 11.4 KB
/
Copy pathez-consent.js
File metadata and controls
325 lines (324 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* global document, location, window */
export const ez_consent = (() => {
const mergeCssClassNames = (...classNames) => classNames.join(' ');
const defaultOptions = {
is_always_visible: false,
privacy_url: '/privacy',
enable_google_consent_mode: false,
consent_duration: 'P10Y',
more_button: {
target_attribute: '_blank',
is_consenting: true,
},
texts: {
main: 'This website uses cookies & similar.',
buttons: {
ok: 'ok',
more: 'more',
},
},
css_classes: {
container: 'cookie-consent',
message_text: 'cookie-consent__text',
buttons: {
wrapper: 'cookie-consent__buttons',
more: mergeCssClassNames(
'cookie-consent__button',
'cookie-consent__button--more',
'cookie-consent__buttons-button', // Legacy (for backwards compatibility with ≤ 1.2.X)
'cookie-consent__buttons__read-more', // Legacy (for backwards compatibility with ≤ 1.2.X)
),
ok: mergeCssClassNames(
'cookie-consent__button',
'cookie-consent__button--ok',
'cookie-consent__buttons-button', // Legacy (for backwards compatibility with ≤ 1.2.X)
'cookie-consent__buttons__close', // Legacy (for backwards compatibility with ≤ 1.2.X)
),
},
},
};
const ui = (() => {
const baseCssClassNames = {
container: 'cookie-consent',
hidden: mergeCssClassNames(
'cookie-consent--hidden',
'cookie-consent__hide', // Legacy (for backwards compatibility with ≤ 1.2.X)
),
};
const baseCss = `
.${baseCssClassNames.container} { z-index: 9999; }
.${baseCssClassNames.hidden} { display:none !important; }
`;
function initializeHtml(options) {
return `
<div class="${options.css_classes.container} ${baseCssClassNames.container} ${baseCssClassNames.hidden}">
<div class="${options.css_classes.message_text}">${options.texts.main}</div>
<div class="${options.css_classes.buttons.wrapper}">
<div class="${options.css_classes.buttons.more}">
<a href="${options.privacy_url}" target="${options.more_button.target_attribute}">${options.texts.buttons.more}</a>
</div>
<div class="${options.css_classes.buttons.ok}">${options.texts.buttons.ok}</div>
</div>
</div>
`;
}
function getElements(options) {
const selectElementByClassNames = (classNames) => {
const elements = document.getElementsByClassName(classNames);
if (elements.length === 0) {
throw new Error(`No elements found for query: ${classNames}`);
}
if (elements.length > 1) {
throw new Error(`Multiple elements found for query: ${classNames}`);
}
return elements[0];
};
return {
container: selectElementByClassNames(options.css_classes.container),
buttons: {
more: selectElementByClassNames(options.css_classes.buttons.more),
ok: selectElementByClassNames(options.css_classes.buttons.ok),
},
};
}
function registerClickHandler(element, handler) {
element.addEventListener('click', () => {
handler();
});
}
return {
injectHtmlAsync: (options) =>
new Promise((resolve) => {
const html = initializeHtml(options);
document.addEventListener(
'DOMContentLoaded', // Wait until "document.body" is ready to ensure this is the first element inserted
() => {
document.body.insertAdjacentHTML('afterbegin', html);
resolve();
},
);
}),
injectCss: () => {
const style = document.createElement('style');
style.textContent = baseCss;
document.head.append(style);
},
showElement: (options) => {
getElements(options).container.classList.remove(...baseCssClassNames.hidden.split(' '));
},
delete: (options) => {
getElements(options).container.remove();
},
onOkButtonClick: (options, handler) =>
registerClickHandler(getElements(options).buttons.ok, handler),
onReadMoreButtonClick: (options, handler) =>
registerClickHandler(getElements(options).buttons.more, handler),
};
})();
const consentCookies = (() => {
const consentCookieName = 'cookie-consent';
function parseISO8601DurationToDate(duration) {
// Standard: https://en.wikipedia.org/wiki/ISO_8601#Durations
if (!duration || typeof duration !== 'string') {
throw new Error(`Expected ISO-8601 duration string, got ${typeof duration}: ${duration}`);
}
if (!duration.startsWith('P')) {
throw new Error(`Invalid ISO-8601 duration: Missing 'P' at start: ${duration}`);
}
if (duration.toUpperCase() !== duration) {
throw new Error(`Invalid ISO-8601 duration: Must use uppercase letters only: ${duration}`);
}
duration = duration.substring(1); // Remove P
let hasSeenT = false;
let currentNumberText = '';
let isDateExtracted = false;
const date = new Date();
const unitHandlers = {
Y: (value) => date.setFullYear(date.getFullYear() + value),
M: (value) => {
// M can be month or minutes
if (hasSeenT) {
date.setMinutes(date.getMinutes() + value);
return;
}
date.setMonth(date.getMonth() + value);
},
W: (value) => date.setDate(date.getDate() + value * 7),
D: (value) => date.setDate(date.getDate() + value),
H: (value) => date.setHours(date.getHours() + value),
S: (value) => date.setSeconds(date.getSeconds() + value),
};
for (const char of duration) {
if (char === 'T') {
hasSeenT = true;
if (currentNumberText) {
throw Error(
`Number ${currentNumberText} without unit before T in duration text: ${duration}`,
);
}
continue;
} else if (char === ',' || char === '.') {
throw new Error(
`Decimal values are not supported in ISO-8601 durations: "${char}" in "${duration}"`,
);
} else if (['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(char)) {
currentNumberText += char;
continue;
} else if (currentNumberText) {
const value = parseFloat(currentNumberText);
const handler = unitHandlers[char];
if (handler) {
unitHandlers[char](value);
isDateExtracted = true;
currentNumberText = '';
continue;
}
}
throw new Error(
`Invalid character '${char}' in ISO-8601 duration. Expected Y, M, W, D, H, or S designators: ${duration}`,
);
}
if (!isDateExtracted) {
throw new Error(
`Invalid ISO-8601 duration: No valid duration components (Y, M, W, D, H, S) found in: ${duration}`,
);
}
return date;
}
const getCookie = () => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${consentCookieName}=`);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
return undefined;
};
const setCookie = (options) => {
const cookieParts = [];
cookieParts.push(`${consentCookieName}=dismissed`);
const date = parseISO8601DurationToDate(options.consent_duration);
cookieParts.push(`expires=${date.toUTCString()}`);
cookieParts.push('path=/');
cookieParts.push(`domain=${location.hostname.replace(/^www\./i, '')}`);
const cookie = `${cookieParts.join('; ')};`;
document.cookie = cookie;
};
return {
getCookie,
setCookie,
};
})();
const googleConsent = (() => {
// Guidance: https://support.google.com/analytics/answer/10000067?hl=en
const pingGoogle = (
consent_arg, // 'default' or 'update', see: https://web.archive.org/web/20250228180948/https://developers.google.com/tag-platform/gtagjs/reference#consent
) => {
function gtag() {
window.dataLayer.push(arguments);
}
gtag('consent', consent_arg, {
// Parameters: https://web.archive.org/web/20250228172407/https://support.google.com/tagmanager/answer/13802165?hl=en
ad_storage: 'granted',
ad_user_data: 'granted',
ad_personalization: 'granted',
analytics_storage: 'granted',
functionality_storage: 'granted',
personalization_storage: 'granted',
security_storage: 'granted',
});
};
return {
// Guidance:
initialize: (options) => {
if (!options.enable_google_consent_mode) {
return;
}
window.dataLayer = window.dataLayer || [];
if (isConsentGranted()) {
pingGoogle('update');
} else {
pingGoogle('default');
}
},
notifyConsentGranted: (options) => {
if (!options.enable_google_consent_mode) {
return;
}
pingGoogle('update');
},
};
})();
function onUserConsentGranted(options) {
consentCookies.setCookie(options);
ui.delete(options);
googleConsent.notifyConsentGranted(options);
}
async function onInitialization(options) {
googleConsent.initialize(options);
if (shouldShowBanner(options)) {
await initializeUi(options);
}
}
async function initializeUi(options) {
await ui.injectHtmlAsync(options);
ui.injectCss();
ui.showElement(options);
ui.onOkButtonClick(options, () => {
onUserConsentGranted(options);
});
if (options.more_button.is_consenting) {
ui.onReadMoreButtonClick(options, () => {
onUserConsentGranted(options);
});
}
}
function shouldShowBanner(options) {
if (
options.is_always_visible ||
options.always_show /* for backwards compatibility in 1.X.X */
) {
return true;
}
const queryParamToShow = 'force-consent';
if (new RegExp(`[?&]${queryParamToShow}`).test(location.search)) {
return true;
}
return !isConsentGranted();
}
function isConsentGranted() {
const cookie = consentCookies.getCookie();
return cookie !== undefined;
}
function fillDefaults(options) {
return objectAssignRecursively(defaultOptions, options || {});
function objectAssignRecursively(target, ...sources) {
// This is implemented because `Object.assign does` not assign nested objects
// `options = {...defaults, ...options}` works, but it is not supported in
// older JavaScript versions:
// not polyfilled by closure compiler
// `babel-plugin-proposal-object-rest-spread` just runs `Object.assign` which
// does not work with nested objects
sources.forEach((source) => {
Object.keys(source).forEach((key) => {
const sourceValue = source[key];
const targetValue = target[key];
target[key] =
targetValue &&
sourceValue &&
typeof targetValue === 'object' &&
typeof sourceValue === 'object'
? objectAssignRecursively(targetValue, sourceValue)
: sourceValue;
});
});
return target;
}
}
async function initializeAsync(options) {
const completeOptions = fillDefaults(options);
await onInitialization(completeOptions);
}
return {
init: (options) => initializeAsync(options),
};
})();