forked from orestbida/cookieconsent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_cookieconsent.js
1531 lines (1287 loc) · 65.1 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
/*!
* CookieConsent v2.4.7
* https://www.github.com/orestbida/cookieconsent
* Author Orest Bida
* Released under the MIT License
*/
(function(){
'use strict';
/**
* @param {HTMLElement} root element where the cookieconsent will be appended (default :=> document.body)
* @returns {Object}
*/
var CookieConsent = function(root){
// CHANGE THIS FLAG FALSE TO DISABLE console.log()
var ENABLE_LOGS = true;
var _config = {
current_lang : "en",
autorun: true, // run as soon as loaded
cookie_name: 'cc_cookie',
cookie_expiration : 182, // default: 6 months (in days)
cookie_domain: location.hostname, // default: current domain
cookie_path: "/",
cookie_same_site: "Lax",
script_selector: "data-cookiecategory"
};
/**
* Object which holds the main methods (.show, .run, ...)
*/
var _cookieconsent = {};
/**
* Internal state variables
*/
var _saved_cookie_content;
var consent_modal_exists = false;
var cookie_consent_accepted = false;
var consent_modal_visible = false;
var settings_modal_visible = false;
var clicked_inside_modal = false;
var current_modal_focusable;
/**
* Save reference to the last focused element on the page
* (used later to restore focus when both modals are closed)
*/
var last_elem_before_modal;
var last_consent_modal_btn_focus;
/**
* Both of the arrays below have the same structure:
* [0] => holds reference to the FIRST focusable element inside modal
* [1] => holds reference to the LAST focusable element inside modal
*/
var consent_modal_focusable = [];
var settings_modal_focusable = [];
/**
* Array of booleans used to keep track of enabled/disabled preferences
*/
var toggle_states = [];
/**
* Pointers to main dom elements (to avoid retrieving them later using document.getElementById)
*/
var html_dom = document.documentElement;
var main_container;
var consent_modal;
var settings_container, settings_inner;
/**
* Update config settings
* @param {Object} conf_params
*/
var _setConfig = function(conf_params){
_log("CookieConsent [CONFIG]: recieved_config_settings ", conf_params);
if(typeof conf_params['cookie_expiration'] === "number"){
_config.cookie_expiration = conf_params['cookie_expiration'];
}
if(typeof conf_params['autorun'] === "boolean"){
_config.autorun = conf_params['autorun'];
}
if(typeof conf_params['cookie_domain'] === "string"){
_config.cookie_domain = conf_params['cookie_domain'];
}
if(typeof conf_params['cookie_same_site'] === "string"){
_config.cookie_same_site = conf_params['cookie_same_site'];
}
if(typeof conf_params['cookie_path'] === "string"){
_config.cookie_path = conf_params['cookie_path'];
}
if(typeof conf_params['cookie_name'] === "string"){
_config.cookie_name = conf_params['cookie_name'];
}
_config.page_scripts = conf_params['page_scripts'] === true;
_config.page_scripts_order = conf_params['page_scripts_order'] !== false;
if(conf_params['auto_language'] === true){
_config.current_lang = _getValidatedLanguage(_getBrowserLang(), conf_params.languages);
}else{
if(typeof conf_params['current_lang'] === "string"){
_config.current_lang = _getValidatedLanguage(conf_params['current_lang'], conf_params.languages);;
}
}
if(conf_params['force_consent'] === true){
_addClass(html_dom, 'force--consent');
}
_log("CookieConsent [LANG]: setting current_lang = '"+ _config.current_lang + "'");
}
/**
* Search for all occurrences in the current page and add an onClick listener :
* when clicked => open settings modal
*/
var _addCookieSettingsButtonListener = function(){
var all_links = document.querySelectorAll('a[data-cc="c-settings"], button[data-cc="c-settings"]');
for(var x=0; x<all_links.length; x++){
all_links[x].setAttribute('aria-haspopup', 'dialog');
_addEvent(all_links[x], 'click', function(event){
_cookieconsent.showSettings(0);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
}
}
/**
* Check if given lang. index exists as a property.
* If it exists -> desired language is implemented,
* otherwise fall back to the default current_lang
* @param {String} lang
* @param {Object} all_languages
*/
var _getValidatedLanguage = function(lang, all_languages){
if(all_languages.hasOwnProperty(lang)){
return lang;
}else if(_getKeys(all_languages).length > 0){
if(all_languages.hasOwnProperty(_config.current_lang)){
return _config.current_lang ;
}else{
return _getKeys(all_languages)[0];
}
}
}
/**
* Save reference to first and last focusable elements inside each modal
* to prevent losing focus while navigating with TAB
* @param {HTMLElement} modal_dom
*/
var _getModalFocusableData = function(){
/**
* Note: any of the below focusable elements, which has the attribute tabindex="-1" AND is either
* the first or last element of the modal, won't recieve focus during "open/close" modal
*/
var allowed_focusable_types = ['[href]', 'button', 'input', 'details', '[tabindex="0"]'];
function _getAllFocusableElements(modal, _array){
var focus_later=false, focus_first=false;
// ie might throw exception due to complex unsupported selector => a:not([tabindex="-1"])
try{
var focusable_elems = modal.querySelectorAll(allowed_focusable_types.join(':not([tabindex="-1"]), '));
var attr, len=focusable_elems.length, i=0;
while(i < len){
attr = focusable_elems[i].getAttribute('data-focus');
if(!focus_first && attr === "1"){
focus_first = focusable_elems[i];
}else if(attr === "0"){
focus_later = focusable_elems[i];
if(!focus_first && focusable_elems[i+1].getAttribute('data-focus') !== "0"){
focus_first = focusable_elems[i+1];
}
}
i++;
}
}catch(e){
return modal.querySelectorAll(allowed_focusable_types.join(', '));
}
/**
* Save first and last elements (used to lock/trap focus inside modal)
*/
_array[0] = focusable_elems[0];
_array[1] = focusable_elems[focusable_elems.length - 1];
_array[2] = focus_later;
_array[3] = focus_first;
}
/**
* Get settings modal'S all focusable elements
* Save first and last elements (used to lock/trap focus inside modal)
*/
_getAllFocusableElements(settings_inner, settings_modal_focusable);
/**
* If consent modal exists, do the same
*/
if(consent_modal_exists){
_getAllFocusableElements(consent_modal, consent_modal_focusable);
}
}
/**
* Generate cookie consent html based on config settings
*/
var _createCookieConsentHTML = function(never_accepted, conf_params){
// Create main container which holds both consent modal & settings modal
main_container = _createNode('div');
main_container.id = 'cc--main';
// Fix layout flash
main_container.style.position = "fixed";
main_container.style.zIndex = "1000000";
main_container.innerHTML = '<!--[if lt IE 9 ]><div id="cc_div" class="cc_div ie"></div><![endif]--><!--[if (gt IE 8)|!(IE)]><!--><div id="cc_div" class="cc_div"></div><!--<![endif]-->'
var all_modals_container = main_container.children[0];
// Get current language
var lang = _config.current_lang;
// Feature detection :=> avoid IE exception since .textContent is not always supported
var innerText = (typeof html_dom.textContent === 'string' ? 'textContent' : 'innerText');
// If never_accepted => create consent-modal
if(!never_accepted){
consent_modal = _createNode('div');
var consent_modal_inner = _createNode('div');
var consent_modal_inner_inner = _createNode('div');
var consent_title = _createNode('div');
var consent_text = _createNode('div');
var consent_buttons = _createNode('div');
var consent_primary_btn = _createNode('button');
var consent_secondary_btn = _createNode('button');
var overlay = _createNode('div');
consent_modal.id = 'cm';
consent_modal_inner.id = 'c-inr';
consent_modal_inner_inner.id = 'c-inr-i';
consent_title.id = 'c-ttl';
consent_text.id = 'c-txt';
consent_buttons.id = "c-bns";
consent_primary_btn.id = 'c-p-bn';
consent_secondary_btn.id = 'c-s-bn';
overlay.id = 'cm-ov';
consent_primary_btn.className = "c-bn";
consent_secondary_btn.className = "c-bn c_link";
consent_title.setAttribute('role', 'heading');
consent_title.setAttribute('aria-level', '2');
consent_modal.setAttribute('role', 'dialog');
consent_modal.setAttribute('aria-modal', 'true');
consent_modal.setAttribute('aria-hidden', 'false');
consent_modal.setAttribute('aria-labelledby', 'c-ttl');
consent_modal.setAttribute('aria-describedby', 'c-txt');
/**
* Make modal by default hidden to prevent weird page jumps/flashes (shown only once css is loaded)
*/
consent_modal.style.visibility = overlay.style.visibility = "hidden";
overlay.style.opacity = 0;
// Use insertAdjacentHTML instead of innerHTML
consent_title.insertAdjacentHTML('beforeend', conf_params.languages[lang]['consent_modal']['title']);
consent_text.insertAdjacentHTML('beforeend', conf_params.languages[lang]['consent_modal']['description']);
consent_primary_btn[innerText] = conf_params.languages[lang]['consent_modal']['primary_btn']['text'];
consent_secondary_btn[innerText] = conf_params.languages[lang]['consent_modal']['secondary_btn']['text'];
var accept_type = -1; // accept current selection
if(conf_params.languages[lang]['consent_modal']['primary_btn']['role'] == 'accept_all'){
accept_type = 1; // accept all
}
_addEvent(consent_primary_btn, "click", function(){
_cookieconsent.hide();
_log("CookieConsent [ACCEPT]: cookie_consent was accepted!");
_saveCookiePreferences(conf_params, accept_type);
});
if(conf_params.languages[lang]['consent_modal']['secondary_btn']['role'] == 'accept_necessary'){
_addEvent(consent_secondary_btn, 'click', function(){
_cookieconsent.hide();
_saveCookiePreferences(conf_params, 0); // 0 => accept necessary only
});
}else{
_addEvent(consent_secondary_btn, 'click', function(){
_cookieconsent.showSettings(0);
});
}
consent_modal_inner_inner.appendChild(consent_title);
consent_modal_inner_inner.appendChild(consent_text);
consent_buttons.appendChild(consent_primary_btn);
consent_buttons.appendChild(consent_secondary_btn);
consent_modal_inner.appendChild(consent_modal_inner_inner);
consent_modal_inner.appendChild(consent_buttons);
consent_modal.appendChild(consent_modal_inner);
// Append consent modal to main container
all_modals_container.appendChild(consent_modal);
all_modals_container.appendChild(overlay);
}
/**
* Create all consent_modal elements
*/
settings_container = _createNode('div');
var settings_container_valign = _createNode('div');
var settings = _createNode('div');
var settings_container_inner = _createNode('div');
settings_inner = _createNode('div');
var settings_title = _createNode('div');
var settings_header = _createNode('div');
var settings_close_btn = _createNode('button');
var settings_close_btn_container = _createNode('div');
var settings_blocks = _createNode('div');
var overlay = _createNode('div');
/**
* Set ids
*/
settings_container.id = 's-cnt';
settings_container_valign.id = "c-vln";
settings_container_inner.id = "c-s-in";
settings.id = "cs";
settings_title.id = 's-ttl';
settings_inner.id = 's-inr';
settings_header.id = "s-hdr";
settings_blocks.id = 's-bl';
settings_close_btn.id = 's-c-bn';
overlay.id = 'cs-ov';
settings_close_btn_container.id = 's-c-bnc';
settings_close_btn.className = 'c-bn';
settings_close_btn.setAttribute('aria-label', conf_params.languages[lang]['settings_modal']['close_btn_label'] || 'Close');
settings_container.setAttribute('role', 'dialog');
settings_container.setAttribute('aria-modal', 'true');
settings_container.setAttribute('aria-hidden', 'true');
settings_container.setAttribute('aria-labelledby', 's-ttl');
settings_title.setAttribute('role', 'heading');
settings_container.style.visibility = overlay.style.visibility = "hidden";
overlay.style.opacity = 0;
settings_close_btn_container.appendChild(settings_close_btn);
// If 'esc' key is pressed inside settings_container div => hide settings
_addEvent(settings_container_valign, 'keydown', function(evt){
evt = evt || window.event;
if (evt.keyCode == 27) {
_cookieconsent.hideSettings(0);
}
}, true);
_addEvent(settings_close_btn, 'click', function(){
_cookieconsent.hideSettings(0);
});
var all_blocks = conf_params.languages[_config.current_lang]['settings_modal']['blocks'];
var n_blocks = all_blocks.length;
// Set settings modal title
settings_title.insertAdjacentHTML('beforeend', conf_params.languages[_config.current_lang]['settings_modal']['title']);
// Create settings modal content (blocks)
for(var i=0; i<n_blocks; ++i){
// Create title
var block_section = _createNode('div');
var block_table_container = _createNode('div');
var block_desc = _createNode('div');
var block_title_container = _createNode('div');
block_section.className = 'c-bl';
block_table_container.className = 'desc';
block_desc.className = 'p';
block_title_container.className = 'title';
// Sset title and description for each block
block_desc.insertAdjacentHTML('beforeend', all_blocks[i]['description']);
// Create toggle if specified (opt in/out)
if(typeof all_blocks[i]['toggle'] !== 'undefined'){
var accordion_id = "c-ac-"+i;
// Create button (to collapse/expand block description)
var block_title_btn = _createNode('button');
var block_switch_label = _createNode('label');
var block_switch = _createNode('input');
var block_switch_span = _createNode('span');
var label_text_span = _createNode('span');
// These 2 spans will contain each 2 pseudo-elements to generate 'tick' and 'x' icons
var block_switch_span_on_icon = _createNode('span');
var block_switch_span_off_icon = _createNode('span');
block_title_btn.className = 'b-tl';
block_switch_label.className = 'b-tg';
block_switch.className = 'c-tgl';
block_switch_span_on_icon.className = 'on-i';
block_switch_span_off_icon.className = 'off-i';
block_switch_span.className = 'c-tg';
label_text_span.className = "t-lb";
block_title_btn.setAttribute('aria-expanded', 'false');
block_title_btn.setAttribute('aria-controls', accordion_id);
block_switch.type = 'checkbox';
block_switch_span.setAttribute('aria-hidden', 'true');
var cookie_category = all_blocks[i]['toggle'].value;
block_switch.value = cookie_category;
label_text_span[innerText] = all_blocks[i]['title'];
block_title_btn.insertAdjacentHTML('beforeend', all_blocks[i]['title']);
block_title_container.appendChild(block_title_btn);
block_switch_span.appendChild(block_switch_span_on_icon);
block_switch_span.appendChild(block_switch_span_off_icon);
/**
* If never accepted => generate toggles with the states defined in the config. object
* Otherwise, retrieve values from saved cookie
*/
if(never_accepted){
if(_inArray(JSON.parse(_saved_cookie_content).level, cookie_category) > -1){
block_switch.checked = true;
toggle_states.push(true);
}else{
toggle_states.push(false);
}
}else if(all_blocks[i]['toggle']['enabled']){
block_switch.checked = true;
}
/**
* Set toggle as readonly if true (disable checkbox)
*/
if(all_blocks[i]['toggle']['readonly']){
block_switch.disabled = true;
block_switch.setAttribute('aria-readonly', 'true');
_addClass(block_switch_span, 'c-ro');
}
_addClass(block_table_container, 'b-acc');
_addClass(block_title_container, 'b-bn');
_addClass(block_section, 'b-ex');
block_table_container.id = accordion_id;
block_table_container.setAttribute('aria-hidden', 'true');
block_switch_label.appendChild(block_switch);
block_switch_label.appendChild(block_switch_span);
block_switch_label.appendChild(label_text_span);
block_title_container.appendChild(block_switch_label);
/**
* On button click handle the following :=> aria-expanded, aria-hidden and act class for current block
*/
(function(accordion, block_section, btn){
_addEvent(block_title_btn, 'click', function(){
if(!_hasClass(block_section, 'act')){
_addClass(block_section, 'act');
btn.setAttribute('aria-expanded', 'true');
accordion.setAttribute('aria-hidden', 'false');
}else{
_removeClass(block_section, 'act');
btn.setAttribute('aria-expanded', 'false');
accordion.setAttribute('aria-hidden', 'true');
}
}, false);
})(block_table_container, block_section, block_title_btn);
}else{
/**
* If block is not a button (no toggle defined),
* create a simple div instead
*/
var block_title = _createNode('div');
block_title.className = 'b-tl';
block_title.setAttribute('role', 'heading');
block_title.setAttribute('aria-level', '3');
block_title.insertAdjacentHTML('beforeend', all_blocks[i]['title']);
block_title_container.appendChild(block_title);
}
block_section.appendChild(block_title_container);
block_table_container.appendChild(block_desc);
// [NEW]
var remove_cookie_tables = conf_params['remove_cookie_tables'] === true;
// if cookie table found, generate table for this block
if(!remove_cookie_tables && typeof all_blocks[i]['cookie_table'] !== 'undefined'){
var tr_tmp_fragment = document.createDocumentFragment();
var all_table_headers = conf_params.languages[_config.current_lang]['settings_modal']['cookie_table_headers'];
/**
* Use custom table headers
*/
for(var p=0; p<all_table_headers.length; ++p){
// create new header
var th1 = _createNode('th');
var obj = all_table_headers[p];
th1.setAttribute('scope', 'col');
// get custom header content
if(obj){
var new_column_key = obj && _getKeys(obj)[0];
th1[innerText] = all_table_headers[p][new_column_key];
tr_tmp_fragment.appendChild(th1);
}
}
var tr_tmp = _createNode('tr');
tr_tmp.appendChild(tr_tmp_fragment);
// create table header & append fragment
var thead = _createNode('thead');
thead.appendChild(tr_tmp);
// append header to table
var block_table = _createNode('table');
block_table.appendChild(thead);
var tbody_fragment = document.createDocumentFragment();
// create table content
for(var n=0; n<all_blocks[i]['cookie_table'].length; n++){
var tr = _createNode('tr');
for(var g=0; g<all_table_headers.length; ++g){
// get custom header content
var obj = all_table_headers[g];
if(obj){
var new_column_key = _getKeys(obj)[0];
var td_tmp = _createNode('td');
// Allow html inside table cells
td_tmp.insertAdjacentHTML('beforeend', all_blocks[i]['cookie_table'][n][new_column_key]);
td_tmp.setAttribute('data-column', obj[new_column_key]);
tr.appendChild(td_tmp);
}
}
tbody_fragment.appendChild(tr);
}
// append tbody_fragment to tbody & append the latter into the table
var tbody = _createNode('tbody');
tbody.appendChild(tbody_fragment);
block_table.appendChild(tbody);
//block_section.appendChild(block_table);
block_table_container.appendChild(block_table);
}
block_section.appendChild(block_table_container);
// append block inside settings dom
settings_blocks.appendChild(block_section);
}
// Create settings buttons
var settings_buttons = _createNode('div');
var settings_save_btn = _createNode('button');
var settings_accept_all_btn = _createNode('button');
settings_buttons.id = 's-bns';
settings_save_btn.id = 's-sv-bn';
settings_accept_all_btn.id = 's-all-bn';
settings_save_btn.className ='c-bn';
settings_accept_all_btn.className ='c-bn';
settings_save_btn.insertAdjacentHTML('beforeend', conf_params.languages[_config.current_lang]['settings_modal']['save_settings_btn']);
settings_accept_all_btn.insertAdjacentHTML('beforeend', conf_params.languages[_config.current_lang]['settings_modal']['accept_all_btn']);
settings_buttons.appendChild(settings_accept_all_btn);
settings_buttons.appendChild(settings_save_btn);
// Add save preferences button onClick event
// Hide both settings modal and consent modal
_addEvent(settings_save_btn, 'click', function(){
_cookieconsent.hideSettings();
_cookieconsent.hide();
_saveCookiePreferences(conf_params, -1);
});
_addEvent(settings_accept_all_btn, 'click', function(){
_cookieconsent.hideSettings();
_cookieconsent.hide();
_saveCookiePreferences(conf_params, 1);
});
settings_header.appendChild(settings_title);
settings_header.appendChild(settings_close_btn_container);
settings_inner.appendChild(settings_header);
settings_inner.appendChild(settings_blocks);
settings_inner.appendChild(settings_buttons);
settings_container_inner.appendChild(settings_inner);
settings.appendChild(settings_container_inner);
settings_container_valign.appendChild(settings);
settings_container.appendChild(settings_container_valign);
all_modals_container.appendChild(settings_container);
all_modals_container.appendChild(overlay);
// Finally append everything to body (main_container holds both modals)
(root || document.body).appendChild(main_container);
}
/**
* Save cookie preferences
* accept_type = 0: accept necessary only
* accept_type = 1: accept all
* accept_type = -1: accept selection
*/
var _saveCookiePreferences = function(conf_params, accept_type){
// Get all cookiepreferences values saved in cookieconsent settings modal
var category_toggles = document.querySelectorAll('.c-tgl') || [];
var c_cookie_level = '', changedSettings = [], must_reload = false;
// If there are opt in/out toggles ...
if(category_toggles.length > 0){
switch(accept_type){
case -1:
//accept current selection
for(var i=0; i<category_toggles.length; i++){
if(category_toggles[i].checked){
c_cookie_level+='"'+category_toggles[i].value+'",';
if(!toggle_states[i]){
changedSettings.push(category_toggles[i].value);
toggle_states[i] = true;
}
}else{
if(toggle_states[i]){
changedSettings.push(category_toggles[i].value);
toggle_states[i] = false;
}
}
}
break;
case 0:
// disable all except necessary
for(var i=0; i<category_toggles.length; i++){
if(category_toggles[i].disabled){
c_cookie_level += '"' + category_toggles[i].value + '",';
toggle_states[i] = true;
}else{
category_toggles[i].checked = false;
if(toggle_states[i]){
changedSettings.push(category_toggles[i].value);
toggle_states[i] = false;
}
}
}
break;
case 1:
// enable all
for(var i=0; i<category_toggles.length; i++){
category_toggles[i].checked = true;
c_cookie_level += '"' + category_toggles[i].value +'",';
if(!toggle_states[i]){
changedSettings.push(category_toggles[i].value);
}
toggle_states[i] = true;
}
break;
}
// remove last ',' character
c_cookie_level = c_cookie_level.slice(0, -1);
/**
* If autoclear_cookies==true -> delete all cookies which are unused (based on selected preferences)
*/
if(conf_params['autoclear_cookies'] && cookie_consent_accepted && changedSettings.length > 0){
// Get array of all blocks defined inside settings
var all_blocks = conf_params.languages[_config.current_lang]['settings_modal']['blocks'];
// Get number of blocks
var len = all_blocks.length;
var count = -1;
// Retrieve all cookies
var all_cookies_array = _getCookie('', 'all');
// delete cookies on 'www.domain.com' and '.www.domain.com' (can also be without www)
var domains = [_config.cookie_domain, '.'+_config.cookie_domain];
// if domain has www, delete cookies also for 'domain.com' and '.domain.com'
if(_config.cookie_domain.slice(0, 4) === 'www.'){
var non_www_domain = _config.cookie_domain.substr(4); // remove first 4 chars (www.)
domains.push(non_www_domain);
domains.push('.' + non_www_domain);
}
// For each block
for(var jk=0; jk<len; jk++){
// Save current block (local scope & less accesses -> ~faster value retrieval)
var curr_block = all_blocks[jk];
// If current block has a toggle for opt in/out
if(curr_block.hasOwnProperty('toggle')){
// if current block has a cookie table, an off toggle,
// and its preferences were just changed => delete cookies
if(
!toggle_states[++count] &&
curr_block.hasOwnProperty('cookie_table') &&
_inArray(changedSettings, curr_block['toggle']['value']) > -1
){
var curr_cookie_table = curr_block['cookie_table'];
// Get first property name
var ckey = _getKeys(conf_params.languages[_config.current_lang]['settings_modal']['cookie_table_headers'][0])[0];
// Get number of cookies defined in cookie_table
var clen = curr_cookie_table.length;
// set "must_reload" to true if reload=on_disable
if(curr_block['toggle']['reload'] === 'on_disable') must_reload = true;
// for each row defined in the cookie table
for(var hk=0; hk<clen; hk++){
// Get current row of table (corresponds to all cookie params)
var curr_row = curr_cookie_table[hk], found_cookies = [];
var curr_cookie_name = curr_row[ckey];
var is_regex = curr_row['is_regex'] || false;
var curr_cookie_domain = curr_row['domain'] || null;
var curr_cookie_path = curr_row['path'] || false;
// set domain to the specified domain
curr_cookie_domain && ( domains = [curr_cookie_domain, '.'+curr_cookie_domain]);
// If regex provided => filter cookie array
if(is_regex){
for(var n=0; n<all_cookies_array.length; n++){
if(all_cookies_array[n].match(curr_cookie_name)){
found_cookies.push(all_cookies_array[n]);
}
}
}else{
var found_index = _inArray(all_cookies_array, curr_cookie_name);
if(found_index > -1) found_cookies.push(all_cookies_array[found_index]);
}
_log("CookieConsent [AUTOCLEAR]: search cookie: '" + curr_cookie_name + "', found:", found_cookies);
// If cookie exists -> delete it
if(found_cookies.length > 0){
_eraseCookies(found_cookies, curr_cookie_path, domains);
curr_block['toggle']['reload'] === 'on_clear' && (must_reload = true);
}
}
}
}
}
}
}
_saved_cookie_content = '{"level": ['+c_cookie_level+']}';
// save cookie with preferences 'level' (only if never accepted or settings were updated)
if(!cookie_consent_accepted || changedSettings.length > 0)
_setCookie(_config.cookie_name, _saved_cookie_content);
_manageExistingScripts();
if(typeof conf_params['onAccept'] === "function" && !cookie_consent_accepted){
cookie_consent_accepted = true;
return conf_params['onAccept'](JSON.parse(_saved_cookie_content));
}
// fire onChange only if settings were changed
if(typeof conf_params['onChange'] === "function" && changedSettings.length > 0){
conf_params['onChange'](JSON.parse(_saved_cookie_content));
}
/**
* reload page if needed
*/
if(must_reload){
window.location.reload();
}
}
/**
* Load style via ajax in background (and then show modal)
* @param {String} css_path
* @param {Function} callback
*/
var _loadCSS = function(css_path, callback){
// Enable if given path is string and non empty
var enable = typeof css_path === 'string' && css_path != "";
if(enable && !document.getElementById('cc--style')){
// Create style tag
var style = _createNode('style');
// ad an id so that in SPA apps (react-like) the style doesn't get loaded multiple times when plugin is called
style.id = 'cc--style';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
// Necessary for <IE9
style.setAttribute('type', 'text/css');
if(style.styleSheet){ // if <IE9
style.styleSheet.cssText = this.responseText;
}else{ // all other browsers
style.appendChild(document.createTextNode(this.responseText));
}
// Append css text content
document.getElementsByTagName('head')[0].appendChild(style);
_log("CookieConsent [AUTOLOAD_CSS]: loaded style = '"+ css_path + "'");
callback();
}
};
xhr.open("GET", css_path);
xhr.send();
}else{
callback();
}
}
/**
* Returns index of found elemet inside array, otherwise -1
* @param {Array} arr
* @param {Object} value
* @returns {Number}
*/
var _inArray = function(arr, value){
var len = arr.length;
for(var i=0; i<len; i++){
if(arr[i] == value)
return i;
}
return -1;
}
/**
* Helper function which prints info (console.log())
* @param {Object} print_msg
* @param {Object} optional_param
*/
var _log = function(print_msg, optional_param, error){
ENABLE_LOGS && (!error ? console.log(print_msg, optional_param !== undefined ? optional_param : ' ') : console.error(print_msg, optional_param || ""));
}
/**
* Helper function which creates an HTMLElement object based on 'type' and returns it.
* @param {String} type
* @returns {HTMLElement}
*/
var _createNode = function(type){
var el = document.createElement(type);
if(type === 'button'){
el.setAttribute('type', type);
}
return el;
}
/**
* Get current client's browser language
* Used when 'auto_language' config property is set to 'true' (boolean)
* @returns {String}
*/
var _getBrowserLang = function(){
var browser_lang = navigator.language || navigator.browserLanguage;
browser_lang.length > 2 && (browser_lang = browser_lang[0]+browser_lang[1]);
_log("CookieConsent [LANG]: detected_browser_lang = '"+ browser_lang + "'");
return browser_lang.toLowerCase()
}
/**
* Trap focus inside modal and focuse the first
* focusable element of current active modal
*/
var _handleFocusTrap = function(){
var tabbedOutsideDiv = false;
var tabbedInsideModal = false;
_addEvent(document, 'keydown', function(e){
e = e || window.event;
// If is tab key => ok
if(e.key !== 'Tab') return;
// If there is any modal to focus
if(current_modal_focusable){
// If reached natural end of the tab sequence => restart
if(e.shiftKey){
if (document.activeElement === current_modal_focusable[0]) {
current_modal_focusable[1].focus();
e.preventDefault();
}
}else{
if (document.activeElement === current_modal_focusable[1]) {
current_modal_focusable[0].focus();
e.preventDefault();
}
}
// If have not yet used tab (or shift+tab) and modal is open ...
// Focus the first focusable element
if(!tabbedInsideModal && !clicked_inside_modal){
tabbedInsideModal = true;
!tabbedOutsideDiv && e.preventDefault();
if(e.shiftKey){
if(current_modal_focusable[3]){
if(!current_modal_focusable[2]){
current_modal_focusable[0].focus();
}else{
current_modal_focusable[2].focus();
}
}else{
current_modal_focusable[1].focus();
}
}else{
if(current_modal_focusable[3]){
current_modal_focusable[3].focus();
}else{
current_modal_focusable[0].focus();
}
}
}
}
!tabbedInsideModal && (tabbedOutsideDiv = true);
});
if(document.contains){
_addEvent(main_container, 'click', function(e){
e = e || window.event;
/**
* If click is on the foreground overlay (and not inside settings_modal),
* hide settings modal
*
* Notice: click on div is not supported in IE
*/
if(settings_modal_visible){
if(!settings_inner.contains(e.target)){
_cookieconsent.hideSettings(0);
clicked_inside_modal = false;
}else{
clicked_inside_modal = true;
}
}else if(consent_modal_visible){
if(consent_modal.contains(e.target)){
clicked_inside_modal = true;
}
}
}, true);
}
}
/**
* Manage each modal's layout
* @param {Object} gui_options
*/
var _guiManager = function(gui_options){