Has anyone had any success getting the google analytics code to work? When I try to insert the code from dagomar's post I get this error:

Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.

Comments

Miszel’s picture

Component: User interface » Code
Category: bug » support

I'd suggest trying to disable GA by setting: window['ga-disable-UA-XXXXXX-Y'] = true; as described at he bottom of this page: https://developers.google.com/analytics/devguides/collection/gajs/

Please let us know if it works.

Boffy31’s picture

Status: Closed (fixed) » Active

That has fixed it thanks, the full code I added to the Advanced Settings->Custom JS in google analytics was:

if (!Drupal.eu_cookie_compliance.hasAgreed()){
window['ga-disable-UA-xxxx-1'] = true;
}

In addition, I needed to change the JS position in the module to header rather than footer to get it to render. I don't know why (perhaps an option for this change could be included in the module admin page?)

Miszel’s picture

Status: Active » Closed (fixed)
joco_sp’s picture

Status: Active » Closed (fixed)

#2 worked form me. I put the code in 'Code snippet (before)' and 'JavaScript scope' in Footer.

pat51’s picture

Issue summary: View changes

@Boffy31: I followed your instructions (#2) and everything works fine. Thank you.

<!-- /page -->
  <script src="http://www.mydomain.tld/sites/all/modules/eu-cookie-compliance/js/eu_cookie_compliance.js?n4sqj0"></script>
<script>var _gaq = _gaq || [];_gaq.push(["_setAccount", "UA-1234567-89"]);_gaq.push(["_gat._anonymizeIp"]);if (!Drupal.eu_cookie_compliance.hasAgreed()){
window['ga-disable-UA-1234567-89'] = true;
}_gaq.push(["_trackPageview"]);(function() {var ga = document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(ga, s);})();</script>
<script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-3.newrelic.com","licenseKey":"5cf655ff81","applicationID":"1273055","transactionName":"bwNVNhYDDUJRUUZaW1ZJdgEQCwxfH1xdV1FnFlYFAT0VWFVF","queueTime":0,"applicationTime":411,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-400.min.js"}</script></body>
</html>
pietrocap’s picture

Hi, I'm struggling trying to follow suggestions on this page.

I tryed putting the code in 'Code snippet (before)' and also in 'Code snippet (after)'.

I get a javascript error generated by google analytics:

Uncaught TypeError: Cannot read property 'hasAgreed' of undefined

I can't do as in #4 because 'JavaScript scope' is no more supported in google analytics module options.

Anonymous’s picture

I too have difficulties making it works with Google Analytics module. The ga.js file is printed in the <head> but the eu_cookie_compliance.js file is loaded at the bottom of the page. So calling to Drupal.eu_cookie_compliance.hasAgreed() function before it's loaded will fail, the problem is that I need to load GA in the document <head> for statistics accuracy purpose.

pietrocap’s picture

Hi LaAaZ,
I've just modified eu_cookie_compliance.module and now eu_cookie_compliance.js file is loaded in the header.

In google analytics settings i've pasted

if (!Drupal.eu_cookie_compliance.hasAgreed()){
window['ga-disable-UA-xxxx-1'] = true;
}

the javascript error disapeared and it seems that the GA cookie it's loaded only after the user has agreed.

The eu cookie compliance module seems to work well as before.

If you want you can't try it at http://www.pietrocappai.info

svenryen’s picture

Great, Pietro! Can you please submit a patch for your changes?

androe’s picture

svenryen I don't know how to submit a patch but in eu_cookie_compliance.module at line 126 you should edit

drupal_add_js(drupal_get_path('module', 'eu_cookie_compliance') . '/js/eu_cookie_compliance.js', array('type' => 'file', 'scope' => 'footer'));
  }

and replace footer with header. It works!

pietrocap’s picture

Hi,
it is what I did and said in #8. I'll try to submit a patch.

Anonymous’s picture

Great, thank you very much !
I spotted the line in #10 but I wasn't sure of what I was doing. Do you have a tutorial on how to submit a patch ? That will be handy someday.

pietrocap’s picture

Version: 6.x-1.5 » 7.x-2.x-dev
Assigned: Unassigned » pietrocap
Category: Support request » Bug report
Status: Closed (fixed) » Needs review
StatusFileSize
new1.06 KB

