-
Notifications
You must be signed in to change notification settings - Fork 18
/
cookieman.js
493 lines (453 loc) · 17.4 KB
/
cookieman.js
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// requires: js.cookie
/** global: Cookies */
var cookieman = (function () {
"use strict";
// remember: write IE11-compatible JavaScript
var cookieName = 'CookieConsent',
cookieLifetimeDays = 365,
form = document.querySelector('[data-cookieman-form]'),
settingsEl = document.querySelector('[data-cookieman-settings]'),
eventsEl = settingsEl,
settings = JSON.parse(settingsEl.dataset.cookiemanSettings),
checkboxes = form.querySelectorAll('[type=checkbox][name]'),
saveButtons = document.querySelectorAll('[data-cookieman-save]'),
acceptAllButtons = document.querySelectorAll('[data-cookieman-accept-all]'),
acceptNoneButtons = document.querySelectorAll('[data-cookieman-accept-none]'),
injectedTrackingObjects = [],
loadedTrackingObjectScripts = {}
function saveSelections() {
var consented = []
for (var _i = 0; _i < checkboxes.length; _i++) {
if (checkboxes[_i].checked) {
consented.push(checkboxes[_i].name)
}
}
Cookies.set(
cookieName,
consented.join('|'),
{expires: cookieLifetimeDays, sameSite: 'lax'}
)
}
function setChecked(checkbox, state) {
checkbox.checked = state
}
function selectNone() {
for (var _i = 0; _i < checkboxes.length; _i++) {
var _checkbox = checkboxes[_i]
if (!_checkbox.disabled) { // exclude disabled (problably preselected) ones
setChecked(_checkbox, false)
}
}
}
function selectAll() {
for (var _i = 0; _i < checkboxes.length; _i++) {
setChecked(checkboxes[_i], true)
}
}
function hasConsented(groupKey) {
var consented = consentedSelectionsRespectDnt()
for (var i = 0; i < consented.length; i++) {
if (consented[i] === groupKey) {
return true
}
}
return false
}
/**
* Checks if consent was given for all groups, in which a trackingObject
* with the given key is defined. Normally each trackingObject should only
* be present in one group.
*
* @param trackingObjectKey string e.g. 'Matomo'
* @return boolean consent given for all groups. If the trackingObject is
* not defined in any group, this function will return false
*/
function hasConsentedTrackingObject(trackingObjectKey) {
var groups = findGroupsByTrackingObjectKey(trackingObjectKey)
return groups.reduce(
function (consentGiven, groupKey) {
return consentGiven && hasConsented(groupKey)
},
groups.length > 0
)
}
function consentedSelectionsAll() {
var cookie = Cookies.get(cookieName)
return cookie ? cookie.split('|') : []
}
function consentedSelectionsRespectDnt() {
return consentedSelectionsAll().filter(
function (consented) {
var aGroup = settings.groups[consented]
if (typeof aGroup === 'undefined') {
return false
}
return !aGroup.respectDnt || (window.navigator.doNotTrack !== '1')
}
)
}
function loadCheckboxStates() {
// do not change checkbox states if there are no saved settings yet
if (typeof Cookies.get(cookieName) === 'undefined') {
return
}
var consented = consentedSelectionsAll()
selectNone()
for (var _i = 0; _i < consented.length; _i++) {
var _checkbox = form.querySelector('[name=' + consented[_i] + ']')
if (_checkbox) {
setChecked(_checkbox, true)
}
}
}
/**
* Intercepts clicks on elements with `data-cookieman-show` attribute
* even when they are not yet in the DOM.
*/
function onBodyClick(e) {
const target = e.target
if (!target) {
return
}
if (target.dataset.hasOwnProperty('cookiemanShow')) {
cookieman.show()
}
}
function onSaveClick(e) {
e.preventDefault()
saveSelections()
cookieman.hide()
removeDisabledTrackingObjects()
injectNewTrackingObjects()
}
function onAcceptAllClick(e) {
e.preventDefault()
selectAll()
}
function onAcceptNoneClick(e) {
e.preventDefault()
selectNone()
}
function setDntTextIfEnabled() {
if (window.navigator.doNotTrack === '1') {
var dnts = document.querySelectorAll('[data-cookieman-dnt]')
for (var _i = 0; _i < dnts.length; _i++) {
dnts[_i].innerHTML = form.dataset.cookiemanDntEnabled
}
}
}
/**
* Returns all groups, in which a trackingObject with the given key is defined.
*
* @param trackingObjectKey string e.g. 'Matomo'
* @return array
*/
function findGroupsByTrackingObjectKey(trackingObjectKey) {
return Object.keys(settings.groups).filter(
function (groupKey) {
return Object.prototype.hasOwnProperty.call(settings.groups[groupKey], 'trackingObjects')
&& settings.groups[groupKey].trackingObjects.indexOf(trackingObjectKey) > -1
}
)
}
/**
* inject the HTML for a given tracking object
* @param trackingObjectKey string e.g. 'Matomo'
* @param trackingObjectSettings object (e.g. the array plugin.tx_cookieman.settings.trackingObjects.Matomo
* from TypoScript)
*/
function injectTrackingObject(trackingObjectKey, trackingObjectSettings) {
if (typeof trackingObjectSettings === 'undefined') {
console.error('Used trackingObject ‹' + trackingObjectKey + '› is undefined.')
return
}
if (typeof trackingObjectSettings.inject !== "undefined") {
// <script>s inserted via innerHTML won't be executed
// https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
// Let the DOM parse our inject-HTML...
var pseudo = document.createElement('div'),
_script
pseudo.innerHTML = trackingObjectSettings.inject
// ... insert each node ...
var iScript = 0
for (var iChild = 0; iChild < pseudo.children.length; iChild++) {
var node = pseudo.children[iChild]
// ... and give special treatment to <script>s
if (node.tagName === 'SCRIPT') {
_script = document.createElement('script')
_script.textContent = node.textContent
for (var _iAttr = 0; _iAttr < node.attributes.length; _iAttr++) {
var _attr = node.attributes[_iAttr]
_script.setAttribute(_attr.name, _attr.value)
}
_script.addEventListener(
'load',
(
function (_script, iScript, trackingObjectKey, trackingObjectSettings) {
return function (ev) {
if (typeof loadedTrackingObjectScripts[trackingObjectKey] === 'undefined') {
loadedTrackingObjectScripts[trackingObjectKey] = []
}
loadedTrackingObjectScripts[trackingObjectKey].push(iScript)
emit(
'scriptLoaded',
{
detail: {
trackingObjectKey: trackingObjectKey,
trackingObjectSettings: trackingObjectSettings,
scriptId: iScript,
node: _script
}
}
)
}
}
)(_script, iScript++, trackingObjectKey, trackingObjectSettings)
)
node = _script
} else {
// we will be removing this child
iChild--
}
document.body.appendChild(node)
}
// keep track what we injected
injectedTrackingObjects.push(trackingObjectKey)
}
}
/**
* remove tracking objects that are not consented.
* See removeTrackingObjectItem() for supported types.
*/
function removeDisabledTrackingObjects() {
for (var groupKey in settings.groups) {
if (!Object.prototype.hasOwnProperty.call(settings.groups, groupKey)) {
continue
}
if (!hasConsented(groupKey)) {
var oGroup = settings.groups[groupKey]
for (var _j = 0; _j < oGroup.trackingObjects.length; _j++) {
var trackingObjectKey = oGroup.trackingObjects[_j]
removeTrackingObject(trackingObjectKey, settings.trackingObjects[trackingObjectKey])
}
}
}
}
/**
* remove a given tracking object
* See removeTrackingObjectItem() for supported types.
* @param trackingObjectKey string e.g. 'Matomo'
* @param trackingObjectSettings object (e.g. the array plugin.tx_cookieman.settings.trackingObjects.Matomo
* from TypoScript)
*/
function removeTrackingObject(trackingObjectKey, trackingObjectSettings) {
if (typeof trackingObjectSettings === 'undefined') {
console.error('Used trackingObject ‹' + trackingObjectKey + '› is undefined.')
return
}
for (var itemKey in trackingObjectSettings.show) {
if (!Object.prototype.hasOwnProperty.call(trackingObjectSettings.show, itemKey)) {
continue
}
var oItem = trackingObjectSettings.show[itemKey]
removeTrackingObjectItem(itemKey, oItem)
}
}
/**
* remove a given single tracking object item
* Supported types: cookie_http+html
* @param itemKey string, e.g. '_ga'
* @param oItem object the settings for a single item (e.g. the array
* plugin.tx_cookieman.settings.trackingObjects.GoogleAnalytics.show._ga from TypoScript)
* @return boolean successful?
*/
function removeTrackingObjectItem(itemKey, oItem) {
if (oItem.type === 'cookie_http+html') {
if (Object.prototype.hasOwnProperty.call(oItem, 'htmlCookieRemovalPattern') && oItem['htmlCookieRemovalPattern'] !== '') {
var regex,
currentCookies = Cookies.get(),
matches
try {
//Put in try/catch in case user set malformed regex
regex = RegExp(oItem['htmlCookieRemovalPattern'])
} catch (e) {
console.error('Malformed pattern for cookie deletion on trackingObjectItem "' + itemKey + '": ' + e.message)
//Do not try the malformed pattern on the other cookie names
return false
}
for (var cookieName in currentCookies) {
if (cookieName.match(regex) !== null) {
removeHtmlCookie(cookieName)
}
}
} else {
removeHtmlCookie(itemKey)
}
return true
}
// unsupported type
return false
}
/**
* inject not-yet-injected tracking objects if consented and matching DNT constraints
*/
function injectNewTrackingObjects() {
var consenteds = consentedSelectionsRespectDnt()
for (var _i = 0; _i < consenteds.length; _i++) {
var oGroup = settings.groups[consenteds[_i]]
for (var _j = 0; _j < oGroup.trackingObjects.length; _j++) {
var trackingObjectKey = oGroup.trackingObjects[_j]
if (injectedTrackingObjects.indexOf(trackingObjectKey) === -1) {
injectTrackingObject(trackingObjectKey, settings.trackingObjects[trackingObjectKey])
}
}
}
}
// CustomEvents https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
// polyfill for IE9+
function polyfillCustomEvent() {
if (typeof window.CustomEvent !== "function") {
window.CustomEvent = function (typeArg, customEventInit) {
customEventInit = customEventInit || {bubbles: false, cancelable: false, detail: undefined}
var event = document.createEvent('CustomEvent')
event.initCustomEvent(typeArg, customEventInit.bubbles, customEventInit.cancelable, customEventInit.detail)
return event
}
window.CustomEvent.prototype = window.Event.prototype
}
}
function emit(typeArg, customEventInit) {
polyfillCustomEvent()
eventsEl.dispatchEvent(
new window.CustomEvent(typeArg, customEventInit)
)
}
/**
* Remove HTML cookie.
* In order to catch wildcard cookies like domain=.xxx.yy try different path and domains.
* @link https://github.com/dmind-gmbh/extension-cookieman/issues/137
* @param name
*/
function removeHtmlCookie(name) {
// www.xxx.yy
var fullDomain = document.location.host
// xxx.yy
var secondLevelDomain = fullDomain.split('.').slice(-2).join('.')
Cookies.remove(name)
Cookies.remove(name, {path: '/'})
Cookies.remove(name, {path: '', domain: fullDomain})
Cookies.remove(name, {path: '/', domain: fullDomain})
Cookies.remove(name, {path: '', domain: '.' + secondLevelDomain})
Cookies.remove(name, {path: '/', domain: '.' + secondLevelDomain})
}
function init() {
// register handlers
for (var i = 0; i < acceptAllButtons.length; i++) {
acceptAllButtons[i].addEventListener(
'click',
onAcceptAllClick
)
}
for (i = 0; i < acceptNoneButtons.length; i++) {
acceptNoneButtons[i].addEventListener(
'click',
onAcceptNoneClick
)
}
for (i = 0; i < saveButtons.length; i++) {
saveButtons[i].addEventListener(
'click',
onSaveClick
)
}
// Intercepts clicks on elements with `data-cookieman-show` attribute
// even when they are not yet in the DOM.
document.body.addEventListener(
'click',
onBodyClick
)
// load form state
loadCheckboxStates()
setDntTextIfEnabled()
// inject tracking objects if consented
injectNewTrackingObjects()
}
init()
return {
/**
* @api
*/
show: function () {
console.error('Your theme should implement function cookieman.show()')
},
/**
* @api
*/
hide: function () {
console.error('Your theme should implement function cookieman.hide()')
},
/**
* @api
*/
showOnce: function () {
if (typeof Cookies.get(cookieName) === 'undefined') {
cookieman.show()
}
},
/**
* @api
* @param {string} groupKey
* @returns {boolean}
*/
hasConsented: hasConsented,
/**
* @api
* @param {string} trackingObjectKey
* @returns {boolean}
*/
hasConsentedTrackingObject: hasConsentedTrackingObject,
/**
* @api
*/
consenteds: consentedSelectionsRespectDnt,
/**
* @api
* @param {string} groupKey
*/
consent: function (groupKey) {
var checkbox = form.querySelector('[type=checkbox][name="' + groupKey + '"]')
setChecked(checkbox, true)
saveSelections()
injectNewTrackingObjects()
},
/**
* @api
* @param {string} trackingObjectKey
* @param {number} scriptId
* @param {function} callback
*/
onScriptLoaded: function (trackingObjectKey, scriptId, callback) {
if (typeof loadedTrackingObjectScripts[trackingObjectKey] === 'undefined') {
loadedTrackingObjectScripts[trackingObjectKey] = []
}
// not loaded yet
if (loadedTrackingObjectScripts[trackingObjectKey].indexOf(scriptId) === -1) {
// attach ourselves to the "scriptLoaded" event
eventsEl.addEventListener(
'scriptLoaded',
function (ev) {
if (ev.detail.trackingObjectKey === trackingObjectKey && ev.detail.scriptId === scriptId) {
callback(ev.detail.trackingObjectKey, ev.detail.scriptId)
}
}
)
} else { // already loaded
callback(trackingObjectKey, scriptId)
}
},
/**
* not part of the API
*/
eventsEl: eventsEl
}
}());