New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disabled cookies #205

Closed
chefuss opened this Issue Jul 19, 2017 · 10 comments

Comments

Projects
None yet
10 participants
@chefuss

chefuss commented Jul 19, 2017

Hi, I been reading the documentation from your site, but cannot get to disable the cookies until the user opt-in for them. This is the code:
I don't know what should I put in the //disable or //enable cookies comments from the onInitialise functions.
Hope you can help, thanks in advance!

window.addEventListener("load", function(){
    window.cookieconsent.initialise({
        "palette": {
            "popup": {
              "background": "#edeff5",
              "text": "#838391"
            },
            "button": {
              "background": "#4b81e8"
            }
        },
        "type": "opt-in",
              "content": {
                "message": "En este sitio utilizamos cookies para mejorar la experiencia de navegación.",
                "dismiss": "Lo entiendo",
                "allow": "Permitir Cookies",
                "link": "Política de cookies",
                "href": "/politica-cookies.html"
        },
        onInitialise: function (status) {
          var type = this.options.type;
          var didConsent = this.hasConsented();
          if (type == 'opt-in' && didConsent) {
            // enable cookies
          }
          if (type == 'opt-out' && !didConsent) {
            // disable cookies
          }
        },
        onStatusChange: function(status, chosenBefore) {
          var type = this.options.type;
          var didConsent = this.hasConsented();
          if (type == 'opt-in' && didConsent) {
            // enable cookies
          }
          if (type == 'opt-out' && !didConsent) {
            // disable cookies
          }
        },
         
        onRevokeChoice: function() {
          var type = this.options.type;
          if (type == 'opt-in') {
            // disable cookies
          }
          if (type == 'opt-out') {
            // enable cookies
          }
        }
    })
});
@panta7

This comment has been minimized.

panta7 commented Oct 30, 2017

Same problem here, I don't Know where to put that code. Example: if I would like to prevent cookie from Google Analytics code befor opt-in where have I to put that code, please? Thanks

@johnfoderaro

This comment has been minimized.

johnfoderaro commented Dec 7, 2017

Hi - I am working through a similar issue and I believe I came up with a solution.

Except, for me, all of the cookies I am contending with are third party and I do not control their "flow" from our web server, nor do we set any from our web server. My solution has been to create an object with a few methods.

Here is a rough implementation I worked on today. It'll get your cookie id's via the read method and then you can "delete" the cookie dependent upon the id via the delete method and passing in a cookie id ("delete" is just setting that cookie id value to nothing and setting an expiration date of 1/20/1970):

