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