I reopen the issue because it's not fixed with the latest version of google analytics and 7.x-2.x version as said in #11. I upload a patch.

svenryen’s picture

pietrocap’s picture

Hello svenryen,
I followed all the steps at https://www.drupal.org/node/707484 but the patch I'm uploading now seems to be the same as the previous one at #13. If there is something wrong please tell me what to do.

Anonymous’s picture

Thank you svenryen, I'll check this out.

francoud’s picture

I often do not use external modules to add the "google analytics" stuff, I just add the script in the page.tpl.php file in my theme (ok it's not clean but it works ;) Something like:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-xxxxxxxxx-y', 'auto');
  
  if (!Drupal.eu_cookie_compliance.hasAgreed()){
      window['ga-disable-UA-xxxxxxxxx-y'] = true;
  }

  ga('send', 'pageview');

This script works only if I also apply the footer/header patch in #15. So if possible I vote for apply the patch to the -dev version at least :)

svenryen’s picture

Assigned: pietrocap » svenryen

Thanks for the patch, @pietrocap - I'll take a look at it some time soon.

gaëlg’s picture

Here's a patch for Drupal 8. If it's not right to add this logic into the module, it could easily be a separate submodule.

svenryen’s picture

Assigned: svenryen » Unassigned
svenryen’s picture

@pietrocap, thanks you again for the patch. I tried applying it and it doesn't apply to the latest beta release. Do you think you could re-roll it, and I'll take a look an review it?

svenryen’s picture

Status: Needs review » Needs work
svenryen’s picture

Version: 7.x-2.x-dev » 7.x-1.x-dev

@GaëlG Do you think you can open a separate issue with your 8.x patch?

gaëlg’s picture

svenryen’s picture

Component: Code » Miscellaneous
Category: Bug report » Support request
Status: Needs work » Active

I have added an option to -dev to place the script in the header rather than the footer. It's in the Advanced fieldset. This can make it easier for people that want to use `hasAgreed()` to interact with other scripts and block tracing from working until the user has accepted cookies.

  • svenryen committed 79054be on 7.x-1.x
    Issue #1648286 by pietrocap, GaëlG, svenryen: Getting google analytics...
svenryen’s picture

Status: Active » Fixed
svenryen’s picture

Status: Fixed » Closed (fixed)
abaier’s picture

I tried to implement the solution of #2, placing the disable-code inside the google_analytics advanced settings (code before) and setting the EUCC script scope to header – but also got the Uncaught TypeError.

Using the latest dev of EUCC (7.x-1.23+13-dev) I saw that eu_cookie_compliance.module now places its script into the JS_THEME group including weight 100. It works if I remove these settings, which then places the script in JS_DEFAULT, I think, loading before the googleanalytics.js to make hasAgreed() available.

eu_cookie_compliance.module, line 324

drupal_add_js(drupal_get_path('module', 'eu_cookie_compliance') . '/js/eu_cookie_compliance.js', array('type' => 'file', 'scope' => $script_scope, 'group' => JS_THEME, 'weight' => 100));

replaced with

drupal_add_js(drupal_get_path('module', 'eu_cookie_compliance') . '/js/eu_cookie_compliance.js', array('type' => 'file', 'scope' => $script_scope));

What was the purpose of changing the group?

----
EDIT
----

Finally solved it like this

function THEME_js_alter(&$javascript) {
  $javascript[drupal_get_path('module', 'eu_cookie_compliance') . '/js/eu_cookie_compliance.js']['group'] = 'JS_DEFAULT';
  $javascript[drupal_get_path('module', 'eu_cookie_compliance') . '/js/eu_cookie_compliance.js']['weight'] = '0';
}
svenryen’s picture

Status: Closed (fixed) » Active

I don't recall the purpose of changing the group, I'll have to take a look once the GDPR features are implemented. I also have some scheduled vacation after that, so the earliest would be late June.

abaier’s picture

No problem, I can imagine the workload these days … At least I achieved to stop GA tracking before consent was given, for now.

svenryen’s picture

abaier’s picture

Thanks, I am already following the issue. Currently I was searching for a quick solution for a D7 project.

anybody’s picture

Status: Active » Closed (duplicate)

I think we can close this as duplicate of #2971644: Eu cookie compliance support now.