export const cookiesUtil = {
  read() {
    const cookies = document.cookie.split(';');
    return cookies.map(cookie => cookie.split('=', 1)[0].trim());
  },
  delete(cookieId) {
    let cookies = document.cookie;
    return cookies = `${cookieId}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
  }
}
@rosibabystiupida

This comment has been minimized.

rosibabystiupida commented Feb 19, 2018

Same problem here! I don't know what to insert where there are "// disable cookies" and "// enable cookies"? Someone can give a complete example please? thank you very much!

@chefuss

This comment has been minimized.

chefuss commented Feb 21, 2018

I think nobody will help with this question, but I manage to solve it like this:

  • Note: my only problematic cookie is from google analytics. So I used window['ga-disable-GA_TRACKING_ID'] = true;
    So when I load the cookie with google gtag.js
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('config', 'GA_TRACKING_ID');
 window['ga-disable-GA_TRACKING_ID'] = true;
</script>

Now the cookie from google won't send any data. Then if the user says "yes" :
in the enable cookies:

window['ga-disable-GA_TRACKING_ID'] = false;

if the user says "no":

window['ga-disable-GA_TRACKING_ID'] = false;

The only problem that I still have is that if the user doesn't navigate to another page there is no data sent. I have to see in the google.developers.com how to do the same for onepage sites.

Hope this works for some of you!! if you have another newbie solution post it please!

@drhickerson

This comment has been minimized.

drhickerson commented Mar 28, 2018

Here was my solution:

onStatusChange: function(status) {
    if (this.hasAnswered() && this.hasConsented()) {
      setTimeout(function(){ window.location.reload(true) }, 100);
          // Put Your Google Analytics Tracking Code here
	  }    
  },

I placed this within the window.cookieconsent.initialise brackets, but loaded the google tag manager script outside of the Cookie Consent code, on it's own line. Including it within caused an error; leaving it outside didn't affect the loading of cookies.

Additionally, I added code to remove the google cookies, which linger on revoking permission if you load the analytics code this way. I put this directly beneath the code above:

onRevokeChoice: function() {
	function clearCookie(d,b,c){try{if(function(h){var e=document.cookie.split(";"),a="",f="",g="";for(i=0;i<e.length;i++){a=e[i].split("=");f=a[0].replace(/^\s+|\s+$/g,"");if(f==h){if(a.length>1)g=unescape(a[1].replace(/^\s+|\s+$/g,""));return g}}return null}(d)){b=b||document.domain;c=c||"/";document.cookie=d+"=; expires="+new Date+"; domain="+b+"; path="+c}}catch(j){}};
	clearCookie('_ga','. yourdomain.com','/');
	clearCookie('_gat_gtag_YOUR_TRACKING_ID','. yourdomain.com','/');
	clearCookie('_gid','.yourdomain.com','/');
	clearCookie('__atuvc','.google.com','/');
	clearCookie('__atuvc','.google.com','/');
	setTimeout(function(){ window.location.reload(true) }, 100);
  },

This forces a browser window refresh, which I found necessary for the clearing of the cookies.

Hope this helps.

Addendum:
The Clear Cookie Code appears to work fine on all desktop computer (Mac & PC) browsers except f0r the Google tags (_ga, _gat_gtag_YOUR_TRACKING_ID, and _gid) in the current version of Safari on Mac. If anyone has suggestions on why this is happening and a fix, I'd be interested.

@nikosdion nikosdion referenced this issue Apr 21, 2018

Closed

Cookie consent #2

@Rohaty

This comment has been minimized.

Rohaty commented Apr 26, 2018

Hi,
if you do not want to send data to Google Analytics unless the user agrees cookies, use the Google Tag Manager and Simo Ahava solution, which is here:

https://www.simoahava.com/gtm-tips/opt-out-of-google-analytics-tracking/
https://www.simoahava.com/gtm-tips/respect-opt-out-from-advertising-and-analytics/

Use "cookieconsent_status" as 1st Party Cookie variables. Elegant, simple, efficient.

@Reshmysandeep

This comment has been minimized.

Reshmysandeep commented May 23, 2018

Hi all,
I'm facing some issue using cookie consent. I have tried this code
window['ga-disable-GA_TRACKING_ID'] = true; for disable google analytics .

If in case the browser user needs to enable it again, where I have to put the code to enable Google Analytics. Please help me on this here am sharing my code sample.


 window.addEventListener("load", function () {
            window.cookieconsent.initialise({
                "palette": {
                    "popup": {
                        "background": "#4c996b"
                    },
                    "button": {
                        "background": "#384c54"
                    }
                },
                revokable:true,
                "type": "opt-out",
                "content": {
                    "dismiss": "Allow Cookies",
                    "deny": "Decline",
                    "href": ""
                },
                onStatusChange: function (status, chosenBefore) {
                   
                    if (type == 'opt-out' && !didConsent)
                    {
                        gaOptout();
                    }
                    if(type == 'opt-out' && didConsent)
                    {
                        //enable cookies
                    }
                   
                },
               
            });
        });



        function gaOptout() {
            window[disableStr] = true;
            document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';

        }

    </script>
@dlangh

This comment has been minimized.

dlangh commented May 31, 2018

Hi,

I struggled with this as well. The problem with removing specific cookies is there will always be another that can popup. I finally managed to figure this out.

Here is my code:

function disableCookies() {
		if(!document.__defineGetter__) {
    		Object.defineProperty(document, 'cookie', {
        		set: function(){ return true; }
    			});
			}
	 	else {
	     	document.__defineSetter__("cookie", function() {} );
		 	}
		}

function enableCookies() {
		delete document.cookie; 
		}

I've tested in FF, Chrome and Safari and it works . I believe it will work in at least IE 8. What took me a while to figure out with re-enabling cookies was I was trying delete the 'set' property/method directly, you have to delete the cookie object itself, which BTW does not delete anything already present before you call disableCookie(), it simply re-exposes the original cookie object. Basically when you call disableCookies, it prevents any cookie set in Javascript from actually being added, any code that tries to set a cookie will just be ignored. Then if you tie in the enableCookies() to your 'Accept' Button your back in business

@Reshmysandeep

This comment has been minimized.

Reshmysandeep commented Jun 5, 2018

Hi All,

Am not sure this is correct way or not, But this worked for me. Please find the code below

Added these reference links to my page

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css" />
    <script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.js"></script>
<script>




        window.addEventListener("load", function () {
            window.cookieconsent.initialise({
                container: document.getElementById("content"),
                "palette": {
                    "popup": {
                        "background": "#4c996b"
                    },
                    "button": {
                        "background": "#384c54"
                    }
                },
                "revokable": true,
                "autoOpen":true,
                "type": "opt-out",
                "content": {
                    "dismiss": "Allow Cookies",
                    "deny": "Decline",
                    "href": ""
                },

                onInitialise: function (status) {
                    var type = this.options.type;
                    var didConsent = this.hasConsented();
                   
                    if (type == 'opt-out' && !didConsent) {
                        gaOptout();
                       
                        if (this.options.revokable) {
                          
                            setTimeout(function () {
                                document.getElementsByClassName("cc-revoke")[0].style.display = "block";
                            });
                        }
                    }
                },
                onStatusChange: function (status, chosenBefore) {
                    var type = this.options.type;
                    
                    var didConsent = this.hasConsented();
                   
                    if (type == 'opt-out' && !didConsent) {
                        gaOptout();
                    }
                    if (type == 'opt-out' && didConsent) {
                        //enable cookies
                        enablecookies();
                    }

                }
               
            });
        });

   
 </script>
<script>
        // Set to the same value as the web property used on the site
        var gaProperty = 'UA-xxxxxx-x';

        // Disable tracking if the opt-out cookie exists.
        var disableStr = 'ga-disable-' + gaProperty;
        if (document.cookie.indexOf(disableStr + '=true') > -1) {
            window[disableStr] = true;
        }
       // console.log(document.cookie);
        // Opt-out function
        function gaOptout() {
            document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
            window[disableStr] = true;

           // console.log(document.cookie);
        }

        function enablecookies() {
           
            window.dataLayer = window.dataLayer || [];
            function gtag() {
                dataLayer.push(arguments)
            }

            gtag('js', new Date());
            gtag('config', 'UA-xxxxxxx-x', { 'anonymize_ip': true });
            window[disableStr] = false;
        }


    </script>




@niuso

This comment has been minimized.

niuso commented Jun 22, 2018

Hello dlangh,
Hi. Could you explain your solution better?
Where do we insert the code?
I have added your code followed by the original code and it does not work.
Thank you.

NOT WORK
`<script>

window.addEventListener("load", function(){
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#252e39"
},
"button": {
"background": "#c2aa2b"
}
},
"type": "opt-in",
"content": {
"message": "Texto del banner",
"dismiss": "dismiss",
"allow": "ALLOW",
"deny": "DENY",
"link": "Política de cookies",
"href": ".mienlaceapoliticadeprivacidad"
}
})});

function disableCookies() {
if(!document.defineGetter) {
Object.defineProperty(document, 'cookie', {
set: function(){ return true; }
});
}
else {
document.defineSetter("cookie", function() {} );
}
}

function enableCookies() {
delete document.cookie;
}

</script>`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment