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