Showing posts with label EU Cookie Compliance. Show all posts
Showing posts with label EU Cookie Compliance. Show all posts

Wednesday, 16 February 2022

Blogger EU Cookie Message Missing Problem & Solution

My EU Cookie Message Disappeared From My Site - How To Get It Back

By Strictly-Software

I had a bit of a weird experience recently, I found out, only from Google informing me, that for some reason one of my Blogger sites was not showing the EU Cookie Notice that should appear on all Blogger sites if in a European country where "Consent to use Cookies", is required by all website users.

It used to show, and my other blogger sites were still working and in fact, on my own PC, it was still showing the correct message e.g:

"This site uses cookies from Google to deliver its services and to analyse traffic. Your IP address and user agent are shared with Google, together with performance and security metrics, to ensure quality of service, generate usage statistics and to detect and address abuse."

However, when I viewed the site Google had told me about on another PC this was not appearing for some reason. 

I cleared all the cookies, path, domain, and session using the Web Extension called "Web Developer Toolbar", such as this Chrome version. After installing it, a grey cog appears in your toolbar if you fix it to. 

It is really helpful for turning password fields into text, if you want to see what you are typing, or need to see a Browser stored password in the field, or as needed in this instance, for deleting all kinds of Cookies. So after deleting all the Cookies, I refreshed the page and but the EU Cookie Message still didn't show.

Fixing Blogger Cookie Notice Not Showing

If you view the source of a blogger site that is showing the EU Cookie message, then you should find the following code in your source, not generated source, but the standard "View Source" options when you right-click on the page and view the context menu.

The following code should be just above the footer where all your widget scripts are loaded. Notice that I put some HTML comments above my version of the code so I could easily identify it from Bloggers version in the DOM when viewing the source. Why do this if Bloggers code is not in the source anyway? Wait and see.

<!-- this is my code as bloggers only appear in the source sometimes -->
<script defer='' src='/js/cookienotice.js'></script>
<script>
 document.addEventListener('DOMContentLoaded', function(event) {
      window.cookieChoices && cookieChoices.showCookieConsentBar && cookieChoices.showCookieConsentBar(
          (window.cookieOptions && cookieOptions.msg) || 'This site uses cookies from Google to deliver its services and to analyse traffic. Your IP address and user agent are shared with Google, together with performance and security metrics, to ensure quality of service, generate usage statistics and to detect and address abuse.',
          (window.cookieOptions && cookieOptions.close) || 'Ok',
          (window.cookieOptions && cookieOptions.learn) || 'Learn more',
          (window.cookieOptions && cookieOptions.link) || 'https://www.blogger.com/go/blogspot-cookies');
});
</script> 

So to fix the issue, copy the code out of the page and then go to your layout tool in Blogger. Add a widget at the bottom if no JavaScript/Text widget already exists and copy the code into it.

Now the odd thing is that as soon as I saved the widget and then my blogger site. I went to the website having issues and viewed the source code. When I did I saw that not only was my version of the code was in the HTML, but somehow this had put Bloggers own version back into the HTML as well!

Why this would do that I have no idea. However, it meant that I now had two lots of the same script being loaded and 2 lots of the EU Cookie code that shows the DIV and the options for wording appearing in my HTML.

The good thing though, is that this did not cause a problem for my site. I found by adding that code into a widget at the bottom of my page above Bloggers magically re-appearing code, that it did NOT cause the message to appear twice, but also that when I removed my own version of the code, the Blogger version remained.

Also even though I have put in a version of the Blogger code that uses English sentences into the HTML when I use a Proxy or VPN to visit a European country such as Germany, the wording appears in German.

I suspect that my code runs first as it's first in the DOM, then the Google code runs, overwriting my DIV with their DIV and of course the correct wording for the country we are in.

So as I thought everything was working, I removed my own code and saved the site. I then went to it, deleted path, domain, and session cookies, and then refreshed the page again and saw the blogger cookie code running okay. When viewing the source I could see that my code had gone but the blogger code was now still in the HTML, whereas it wasn't before.

However......

