forked from osano/cookieconsent
/
cookieconsent.js
1499 lines (1225 loc) · 52.9 KB
/
cookieconsent.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(cc) {
// stop from running again, if accidently included more than once.
if (cc.hasInitialised) return;
var util = {
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
escapeRegExp: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
},
hasClass: function(element, selector) {
var s = ' ';
return element.nodeType === 1 &&
(s + element.className + s).replace(/[\n\t]/g, s).indexOf(s + selector + s) >= 0;
},
addClass: function(element, className) {
element.className += ' ' + className;
},
removeClass: function(element, className) {
var regex = new RegExp('\\b' + this.escapeRegExp(className) + '\\b');
element.className = element.className.replace(regex, '');
},
interpolateString: function(str, callback) {
var marker = /{{([a-z][a-z0-9\-_]*)}}/ig;
return str.replace(marker, function(matches) {
return callback(arguments[1]) || '';
})
},
getCookie: function(name) {
var value = '; ' + document.cookie;
var parts = value.split('; ' + name + '=');
return parts.length != 2 ?
undefined : parts.pop().split(';').shift();
},
setCookie: function(name, value, expiryDays, domain, path) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + (expiryDays || 365));
var cookie = [
name + '=' + value,
'expires=' + exdate.toUTCString(),
'path=' + (path || '/')
];
if (domain) {
cookie.push('domain=' + domain);
}
document.cookie = cookie.join(';');
},
// only used for extending the initial options
deepExtend: function(target, source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in target && this.isPlainObject(target[prop]) && this.isPlainObject(source[prop])) {
this.deepExtend(target[prop], source[prop]);
} else {
target[prop] = source[prop];
}
}
}
return target;
},
// only used for throttling the 'mousemove' event (used for animating the revoke button when `animateRevokable` is true)
throttle: function(callback, limit) {
var wait = false;
return function() {
if (!wait) {
callback.apply(this, arguments);
wait = true;
setTimeout(function() {
wait = false;
}, limit);
}
}
},
// only used for hashing json objects (used for hash mapping palette objects, used when custom colours are passed through JavaScript)
hash: function(str) {
var hash = 0,
i, chr, len;
if (str.length === 0) return hash;
for (i = 0, len = str.length; i < len; ++i) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
},
normaliseHex: function(hex) {
if (hex[0] == '#') {
hex = hex.substr(1);
}
if (hex.length == 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
return hex;
},
// used to get text colors if not set
getContrast: function(hex) {
hex = this.normaliseHex(hex);
var r = parseInt(hex.substr(0, 2), 16);
var g = parseInt(hex.substr(2, 2), 16);
var b = parseInt(hex.substr(4, 2), 16);
var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
return (yiq >= 128) ? '#000' : '#fff';
},
// used to change color on highlight
getLuminance: function(hex) {
var num = parseInt(this.normaliseHex(hex), 16),
amt = 38,
R = (num >> 16) + amt,
B = (num >> 8 & 0x00FF) + amt,
G = (num & 0x0000FF) + amt;
var newColour = (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1);
return '#'+newColour;
},
isMobile: function() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
},
isPlainObject: function(obj) {
// The code "typeof obj === 'object' && obj !== null" allows Array objects
return typeof obj === 'object' && obj !== null && obj.constructor == Object;
},
};
// valid cookie values
cc.status = {
deny: 'deny',
allow: 'allow',
dismiss: 'dismiss'
};
// detects the `transitionend` event name
cc.transitionEnd = (function() {
var el = document.createElement('div');
var trans = {
t: "transitionend",
OT: "oTransitionEnd",
msT: "MSTransitionEnd",
MozT: "transitionend",
WebkitT: "webkitTransitionEnd",
};
for (var prefix in trans) {
if (trans.hasOwnProperty(prefix) && typeof el.style[prefix + 'ransition'] != 'undefined') {
return trans[prefix];
}
}
return '';
}());
cc.hasTransition = !!cc.transitionEnd;
// array of valid regexp escaped statuses
var __allowedStatuses = Object.keys(cc.status).map(util.escapeRegExp);
// contains references to the custom <style> tags
cc.customStyles = {};
cc.Popup = (function() {
var defaultOptions = {
// if false, this prevents the popup from showing (useful for giving to control to another piece of code)
enabled: true,
// optional (expecting a HTML element) if passed, the popup is appended to this element. default is `document.body`
container: null,
// defaults cookie options - it is RECOMMENDED to set these values to correspond with your server
cookie: {
// This is the name of this cookie - you can ignore this
name: 'cookieconsent_status',
// This is the url path that the cookie 'name' belongs to. The cookie can only be read at this location
path: '/',
// This is the domain that the cookie 'name' belongs to. The cookie can only be read on this domain.
// - Guide to cookie domains - http://erik.io/blog/2014/03/04/definitive-guide-to-cookie-domains/
domain: '',
// The cookies expire date, specified in days (specify -1 for no expiry)
expiryDays: 365,
},
// these callback hooks are called at certain points in the program execution
onPopupOpen: function() {},
onPopupClose: function() {},
onInitialise: function(status) {},
onStatusChange: function(status, chosenBefore) {},
onRevokeChoice: function() {},
// each item defines the inner text for the element that it references
content: {
header: 'Cookies used on the website!',
message: 'This website uses cookies to ensure you get the best experience on our website.',
dismiss: 'Got it!',
allow: 'Allow cookies',
deny: 'Decline',
link: 'Learn more',
href: 'http://cookiesandyou.com',
close: '❌',
},
// This is the HTML for the elements above. The string {{header}} will be replaced with the equivalent text below.
// You can remove "{{header}}" and write the content directly inside the HTML if you want.
//
// - ARIA rules suggest to ensure controls are tabbable (so the browser can find the first control),
// and to set the focus to the first interactive control (http://w3c.github.io/aria-in-html/)
elements: {
header: '<span class="cc-header">{{header}}</span> ',
message: '<span id="cookieconsent:desc" class="cc-message">{{message}}</span>',
messagelink: '<span id="cookieconsent:desc" class="cc-message">{{message}} <a aria-label="learn more about cookies" role=button tabindex="0" class="cc-link" href="{{href}}" rel="noopener noreferrer nofollow" target="_blank">{{link}}</a></span>',
dismiss: '<a aria-label="dismiss cookie message" role=button tabindex="0" class="cc-btn cc-dismiss">{{dismiss}}</a>',
allow: '<a aria-label="allow cookies" role=button tabindex="0" class="cc-btn cc-allow">{{allow}}</a>',
deny: '<a aria-label="deny cookies" role=button tabindex="0" class="cc-btn cc-deny">{{deny}}</a>',
link: '<a aria-label="learn more about cookies" role=button tabindex="0" class="cc-link" href="{{href}}" target="_blank">{{link}}</a>',
close: '<span aria-label="dismiss cookie message" role=button tabindex="0" class="cc-close">{{close}}</span>',
//compliance: compliance is also an element, but it is generated by the application, depending on `type` below
},
// The placeholders {{classes}} and {{children}} both get replaced during initialisation:
// - {{classes}} is where additional classes get added
// - {{children}} is where the HTML children are placed
window: '<div role="dialog" aria-live="polite" aria-label="cookieconsent" aria-describedby="cookieconsent:desc" class="cc-window {{classes}}"><!--googleoff: all-->{{children}}<!--googleon: all--></div>',
// This is the html for the revoke button. This only shows up after the user has selected their level of consent
// It can be enabled of disabled using the `revokable` option
revokeBtn: '<div class="cc-revoke {{classes}}">Cookie Policy</div>',
// define types of 'compliance' here. '{{value}}' strings in here are linked to `elements`
compliance: {
'info': '<div class="cc-compliance">{{dismiss}}</div>',
'opt-in': '<div class="cc-compliance cc-highlight">{{dismiss}}{{allow}}</div>',
'opt-out': '<div class="cc-compliance cc-highlight">{{deny}}{{dismiss}}</div>',
},
// select your type of popup here
type: 'info', // refers to `compliance` (in other words, the buttons that are displayed)
// define layout layouts here
layouts: {
// the 'block' layout tend to be for square floating popups
'basic': '{{messagelink}}{{compliance}}',
'basic-close': '{{messagelink}}{{compliance}}{{close}}',
'basic-header': '{{header}}{{message}}{{link}}{{compliance}}',
// add a custom layout here, then add some new css with the class '.cc-layout-my-cool-layout'
//'my-cool-layout': '<div class="my-special-layout">{{message}}{{compliance}}</div>{{close}}',
},
// default layout (see above)
layout: 'basic',
// this refers to the popup windows position. we currently support:
// - banner positions: top, bottom
// - floating positions: top-left, top-right, bottom-left, bottom-right
//
// adds a class `cc-floating` or `cc-banner` which helps when styling
position: 'bottom', // default position is 'bottom'
// Available styles
// -block (default, no extra classes)
// -edgeless
// -classic
// use your own style name and use `.cc-theme-STYLENAME` class in CSS to edit.
// Note: style "wire" is used for the configurator, but has no CSS styles of its own, only palette is used.
theme: 'block',
// The popup is `fixed` by default, but if you want it to be static (inline with the page content), set this to false
// Note: by default, we animate the height of the popup from 0 to full size
static: false,
// if you want custom colours, pass them in here. this object should look like this.
// ideally, any custom colours/themes should be created in a separate style sheet, as this is more efficient.
// {
// popup: {background: '#000000', text: '#fff', link: '#fff'},
// button: {background: 'transparent', border: '#f8e71c', text: '#f8e71c'},
// highlight: {background: '#f8e71c', border: '#f8e71c', text: '#000000'},
// }
// `highlight` is optional and extends `button`. if it exists, it will apply to the first button
// only background needs to be defined for every element. if not set, other colors can be calculated from it
palette: null,
// Some countries REQUIRE that a user can change their mind. You can configure this yourself.
// Most of the time this should be false, but the `cookieconsent.law` can change this to `true` if it detects that it should
revokable: false,
// if true, the revokable button will tranlate in and out
animateRevokable: true,
// used to disable link on existing layouts
// replaces element messagelink with message and removes content of link
showLink: true,
// set value as scroll range to enable
dismissOnScroll: false,
// set value as time in milliseconds to autodismiss after set time
dismissOnTimeout: false,
// The application automatically decide whether the popup should open.
// Set this to false to prevent this from happening and to allow you to control the behaviour yourself
autoOpen: true,
// By default the created HTML is automatically appended to the container (which defaults to <body>). You can prevent this behaviour
// by setting this to false, but if you do, you must attach the `element` yourself, which is a public property of the popup instance:
//
// var instance = cookieconsent.factory(options);
// document.body.appendChild(instance.element);
//
autoAttach: true,
// simple whitelist/blacklist for pages. specify page by:
// - using a string : '/index.html' (matches '/index.html' exactly) OR
// - using RegExp : /\/page_[\d]+\.html/ (matched '/page_1.html' and '/page_2.html' etc)
whitelistPage: [],
blacklistPage: [],
// If this is defined, then it is used as the inner html instead of layout. This allows for ultimate customisation.
// Be sure to use the classes `cc-btn` and `cc-allow`, `cc-deny` or `cc-dismiss`. They enable the app to register click
// handlers. You can use other pre-existing classes too. See `src/styles` folder.
overrideHTML: null,
};
function CookiePopup() {
this.initialise.apply(this, arguments);
}
CookiePopup.prototype.initialise = function(options) {
if (this.options) {
this.destroy(); // already rendered
}
// set options back to default options
util.deepExtend(this.options = {}, defaultOptions);
// merge in user options
if (util.isPlainObject(options)) {
util.deepExtend(this.options, options);
}
// returns true if `onComplete` was called
if (checkCallbackHooks.call(this)) {
// user has already answered
this.options.enabled = false;
}
// apply blacklist / whitelist
if (arrayContainsMatches(this.options.blacklistPage, location.pathname)) {
this.options.enabled = false;
}
if (arrayContainsMatches(this.options.whitelistPage, location.pathname)) {
this.options.enabled = true;
}
// the full markup either contains the wrapper or it does not (for multiple instances)
var cookiePopup = this.options.window
.replace('{{classes}}', getPopupClasses.call(this).join(' '))
.replace('{{children}}', getPopupInnerMarkup.call(this));
// if user passes html, use it instead
var customHTML = this.options.overrideHTML;
if (typeof customHTML == 'string' && customHTML.length) {
cookiePopup = customHTML;
}
// if static, we need to grow the element from 0 height so it doesn't jump the page
// content. we wrap an element around it which will mask the hidden content
if (this.options.static) {
// `grower` is a wrapper div with a hidden overflow whose height is animated
var wrapper = appendMarkup.call(this, '<div class="cc-grower">' + cookiePopup + '</div>');
wrapper.style.display = ''; // set it to visible (because appendMarkup hides it)
this.element = wrapper.firstChild; // get the `element` reference from the wrapper
this.element.style.display = 'none';
util.addClass(this.element, 'cc-invisible');
} else {
this.element = appendMarkup.call(this, cookiePopup);
}
applyAutoDismiss.call(this);
applyRevokeButton.call(this);
if (this.options.autoOpen) {
this.autoOpen();
}
};
CookiePopup.prototype.destroy = function() {
if (this.onButtonClick && this.element) {
this.element.removeEventListener('click', this.onButtonClick);
this.onButtonClick = null;
}
if (this.dismissTimeout) {
clearTimeout(this.dismissTimeout);
this.dismissTimeout = null;
}
if (this.onWindowScroll) {
window.removeEventListener('scroll', this.onWindowScroll);
this.onWindowScroll = null;
}
if (this.onMouseMove) {
window.removeEventListener('mousemove', this.onMouseMove);
this.onMouseMove = null;
}
if (this.element && this.element.parentNode) {
this.element.parentNode.removeChild(this.element);
}
this.element = null;
if (this.revokeBtn && this.revokeBtn.parentNode) {
this.revokeBtn.parentNode.removeChild(this.revokeBtn);
}
this.revokeBtn = null;
removeCustomStyle(this.options.palette);
this.options = null;
};
CookiePopup.prototype.open = function(callback) {
if (!this.element) return;
if (!this.isOpen()) {
if (cc.hasTransition) {
this.fadeIn();
} else {
this.element.style.display = '';
}
if (this.options.revokable) {
this.toggleRevokeButton();
}
this.options.onPopupOpen.call(this);
}
return this;
};
CookiePopup.prototype.close = function(showRevoke) {
if (!this.element) return;
if (this.isOpen()) {
if (cc.hasTransition) {
this.fadeOut();
} else {
this.element.style.display = 'none';
}
if (showRevoke && this.options.revokable) {
this.toggleRevokeButton(true);
}
this.options.onPopupClose.call(this);
}
return this;
};
CookiePopup.prototype.fadeIn = function() {
var el = this.element;
if (!cc.hasTransition || !el)
return;
// This should always be called AFTER fadeOut (which is governed by the 'transitionend' event).
// 'transitionend' isn't all that reliable, so, if we try and fadeIn before 'transitionend' has
// has a chance to run, then we run it ourselves
if (this.afterTransition) {
afterFadeOut.call(this, el)
}
if (util.hasClass(el, 'cc-invisible')) {
el.style.display = '';
if (this.options.static) {
var height = this.element.clientHeight;
this.element.parentNode.style.maxHeight = height + 'px';
}
var fadeInTimeout = 20; // (ms) DO NOT MAKE THIS VALUE SMALLER. See below
// Although most browsers can handle values less than 20ms, it should remain above this value.
// This is because we are waiting for a "browser redraw" before we remove the 'cc-invisible' class.
// If the class is remvoed before a redraw could happen, then the fadeIn effect WILL NOT work, and
// the popup will appear from nothing. Therefore we MUST allow enough time for the browser to do
// its thing. The actually difference between using 0 and 20 in a set timeout is neglegible anyway
this.openingTimeout = setTimeout(afterFadeIn.bind(this, el), fadeInTimeout);
}
};
CookiePopup.prototype.fadeOut = function() {
var el = this.element;
if (!cc.hasTransition || !el)
return;
if (this.openingTimeout) {
clearTimeout(this.openingTimeout);
afterFadeIn.bind(this, el);
}
if (!util.hasClass(el, 'cc-invisible')) {
if (this.options.static) {
this.element.parentNode.style.maxHeight = '';
}
this.afterTransition = afterFadeOut.bind(this, el);
el.addEventListener(cc.transitionEnd, this.afterTransition);
util.addClass(el, 'cc-invisible');
}
};
CookiePopup.prototype.isOpen = function() {
return this.element && this.element.style.display == '' && (cc.hasTransition ? !util.hasClass(this.element, 'cc-invisible') : true);
};
CookiePopup.prototype.toggleRevokeButton = function(show) {
if (this.revokeBtn) this.revokeBtn.style.display = show ? '' : 'none';
};
CookiePopup.prototype.revokeChoice = function(preventOpen) {
this.options.enabled = true;
this.clearStatus();
this.options.onRevokeChoice.call(this);
if (!preventOpen) {
this.autoOpen();
}
};
// returns true if the cookie has a valid value
CookiePopup.prototype.hasAnswered = function(options) {
return Object.keys(cc.status).indexOf(this.getStatus()) >= 0;
};
// returns true if the cookie indicates that consent has been given
CookiePopup.prototype.hasConsented = function(options) {
var val = this.getStatus();
var type = this.options.type;
if (type == "opt-in") {
return val == cc.status.allow
}
return val == cc.status.allow || val == cc.status.dismiss;
};
// opens the popup if no answer has been given
CookiePopup.prototype.autoOpen = function(options) {
!this.hasAnswered() && this.options.enabled && this.open();
};
CookiePopup.prototype.setStatus = function(status) {
var c = this.options.cookie;
var value = util.getCookie(c.name);
var chosenBefore = Object.keys(cc.status).indexOf(value) >= 0;
// if `status` is valid
if (Object.keys(cc.status).indexOf(status) >= 0) {
util.setCookie(c.name, status, c.expiryDays, c.domain, c.path);
this.options.onStatusChange.call(this, status, chosenBefore);
} else {
this.clearStatus();
}
};
CookiePopup.prototype.getStatus = function() {
return util.getCookie(this.options.cookie.name);
};
CookiePopup.prototype.clearStatus = function() {
var c = this.options.cookie;
util.setCookie(c.name, '', -1, c.domain, c.path);
};
// This needs to be called after 'fadeIn'. This is the code that actually causes the fadeIn to work
// There is a good reason why it's called in a timeout. Read 'fadeIn';
function afterFadeIn(el) {
this.openingTimeout = null;
util.removeClass(el, 'cc-invisible');
}
// This is called on 'transitionend' (only on the transition of the fadeOut). That's because after we've faded out, we need to
// set the display to 'none' (so there aren't annoying invisible popups all over the page). If for whenever reason this function
// is not called (lack of support), the open/close mechanism will still work.
function afterFadeOut(el) {
el.style.display = 'none'; // after close and before open, the display should be none
el.removeEventListener(cc.transitionEnd, this.afterTransition);
this.afterTransition = null;
}
// this function calls the `onComplete` hook and returns true (if needed) and returns false otherwise
function checkCallbackHooks() {
var complete = this.options.onInitialise.bind(this);
if (!window.navigator.cookieEnabled) {
complete(cc.status.deny);
return true;
}
if (window.CookiesOK || window.navigator.CookiesOK) {
complete(cc.status.allow);
return true;
}
var allowed = Object.keys(cc.status);
var answer = this.getStatus();
var match = allowed.indexOf(answer) >= 0;
if (match) {
complete(answer);
}
return match;
}
function getPositionClasses() {
var positions = this.options.position.split('-'); // top, bottom, left, right
var classes = [];
// top, left, right, bottom
positions.forEach(function(cur) {
classes.push('cc-' + cur);
});
return classes;
}
function getPopupClasses() {
var opts = this.options;
var positionStyle = (opts.position == 'top' || opts.position == 'bottom') ? 'banner' : 'floating';
if (util.isMobile()) {
positionStyle = 'floating';
}
var classes = [
'cc-' + positionStyle, // floating or banner
'cc-type-' + opts.type, // add the compliance type
'cc-theme-' + opts.theme, // add the theme
];
if (opts.static) {
classes.push('cc-static');
}
classes.push.apply(classes, getPositionClasses.call(this));
// we only add extra styles if `palette` has been set to a valid value
var didAttach = attachCustomPalette.call(this, this.options.palette);
// if we override the palette, add the class that enables this
if (this.customStyleSelector) {
classes.push(this.customStyleSelector);
}
return classes;
}
function getPopupInnerMarkup() {
var interpolated = {};
var opts = this.options;
// removes link if showLink is false
if (!opts.showLink) {
opts.elements.link = '';
opts.elements.messagelink = opts.elements.message;
}
Object.keys(opts.elements).forEach(function(prop) {
interpolated[prop] = util.interpolateString(opts.elements[prop], function(name) {
var str = opts.content[name];
return (name && typeof str == 'string' && str.length) ? str : '';
})
});
// checks if the type is valid and defaults to info if it's not
var complianceType = opts.compliance[opts.type];
if (!complianceType) {
complianceType = opts.compliance.info;
}
// build the compliance types from the already interpolated `elements`
interpolated.compliance = util.interpolateString(complianceType, function(name) {
return interpolated[name];
});
// checks if the layout is valid and defaults to basic if it's not
var layout = opts.layouts[opts.layout];
if (!layout) {
layout = opts.layouts.basic;
}
return util.interpolateString(layout, function(match) {
return interpolated[match];
});
}
function appendMarkup(markup) {
var opts = this.options;
var div = document.createElement('div');
var cont = (opts.container && opts.container.nodeType === 1) ? opts.container : document.body;
div.innerHTML = markup;
var el = div.children[0];
el.style.display = 'none';
if (util.hasClass(el, 'cc-window') && cc.hasTransition) {
util.addClass(el, 'cc-invisible');
}
// save ref to the function handle so we can unbind it later
this.onButtonClick = handleButtonClick.bind(this);
el.addEventListener('click', this.onButtonClick);
if (opts.autoAttach) {
if (!cont.firstChild) {
cont.appendChild(el);
} else {
cont.insertBefore(el, cont.firstChild)
}
}
return el;
}
function handleButtonClick(event) {
var targ = event.target;
if (util.hasClass(targ, 'cc-btn')) {
var matches = targ.className.match(new RegExp("\\bcc-(" + __allowedStatuses.join('|') + ")\\b"));
var match = (matches && matches[1]) || false;
if (match) {
this.setStatus(match);
this.close(true);
}
}
if (util.hasClass(targ, 'cc-close')) {
this.setStatus(cc.status.dismiss);
this.close(true);
}
if (util.hasClass(targ, 'cc-revoke')) {
this.revokeChoice();
}
}
// I might change this function to use inline styles. I originally chose a stylesheet because I could select many elements with a
// single rule (something that happened a lot), the apps has changed slightly now though, so inline styles might be more applicable.
function attachCustomPalette(palette) {
var hash = util.hash(JSON.stringify(palette));
var selector = 'cc-color-override-' + hash;
var isValid = util.isPlainObject(palette);
this.customStyleSelector = isValid ? selector : null;
if (isValid) {
addCustomStyle(hash, palette, '.' + selector);
}
return isValid;
}
function addCustomStyle(hash, palette, prefix) {
// only add this if a style like it doesn't exist
if (cc.customStyles[hash]) {
// custom style already exists, so increment the reference count
++cc.customStyles[hash].references;
return;
}
var colorStyles = {};
var popup = palette.popup;
var button = palette.button;
var highlight = palette.highlight;
// needs background colour, text and link will be set to black/white if not specified
if (popup) {
// assumes popup.background is set
popup.text = popup.text ? popup.text : util.getContrast(popup.background);
popup.link = popup.link ? popup.link : popup.text;
colorStyles[prefix + '.cc-window'] = [
'color: ' + popup.text,
'background-color: ' + popup.background
];
colorStyles[prefix + '.cc-revoke'] = [
'color: ' + popup.text,
'background-color: ' + popup.background
];
colorStyles[prefix + ' .cc-link,' + prefix + ' .cc-link:active,' + prefix + ' .cc-link:visited'] = [
'color: ' + popup.link
];
if (button) {
// assumes button.background is set
button.text = button.text ? button.text : util.getContrast(button.background);
button.border = button.border ? button.border : 'transparent';
colorStyles[prefix + ' .cc-btn'] = [
'color: ' + button.text,
'border-color: ' + button.border,
'background-color: ' + button.background
];
if(button.background != 'transparent')
colorStyles[prefix + ' .cc-btn:hover, ' + prefix + ' .cc-btn:focus'] = [
'background-color: ' + getHoverColour(button.background)
];
if (highlight) {
//assumes highlight.background is set
highlight.text = highlight.text ? highlight.text : util.getContrast(highlight.background);
highlight.border = highlight.border ? highlight.border : 'transparent';
colorStyles[prefix + ' .cc-highlight .cc-btn:first-child'] = [
'color: ' + highlight.text,
'border-color: ' + highlight.border,
'background-color: ' + highlight.background
];
} else {
// sets highlight text color to popup text. background and border are transparent by default.
colorStyles[prefix + ' .cc-highlight .cc-btn:first-child'] = [
'color: ' + popup.text
];
}
}
}
// this will be interpretted as CSS. the key is the selector, and each array element is a rule
var style = document.createElement('style');
document.head.appendChild(style);
// custom style doesn't exist, so we create it
cc.customStyles[hash] = {
references: 1,
element: style.sheet
};
var ruleIndex = -1;
for (var prop in colorStyles) {
if (colorStyles.hasOwnProperty(prop)) {
style.sheet.insertRule(prop + '{' + colorStyles[prop].join(';') + '}', ++ruleIndex);
}
}
}
function getHoverColour(hex) {
hex = util.normaliseHex(hex);
// for black buttons
if (hex == '000000') {
return '#222';
}
return util.getLuminance(hex);
}
function removeCustomStyle(palette) {
if (util.isPlainObject(palette)) {
var hash = util.hash(JSON.stringify(palette));
var customStyle = cc.customStyles[hash];
if (customStyle && !--customStyle.references) {
var styleNode = customStyle.element.ownerNode;
if (styleNode && styleNode.parentNode) {
styleNode.parentNode.removeChild(styleNode);
}
cc.customStyles[hash] = null;
}
}
}
function arrayContainsMatches(array, search) {
for (var i = 0, l = array.length; i < l; ++i) {
var str = array[i];
// if regex matches or string is equal, return true
if ((str instanceof RegExp && str.test(search)) ||
(typeof str == 'string' && str.length && str === search)) {
return true;
}
}
return false;
}
function applyAutoDismiss() {
var setStatus = this.setStatus.bind(this);
var delay = this.options.dismissOnTimeout;
if (typeof delay == 'number' && delay >= 0) {
this.dismissTimeout = window.setTimeout(function() {
setStatus(cc.status.dismiss);
}, Math.floor(delay));
}
var scrollRange = this.options.dismissOnScroll;
if (typeof scrollRange == 'number' && scrollRange >= 0) {
var onWindowScroll = function(evt) {
if (window.pageYOffset > Math.floor(scrollRange)) {
setStatus(cc.status.dismiss);
window.removeEventListener('scroll', onWindowScroll);
this.onWindowScroll = null;
}
};
this.onWindowScroll = onWindowScroll;
window.addEventListener('scroll', onWindowScroll);
}
}
function applyRevokeButton() {
// revokable is true if advanced compliance is selected
if (this.options.type != 'info') this.options.revokable = true;
// animateRevokable false for mobile devices
if (util.isMobile()) this.options.animateRevokable = false;
if (this.options.revokable) {
var classes = getPositionClasses.call(this);
if (this.options.animateRevokable) {
classes.push('cc-animate');
}
if (this.customStyleSelector) {
classes.push(this.customStyleSelector)
}
var revokeBtn = this.options.revokeBtn.replace('{{classes}}', classes.join(' '));
this.revokeBtn = appendMarkup.call(this, revokeBtn);
var btn = this.revokeBtn;
if (this.options.animateRevokable) {
var wait = false;
var onMouseMove = util.throttle(function(evt) {
var active = false;
var minY = 20;
var maxY = (window.innerHeight - 20);
if (util.hasClass(btn, 'cc-top') && evt.clientY < minY) active = true;
if (util.hasClass(btn, 'cc-bottom') && evt.clientY > maxY) active = true;
if (active) {
if (!util.hasClass(btn, 'cc-active')) {
util.addClass(btn, 'cc-active');
}
} else {
if (util.hasClass(btn, 'cc-active')) {
util.removeClass(btn, 'cc-active');
}
}
}, 200);
this.onMouseMove = onMouseMove;
window.addEventListener('mousemove', onMouseMove);
}
}
}
return CookiePopup
}());
cc.Location = (function() {
// An object containing all the location services we have already set up.
// When using a service, it could either return a data structure in plain text (like a JSON object) or an executable script
// When the response needs to be executed by the browser, then `isScript` must be set to true, otherwise it won't work.
// When the service uses a script, the chances are that you'll have to use the script to make additional requests. In these
// cases, the services `callback` property is called with a `done` function. When performing async operations, this must be called
// with the data (or Error), and `cookieconsent.locate` will take care of the rest
var defaultOptions = {
// The default timeout is 5 seconds. This is mainly needed to catch JSONP requests that error.
// Otherwise there is no easy way to catch JSONP errors. That means that if a JSONP fails, the
// app will take `timeout` milliseconds to react to a JSONP network error.
timeout: 5000,
// the order that services will be attempted in
services: [
'freegeoip',
'ipinfo',
'maxmind'
/*
// 'ipinfodb' requires some options, so we define it using an object