UNPKG

14.2 kBJavaScriptView Raw
1/*
2 Plugin Name: Cookie Popup
3 @description: Cookie Popup is a free & simple solution to the EU cookie law.
4 version": "1.7.32
5*/
6
7
8
9/*
10 * Available languages array
11 */
12
13
14
15
16
17var CookieLanguages = [
18 'ca',
19 'cs',
20 'da',
21 'de',
22 'en',
23 'es',
24 'fr',
25 'hu',
26 'it',
27 'nl',
28 'pl',
29 'pt',
30 'ro',
31 'ru',
32 'se',
33 'sk',
34 'sl'
35];
36
37var cookieLawStates = [
38 'AT',
39 'BE',
40 'BG',
41 'CY',
42 'CZ',
43 'DE',
44 'DK',
45 'EE',
46 'EL',
47 'ES',
48 'FI',
49 'FR',
50 'GB',
51 'HR',
52 'HU',
53 'IE',
54 'IT',
55 'LT',
56 'LU',
57 'LV',
58 'MT',
59 'NL',
60 'PL',
61 'PT',
62 'RO',
63 'SE',
64 'SI',
65 'SK'
66];
67
68
69/**
70 * Main function
71 */
72
73function setupCookieBar() {
74 var scriptPath = getScriptPath();
75 var cookieBar;
76 var button;
77 var buttonNo;
78 var prompt;
79 var promptBtn;
80 var promptClose;
81 var promptContent;
82 var promptNoConsent;
83 var cookiesListDiv;
84 var detailsLinkText;
85 var detailsLinkUrl;
86 var startup = false;
87 var shutup = false;
88
89 // Get the users current cookie selection
90 var currentCookieSelection = getCookie();
91
92 /**
93 * If cookies are disallowed, delete all the cookies at every refresh
94 * @param null
95 * @return null
96 */
97 if (currentCookieSelection == 'CookieDisallowed') {
98 removeCookies();
99 setCookie('cookiebar', 'CookieDisallowed');
100 }
101
102 // Stop further execution,
103 // if the user already allowed / disallowed cookie usage.
104 if (currentCookieSelection !== undefined) {
105 return;
106 }
107
108 /**
109 * Load plugin only if needed:
110 * show if the "always" parameter is set
111 * do nothing if cookiebar cookie is set
112 * show only for european users
113 * @param null
114 * @return null
115 */
116
117 // Init cookieBAR without geoip localization, if it was explicitly disabled.
118 if (getURLParameter('noGeoIp')) {
119 startup = true;
120 initCookieBar();
121 }
122
123 // Otherwise execute geoip localization and init cookieBAR afterwards.
124 else {
125 // If the user is in EU, then STARTUP
126 var checkEurope = new XMLHttpRequest();
127 checkEurope.open('GET', '//freegeoip.net/json/', true);
128 checkEurope.onreadystatechange = function() {
129 // Don't process anything else besides finished requests.
130 if (checkEurope.readyState !== 4) {
131 return;
132 }
133
134 // Immediately clear timeout handler in order to avoid multiple executions.
135 clearTimeout(xmlHttpTimeout);
136
137 // Process response on case of a successful request.
138 if (checkEurope.status === 200) {
139 var country = JSON.parse(checkEurope.responseText).country_code;
140 if (cookieLawStates.indexOf(country) > -1) {
141 startup = true;
142 } else {
143 shutup = true;
144 }
145 }
146
147 // Enforce startup, if the webservice returned an error.
148 else {
149 startup = true;
150 }
151
152 // Init cookieBAR after geoip localization was finished.
153 initCookieBar();
154 };
155
156 /*
157 * Using an external service for geoip localization could be a long task
158 * If it takes more than 1.5 second, start normally
159 */
160 var xmlHttpTimeout = setTimeout(function () {
161 console.log('cookieBAR - Timeout for ip geolocation');
162
163 // Make sure, that checkEurope.onreadystatechange() is not called anymore
164 // in order to avoid possible multiple executions of initCookieBar().
165 checkEurope.onreadystatechange = function() {};
166
167 // Abort geoip localization.
168 checkEurope.abort();
169
170 // Init cookieBAR after geoip localization was aborted.
171 startup = true;
172 initCookieBar();
173 }, 1500);
174
175 checkEurope.send();
176 }
177
178
179 /**
180 * Initialize cookieBAR according to the startup / shutup values.
181 * @return null
182 */
183 function initCookieBar() {
184 // If at least a cookie or localstorage is set, then STARTUP
185 if (document.cookie.length > 0 || window.localStorage.length > 0) {
186 var accepted = getCookie();
187 if (accepted === undefined) {
188 startup = true;
189 } else {
190 shutup = true;
191 }
192 }
193
194 // If cookieBAR should always be show, then STARTUP
195 if (getURLParameter('always')) {
196 startup = true;
197 }
198
199 if (startup === true && shutup === false) {
200 startCookieBar();
201 }
202 }
203
204 /**
205 * Load external files (css, language files etc.)
206 * @return null
207 */
208 function startCookieBar() {
209 var userLang = detectLang();
210
211 // Load CSS file
212 var theme = '';
213 if (getURLParameter('theme')) {
214 theme = '-' + getURLParameter('theme');
215 }
216 var path = scriptPath.replace(/[^\/]*$/, '');
217 var minified = (scriptPath.indexOf('.min') > -1) ? '.min' : '';
218 var stylesheet = document.createElement('link');
219 stylesheet.setAttribute('rel', 'stylesheet');
220 stylesheet.setAttribute('href', path + 'cookiebar' + theme + minified + '.css');
221 document.head.appendChild(stylesheet);
222
223 // Load the correct language messages file and set some variables
224 var request = new XMLHttpRequest();
225 request.open('GET', path + 'lang/' + userLang + '.html', true);
226 request.onreadystatechange = function() {
227 if (request.readyState === 4 && request.status === 200) {
228 var element = document.createElement('div');
229 element.innerHTML = request.responseText;
230 document.getElementsByTagName('body')[0].appendChild(element);
231
232 cookieBar = document.getElementById('cookie-bar');
233 button = document.getElementById('cookie-bar-button');
234 buttonNo = document.getElementById('cookie-bar-button-no');
235 prompt = document.getElementById('cookie-bar-prompt');
236
237 promptBtn = document.getElementById('cookie-bar-prompt-button');
238 promptClose = document.getElementById('cookie-bar-prompt-close');
239 promptContent = document.getElementById('cookie-bar-prompt-content');
240 promptNoConsent = document.getElementById('cookie-bar-no-consent');
241
242 thirdparty = document.getElementById('cookie-bar-thirdparty');
243 tracking = document.getElementById('cookie-bar-tracking');
244
245 scrolling = document.getElementById('cookie-bar-scrolling');
246 privacyPage = document.getElementById('cookie-bar-privacy-page');
247 privacyLink = document.getElementById('cookie-bar-privacy-link');
248
249 if (!getURLParameter('showNoConsent')) {
250 promptNoConsent.style.display = 'none';
251 buttonNo.style.display = 'none';
252 }
253
254 if (getURLParameter('blocking')) {
255 fadeIn(prompt, 500);
256 promptClose.style.display = 'none';
257 }
258
259 if (getURLParameter('thirdparty')) {
260 thirdparty.style.display = 'block';
261 }
262
263 if (getURLParameter('tracking')) {
264 tracking.style.display = 'block';
265 }
266
267 if (getURLParameter('hideDetailsBtn')) {
268 promptBtn.style.display = 'none';
269 }
270
271 if (getURLParameter('scrolling')) {
272 scrolling.style.display = 'inline-block';
273 }
274
275 if (getURLParameter('top')) {
276 cookieBar.style.top = 0;
277 setBodyMargin('top');
278 } else {
279 cookieBar.style.bottom = 0;
280 setBodyMargin('bottom');
281 }
282
283 if (getURLParameter('privacyPage')) {
284 var url = decodeURIComponent(getURLParameter('privacyPage'));
285 privacyLink.href = url;
286 privacyPage.style.display = 'inline-block';
287 }
288
289 setEventListeners();
290 fadeIn(cookieBar, 250);
291 setBodyMargin();
292 }
293 };
294 request.send();
295 }
296
297
298 /**
299 * Get this javascript's path
300 * @return {String} this javascript's path
301 */
302 function getScriptPath() {
303 var scripts = document.getElementsByTagName('script');
304
305 for (i = 0; i < scripts.length; i += 1) {
306 if (scripts[i].hasAttribute('src')) {
307 path = scripts[i].src;
308 if (path.indexOf('cookiebar') > -1) {
309 return path;
310 }
311 }
312 }
313 }
314
315 /**
316 * Get browser's language or, if available, the specified one
317 * @return {String} userLang - short language name
318 */
319 function detectLang() {
320 var userLang = getURLParameter('forceLang');
321 if (userLang === false) {
322 userLang = navigator.language || navigator.userLanguage;
323 }
324 userLang = userLang.substr(0, 2);
325 if (CookieLanguages.indexOf(userLang) < 0) {
326 userLang = 'en';
327 }
328 return userLang;
329 }
330
331 /**
332 * Get a list of all cookies
333 * @param {HTMLElement} cookiesListDiv
334 * @return {void}
335 */
336 function listCookies(cookiesListDiv) {
337 var cookies = [];
338 var i, x, y, ARRcookies = document.cookie.split(';');
339 for (i = 0; i < ARRcookies.length; i += 1) {
340 x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
341 y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
342 x = x.replace(/^\s+|\s+$/g, '');
343 cookies.push(x);
344 }
345 cookiesListDiv.innerHTML = cookies.join(', ');
346 }
347
348 /**
349 * Get Cookie Bar's cookie if available
350 * @return {string} cookie value
351 */
352 function getCookie() {
353 var cookieValue = document.cookie.match(/(;)?cookiebar=([^;]*);?/);
354
355 if (cookieValue == null) {
356 return undefined;
357 } else {
358 return decodeURI(cookieValue[2]);
359 }
360 }
361
362 /**
363 * Write cookieBar's cookie when user accepts cookies :)
364 * @param {string} name - cookie name
365 * @param {string} value - cookie value
366 * @return null
367 */
368 function setCookie(name, value) {
369 var exdays = 30;
370 if (getURLParameter('remember')) {
371 exdays = getURLParameter('remember');
372 }
373
374 var exdate = new Date();
375 exdate.setDate(exdate.getDate() + parseInt(exdays));
376 var cValue = encodeURI(value) + ((exdays === null) ? '' : '; expires=' + exdate.toUTCString() + ';path=/');
377 document.cookie = name + '=' + cValue;
378 }
379
380 /**
381 * Remove all the cookies and empty localStorage when user refuses cookies
382 * @return null
383 */
384 function removeCookies() {
385 // Clear cookies
386 document.cookie.split(';').forEach(function(c) {
387 document.cookie = c.replace(/^\ +/, '').replace(/\=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
388 });
389
390 // Clear localStorage
391 localStorage.clear();
392 }
393
394
395 /**
396 * FadeIn effect
397 * @param {HTMLElement} el - Element
398 * @param {number} speed - effect duration
399 * @return null
400 */
401 function fadeIn(el, speed) {
402 var s = el.style;
403 s.opacity = 0;
404 s.display = 'block';
405 (function fade() {
406 (s.opacity -= -0.1) > 0.9 ? null : setTimeout(fade, (speed / 10));
407 })();
408 }
409
410
411 /**
412 * FadeOut effect
413 * @param {HTMLElement} el - Element
414 * @param {number} speed - effect duration
415 * @return null
416 */
417 function fadeOut(el, speed) {
418 var s = el.style;
419 s.opacity = 1;
420 (function fade() {
421 (s.opacity -= 0.1) < 0.1 ? s.display = 'none' : setTimeout(fade, (speed / 10));
422 })();
423 }
424
425 /**
426 * Add a body tailored bottom (or top) margin so that CookieBar doesn't hide anything
427 * @param {String} where
428 * @return null
429 */
430 function setBodyMargin(where) {
431 setTimeout(function () {
432
433 var height = document.getElementById('cookie-bar').clientHeight;
434
435 var bodyEl = document.getElementsByTagName('body')[0];
436 var bodyStyle = bodyEl.currentStyle || window.getComputedStyle(bodyEl);
437
438 switch (where) {
439 case 'top':
440 bodyEl.style.marginTop = (parseInt(bodyStyle.marginTop) + height) + 'px';
441 break;
442 case 'bottom':
443 bodyEl.style.marginBottom = (parseInt(bodyStyle.marginBottom) + height) + 'px';
444 break;
445 }
446 }, 300);
447 }
448
449 /**
450 * Clear the bottom (or top) margin when the user closes the CookieBar
451 * @return null
452 */
453 function clearBodyMargin() {
454 var height = document.getElementById('cookie-bar').clientHeight;
455
456 if (getURLParameter('top')) {
457 var currentTop = parseInt(document.getElementsByTagName('body')[0].style.marginTop);
458 document.getElementsByTagName('body')[0].style.marginTop = currentTop - height + 'px';
459 } else {
460 var currentBottom = parseInt(document.getElementsByTagName('body')[0].style.marginBottom);
461 document.getElementsByTagName('body')[0].style.marginBottom = currentBottom -height + 'px';
462 }
463 }
464
465 /**
466 * Get ul parameter to look for
467 * @param {string} name - param name
468 * @return {String|Boolean} param value (false if parameter is not found)
469 */
470 function getURLParameter(name) {
471 var set = scriptPath.split(name + '=');
472 if (set[1]) {
473 return set[1].split(/[&?]+/)[0];
474 } else {
475 return false;
476 }
477 }
478
479 /**
480 * Set button actions (event listeners)
481 * @return null
482 */
483 function setEventListeners() {
484 button.addEventListener('click', function() {
485 setCookie('cookiebar', 'CookieAllowed');
486 clearBodyMargin();
487 fadeOut(prompt, 250);
488 fadeOut(cookieBar, 250);
489 if (getURLParameter('refreshPage')) {
490 window.location.reload();
491 }
492 });
493
494 buttonNo.addEventListener('click', function() {
495 var txt = promptNoConsent.textContent.trim();
496 var confirm = window.confirm(txt);
497 if (confirm === true) {
498 removeCookies();
499 setCookie('cookiebar', 'CookieDisallowed');
500 clearBodyMargin();
501 fadeOut(prompt, 250);
502 fadeOut(cookieBar, 250);
503 }
504 });
505
506 promptBtn.addEventListener('click', function() {
507 fadeIn(prompt, 250);
508 });
509
510 promptClose.addEventListener('click', function() {
511 fadeOut(prompt, 250);
512 });
513
514 if (getURLParameter('scrolling')) {
515 var scrollPos = document.body.getBoundingClientRect().top;
516 var scrolled = false;
517 window.addEventListener('scroll', function() {
518 if (scrolled === false) {
519 if (document.body.getBoundingClientRect().top - scrollPos > 250 || document.body.getBoundingClientRect().top - scrollPos < -250) {
520 setCookie('cookiebar', 'CookieAllowed');
521 clearBodyMargin();
522 fadeOut(prompt, 250);
523 fadeOut(cookieBar, 250);
524 scrolled = true;
525 if (getURLParameter('refreshPage')) {
526 window.location.reload();
527 }
528 }
529 }
530 });
531 }
532 }
533}
534
535// Load the script only if there is at least a cookie or a localStorage item
536document.addEventListener('DOMContentLoaded', function() {
537 setupCookieBar();
538});