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