After a few hours when I came back to the computer which had not been showing the message and I re-checked by clearing all cookies (path, domain and session), and saw that Bloggers code had disappeared again, and the message was now not showing again!

Why this has happened I do not know as I had not re-saved the Blogger site in question during the time away so I have no idea what caused the Blogger EU Code to disappear again

There really should be an option in settings to force the Cookie compliance code to be inserted but as there isn't the answer seems to be to just leave your version of the cookie code in the HTML source in a widget at the bottom of the layout.

Why this works without causing issues I have no idea and it sounds like a bodge which it is, but as I cannot find any real answers to this problem online, or in Googles KB, I had to come up with a solution that worked to comply with Google's request and this seems to do it.

So the fact that when you have two lots of the same code in your HTML does NOT cause the message to appear twice is a good thing. This means that even if the original code re-appears then you are okay, and if it doesn't then your own code, which is a direct copy of the blogger code, runs instead. 

Also as your code runs first, if it is causing Bloggers code to also re-appear in the HTML then that will run afterwards ensuring the correct European language is shown in the message.

You can view the JavaScript which is loaded in by Blogger by just appending /js/cookienotice.js to any blogger site e.g this one, http://blog.strictly-software.com/js/cookienotice.js. You can then see the functions and HTML they use to show the DIV. You can also see at the top the ID's and Classes they put on the Cookie Message DIV.

So if you want to check which version of the EU Cookie code is running when both sets of JavaScript exist, you could add a bit of code underneath that checks for the Cookie DIV on display, and add some CSS to target cookieChoicesInfo, which is the ID of the DIV that is shown and you could change the background colour of the DIV to see if it is your DIV or Bloggers DIV that appears.

For example, you could put this under your JavaScript code to change the background colour of the DIV with the following code.

<style>
#cookieChoiceInfo{
	background-color: green !important;
}
</style>

Obviously green is a horrible colour for a background, but it easily stands out. When I did this I saw a Green DIV appear with the message in the correct language displayed, despite my EU options having English as the language for all the wording. 

This is because our code to load the script, and the cookie options into the page runs first, before any Blogger code that appears lower down in the HTML / DOM. When that Blogger code does run, it overwrites the DIV and the wording in the correct European language.

If you right-click on the DIV and choose "inspect" then the Developer Console will appear and you will be able to see that your style to change the background colour is being used on the Cookie message DIV. 

As it's a CSS style block with !important after the style, when the Blogger code overwrites the DIV and wording, the style for the background colour of the DIV is still being determined by our CSS Style block.

So the answer if your EU Cookie Compliance Message disappears is to add your own copy of their code into the site through a widget. 

This shouldn't cause any problems due to any duplicate DIV overwriting your DIV and if it disappears again then at least your version remains.

I just don't understand two things.

1. Why did the Cookie code disappear in the first place?

2. Why did the Blogger code re-appear when I added my own version of Bloggers own EU Cookie message code into the HTML and then why did it dissapear again a couple of hours? 

If anyone can answer these questions then please let me know. A search inside Googles Adsense site does not reveal any useful answers at all.

People just suggest adding query strings to your URL to force it to appear which is no good if your site is linked to from various Search Engines and other sites. Or to just delete all the cookies and refresh the page. 

These are two useless suggestions, and the only thing that seems to work for me is the solution I came up with above. So if you have the same problem try this solution.


By Strictly-Software

Tuesday, 12 June 2012

New unobtrusive EU Cookie Compliance Code

Some people have said that my JavaScript lightbox method for EU Cookie compliance is a bit off putting for users as it takes them away from the site if they disagree.


Also at the last minute the EU has allowed compliance with their new cookie privacy rules through a much easier method.

This allows sites to show the users that cookies are being used with a link to the sites cookie policy and a button to hide the message in future. If they continue to use the site they have basically agreed to the use of cookies.

You may have noticed on sites like the BBC or Channel 4 etc they will show a little piece of text at the top of the page that slides out and tells the user that cookies are being used with a link to their cookie policy. They also have a button to set a cookie so the message isn't shown again.

