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