Also see #3060312: Better GDPR compliance: Fix Do not track & EU Cookie Privacy integration for a full featured EU Cookie Compliance solution (with Admin UI) in Google Analytics - no more hacks needed!

b10zgr’s picture

when i try to add to the custom JS i get this message "Uncaught ReferenceError: Drupal is not defined".
google_analytics:
google_analytics:
version: VERSION
js:
js/google_analytics.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings

google_analytics.debug:
version: VERSION
js:
js/google_analytics.debug.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings

google_analytics.admin:
version: VERSION
js:
js/google_analytics.admin.js: {}
dependencies:
- core/jquery
- core/drupal

google_analytics.test:
version: VERSION
js:
src/Tests/GoogleAnalyticsJavaScriptTest.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings

here are my dependencies of google analytics. Any idea where is the problem?

b10zgr’s picture

the problem seems to be that the code is located on the header but because i cant find a way to put google analytics on the bottom, i figured out another way. Please let me know if i''ve done something wrong.

At google analytics->Advanced->Custom JS
There, i set @before "/*" and @after "*/" in order to comment ga("send", "pageview"); that's between.

Then simply i edited my html.html.twig file and inserted the following code @body

<script type="text/javascript">
    if (!Drupal.eu_cookie_compliance.hasAgreed()){
      window['ga-disable-UA-XXXXX-1'] = true;
    }
    ga("send", "pageview");
</script>

and now, even if i still get __ga cookie and __id cookie without consent there is no traffic on google analytics.
i was wondering if i could somehow to disable completely these cookies.

(Drupal version 8.6 with the current google_analytics)

rcls_’s picture

It's been a while since I actually had to develop a Drupal website, but since I was asked to add a cookie consent notice to a website that used it I decided to look for a pre-made module to help with the job. So I came across this one, but Google Analytics was still getting set after declining and I had to read the module description and issues for help. I tried implementing all of the suggestions above only to hit a TypeError where hasAgreed is undefined.

Looking at the source code my guess is that the defer attribute in loading the eu cookie consent JS file is actually making the code load AFTER analytics has done executing, so hasAgreed is not available when Analytics is called.

To get around this I did what @wowDrpl suggested on #36 and commented out the ga("send", "pageview") portion, and I added the piece of code to html.tpl.php just before the closing body element. However, I did make a minor adjustment and that was to call it only after the page is loaded using jQuery's `ready()` method. Like so:

    <script type="text/javascript">
    $(function() {
      if (!Drupal.eu_cookie_compliance.hasAgreed()){
        window['ga-disable-UA-XXXX-1'] = true;
      }

      ga("send", "pageview");
    });
  </script>

This waits for the script to load and code to execute after that. You could potentially add this to the Google Analytic's module Custom JS portion too, without the ga("send", "pageview"); line and it should work too.

pillona’s picture

To be able to use the hasAgreed() function, I relied on the observer pattern provided by the eu_cookie_compliance library

It can be done this way in order to declare a function which will be called after the cookie value has been loaded and the hasAgreed function works.
(beware, it is actually called twice, so you may want to protect your function against being called twice)

Drupal.eu_cookie_compliance("postStatusLoad", function postLoadHandle(scope,o) {
  if (Drupal.eu_cookie_compliance.hasAgreed()){
   //GOOGLE ANALYTICS CODE
  }
  else {
   // DISABLE GOOGLE ANALYTICS CODE
  }
  });
Shantina’s picture

Hello everyone,

I got this task to make our web site from work GDPR compliant.
So here we are, they gave me the drupal user and I need to find solution.
First time I work with Drupal and I try already with days to fix the issue.
As i dont understand where I have to put the above functionalities for disabling the Google Analytics ,
can some one point me where exactly I need to put the code?
I am trying in the Header Footer Scripts Settings in the configuration of Drupal,
and here where the google analytics is set, under neath I am putting this code:

if (!Drupal.eu_cookie_compliance.hasAgreed()){ window['ga-disable-UA-XXXXXXXX-1'] = true; } ga("send", "pageview");

But still when i try to check the web site, the report is coming back for Google Analytics:
Blocked until accepted by user: No
I would much appreciate any help cause I am already stuck with days and I need to fix this issue asap.
Thank you