This method is a lot less intrusive and doesn't take the user away from the site as there is no "agree" or "disagree" button.

Therefore for those of you not wanting to make use of my EU Cookie compliance code I have created a newer version that follows this new format which can be seen here.

It is up to you to create a cookie policy document that details how cookies can be viewed and disabled through various browsers and toolbars etc. Plus the text and styling is up to you but the example html page shows this new unobtrusive method in action.

The code makes use of jQuery to handle the animations so load in the source code from your usual repository e.g Google or jQuery e.g: http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
  
The actual JavaScript for the html test page is below.


// run immediatley - place in footer
(function(){

 EUCookie = {
  
  confirmed : false,

  Confirm : function(e){   
   var self = this;
   
   // create cookie   
   self.CreateCookie("EUCookie",1,365);  
   
   // slide back in the cookie bar
   $("#cookieWarning").animate({
     height: 0
   }, 300, function(){
    $("#cookieWarning").css("display", "none");
   });
   
   return false;
  },

  CheckEUCookie : function(){

   var self = this,
    val = self.ReadCookie("EUCookie");
   
   // if our cookie has been set
   if(typeof(val)!=undefined && val==1){   
    self.confirmed = true;
   }
 
   return self.confirmed;
  },

  CreateCookie : function(name,value,days) {
 
   if (days){
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
   }else{
    var expires = "";
   }
   
   document.cookie = name+"="+escape(value)+expires+"; path=/";
  },

  ReadCookie : function(name){
   
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0){
     var r = unescape(c.substring(nameEQ.length,c.length));    
     return r;
    }
   }
   return null;
  }
 };

 // add click event;
 $("#cookie-close-button").click(function(){EUCookie.Confirm()});
 
 // if no cookie set show form
 if(EUCookie.CheckEUCookie()){
  
  // cookie already set so hide box
  $("#cookieWarning").css("display", "none");
 }else{
  
  // Show the form - set to zilch then slide out to the appropriate height
  document.getElementById("cookieWarning").style.display = "none";
  document.getElementById("cookieWarning").style.height = 0;
  
  $("#cookieWarning").animate({
     height: 28
   }, 500, function(){
  }).css("display", "block");    
 }
})();

To view the code in action you can visit the demo page and download the html page and tweak it to your hearts desire.

Let me know what you think.

Monday, 30 April 2012

Simple JavaScript EU Cookie Compliance Code

JavaScript code to comply with EU law on Cookies and Privacy whilst browsing.

Something I quickly did at work the other day was useful enough to put up on my site for people to download and use. I have just updated it to make it more customisable and even more useful so I thought I would update the blog as well.

If you live in the European Union you might have been aware of a recent rule for websites that was made many years back but totally ignored up until now.

It is going to take a test case in the courts to resolve it one way or the other but just to be safe and to be compliant with new EU law about cookies I have created a generic EU Cookie / Privacy JavaScript function.

This code can be referenced from any site in the footer (a global footer would be advised) and then your site will become compliant with EU diktats on website privacy and cookies straight away.

The code is wrapped in a self calling function so will be called as soon as the script is loaded into the DOM.

You might want to add a call to the main function call on line 409 of the script into your own onDOM or onWindow ready function to make sure it is called after all other scripts that may load cookies into the users browser last.

// call the CheckCookie function
EUCookie.CheckCookie();


The parameters at the top of the EUCookie object that display the message and the wording for the buttons are all customisable (different languages, different HTML etc) and you can modify the code to pass in different variables as you see fit.

On our site which handles multiple languages and parameters we have handled this by removing the self calling function code from the script just leaving the EUCookie namespace and then in our global footer doing something like this:


<script type="text/javascript" src="/jobboard/scripts/JS/EUCookie.js"></script>
<script type="text/javascript">
 
 // set custom values for the EUCookie object
 EUCookie.EUMessage = '<p>Do you want this site to accept cookies and be compliant with EU law?</p>';
 EUCookie.AgreeText = 'Accept';
 EUCookie.DisagreeText = 'Decline';
 EUCookie.RedirectLink = 'http://www.strictly-software.com/';
 EUCookie.MsgWidth = '400px';
 EUCookie.MsgHeight = '200px';

 // check whether the user wants to use the site with cookies
 EUCookie.CheckCookie();

