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