</script>


As you can see the EUCookie object script - with self calling (function(){ })(); removed is loaded in first and then any parameters you want to change are modified on the singleton before the CheckCookie() function is called.

The script also handles browsers where the user has totally disabled cookies either through a toolbar like the Web Developer Toolbar or through the browser itself and if the user has no cookies passed to it then the message won't even appear.

I have just added in "Paranoid Mode" which is a setting you can turn on which will do the following when testing for cookies.
  • It will not only just check for document.cookie but actually create a test cookie, read it and then delete it before checking it has gone - some old browsers only clear cookies on a new session.
  • It will also set a timer (the length of time in milliseconds is also set by the ParanoidCheckTimer property) that will constantly check the DOM for the re-enabling of cookie use e.g if you use the Web Developer Toolbar you can disable cookies on the fly. If you loaded the page with cookies off and then set them on with the toolbar the ParanoidMode setting will detect the change and show the popup message.

If the user decides they don't want to use cookies and therefore if the site if it relies on them, then they are taken away to another customisable URL the EUCookie.RedirectLink parameter which defaults to my blog at the moment.

Obviously this url could be changed to a cookieless version of your site so that they can continue to use it . Maybe a version designed for mobiles where cookies are not used at all could be a viable option.

If the user clicks on the "I agree" button then a cookie called EUCookie is set for 365 days on their computer and on each subsequent visit it rolls over for another 365 days.

Obviously if the user clears their cookies, or lets an anti-virus scanner or tool like CCleaner remove the EUCookie my script sets, then they will be asked the question again on their next visit. So you might want to change the wording of the message to reflect this.

I have also added another property called AlwaysShowMsg which will always show the warning message whether or not cookies are currently enabled or not. You never know when a 3rd party script or your system might load in a cookie so this might be useful - also check out the ParanoidMode setting.

I have also added in a property called HideScroll which can be set to BODY, HTML or an empty string. This will hide the relevant scrollbars when the lightbox is shown to prevent users scrolling down past the greyed out area. The scrollbars are returned to a setting of "auto" once the DOM is cleared of the cookie messages if agreed to.

I have also added in some code to measure the viewport and the scroll position so that the message box is properly centered in the screen rather than the inline 20% margin style it was using before.

Benefits of this EU Cookie Compliance Script 
  1. It is easily installed and makes any website comply with EU law. 
  2. The code is wrapped in a namespace and therefore you shouldn't get problems with functions overwriting functions etc. 
  3. It uses very simple design inline and backward compatible styles to create a lightbox and "center" the box on the page.
  4. All the major parameters can be customised including the name and value of the EU compliance cookie, the text for the buttons, the redirect link and the styling.
  5. No framework is used or relied upon and all the code is self contained within the script. 
  6. The ParanoidMode option allows you to automatically detect when cookies are switched on or used if the page is loaded without their use. This enables a loaded page to still show the message when it detects cookies being used.
  7. The code is a simple drop into any global footer of your site. Just put a reference to the script in your footer and the script should work (as long as you haven't got previous JavaScript errors).
The only downside is that the script relies on JavaScript to be enabled and for a cookie to be set to tell the website that cookies are allowed. A server side version could be made easily enough but for the 90% of internet users who use JavaScript this script should be good enough.

Plus as most 3rd party cookies are set by advertising or other external scripts with JavaScript then this solution is enough to stop them in their tracks especially with paranoid mode which will kick in whilst you have a loaded page open and an external script decides to attempt to set a cookie 1 minute into your viewing. A server side solution wouldn't handle this.

You can see and download the source code from here: EU Cookie Law Compliance Code

Feel free to make use of it as you want but if you don't change it dramatically (e.g just add a missing ; etc) then please leave the credits at the top of the script.

Hopefully this script will help all of us out and prevent those evil virus spreading cookies from infecting all our computers before it's too late :)