63

I have a website that I am using the new Universal Analytics (analytics.js) to track. Everything is setup and working (pageviews, referrals, etc.) using the following code snippet:

<script>
  (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-39570713-1', 'site.com');
  ga('send', 'pageview');

</script>

That is located before the </head> tag.

I am using JQuery to fire off an event. I tested the JQuery with an alert message and it is getting called, so that isn't the problem. Here is the snippet that fires when a button is clicked:

$('#submitButton').on('click', function() {
      ga('send', 'event', 'button', 'click', 'contact form');
    });

Nothing is appearing in the Events section of Analytics. I keep clicking the button, even from different computers just to make sure it isn't excluding my IP address. Because the Analytics doc that Google provides does not provide a whole lot of explanation I'm at a loss here.

Charles
  • 50,943
  • 13
  • 104
  • 142
squeezemylime
  • 2,102
  • 3
  • 18
  • 26
  • I too am facing the same problem. I can see the events in realtime view. But not under Events in Content section. Any ideas? – dicemaster Jun 18 '13 at 13:55
  • I'm having the same problem too. I was wondering if it is because the click event we are tracking will produce a new page load (a form submission in your case or a click on a link in my case). As we are "leaving" the page and because Google Analytics tracking is asynchronous, I can imagine that the tracking event must be sent first (this takes some time) and then the original "click" action (submission or loading a new page) must be done. Google Analytics provides a callback to do that : http://stackoverflow.com/questions/18428690/analytics-js-event-not-working-properly – Patrick Janser Feb 10 '15 at 14:42

20 Answers20

197

If you are using Google Tag Manager and also want to trigger some events via code, ga('send'...) does not appear to be enough. You need to first fetch the appropriate analytics object:

if ("ga" in window) {
    tracker = ga.getAll()[0];
    if (tracker)
        tracker.send("event", "Test", "Test GA");
}

Note that this assumes you're only using a single Google Analytics Tracking code on your site. If you happen to be using multiple, you may need to fetch the appropriate one by name or index.

Simon East
  • 55,742
  • 17
  • 139
  • 133
Sanjay Vamja
  • 2,235
  • 1
  • 16
  • 16
  • 4
    snippet for those who want to send pageview event using Google Tag Manager const tracker = window.ga.getAll()[0]; if (tracker && tracker.set && tracker.send) { tracker.set('page', props.location.pathname) tracker.send('pageview') } – Denis Nov 13 '17 at 21:00
  • 30
    This worked for me. Why isn't this documented in the [Google Analytics Event Tracking page](https://developers.google.com/analytics/devguides/collection/analyticsjs/events)? – user2233706 Mar 06 '18 at 04:59
  • 4
    Relevant [documentation on the `tracker.send` method](https://developers.google.com/analytics/devguides/collection/analyticsjs/tracker-object-reference#send) – ᴍᴇʜᴏᴠ Mar 13 '18 at 14:38
  • 1
    This fixed the problem for me, too. – Joseph at SwiftOtter Jul 04 '18 at 15:50
  • 4
    Or, just add the tracker name like so: ga('gtm1.send', 'event', 'Test', 'Test GA'); – Bob H Dec 20 '18 at 14:44
  • I have to send the pageview ga('gtm1.send','pageview','path_to_load'); but it is not working – Orchid Apr 17 '19 at 05:07
  • Google [documents](https://support.google.com/tagmanager/answer/6106716) a different way of tracking events when using the Tag manager. (Scroll down to _Clicks on any element_). Though I must say doing that per code can be easier, once you know that `ga.getAll()` approach. – Anse Oct 28 '19 at 09:41
  • 1
    The first attribute is the `hitType` and the second can be a dictionary https://developers.google.com/analytics/devguides/collection/analyticsjs/tracker-object-reference#send So your code can look like: `tracker.send("event", { eventCategory: 'button', eventAction: 'click', eventLabel: 'button1'});` – Rudolf Real Jun 16 '20 at 04:46
  • Thanks to both repliers. I spent days trying to find a solution like this... – Pablo Oct 23 '20 at 14:04
  • Thank you. This was driving me crazy for hours. – cdmckay Feb 09 '21 at 12:10
36

New version of analytics has a new syntax. Replace the line below;

ga('send', 'event', 'button', 'click', 'contact form');

with this;

gtag('event', 'click', {'event_category' : 'button',
  'event_label' : 'contact form'});

Reference; https://developers.google.com/analytics/devguides/collection/gtagjs/events

afelaho
  • 461
  • 4
  • 3
10

For testing purposes you could also use the hitCallback method:

ga('send', {
  'hitType': 'event',         
  'eventCategory': 'button', 
  'eventAction': 'click',     
  'eventLabel': 'contact form',
  'hitCallback' : function () {
      alert("Event received");
   }
});

Update: comma was missing.

Community
  • 1
  • 1
Dom
  • 218
  • 1
  • 6
8

For GA for this moment... Sending a new page in SPA looks finally like this for me:

if (window.ga){
    window.ga.getAll()[0].set('page', location);
    window.ga.getAll()[0].send('pageview')
}

This shows exactly what wanted on GA reports like a new page is hit and the title and all are correct.

Albedo
  • 81
  • 1
  • 2
5

In my case the problem was uBlock Origin that was blocking the analytics script from loading.

Simon East
  • 55,742
  • 17
  • 139
  • 133
user1139733
  • 986
  • 9
  • 14
4

I had the exact same problem. I had to create a new property and select "Universal Analytics" instead of "Classic Analytics" (it is labeled as "beta"). Now events are captured properly.

extrabacon
  • 1,220
  • 1
  • 12
  • 14
  • Why is this not documented :( – Doydle Apr 20 '16 at 17:01
  • Hi and thanks @extrabacon! What I've done is this: (1) create a new Analytics property, (2) copy/paste the new tracking code in the site and (3) see events tracking work with no reason... This seems to be one of these case in which you should accept that you solved a problem without knowing how! Haha! – vcoppolecchia Oct 24 '16 at 16:01
3

I had this same problem, and I think I've found the solution, but it really leaves a bad taste in my mouth about Universal Analytics.

What I had to do was explicitly use the synchronous analytics API. So instead of including the usual snippet in your <head> tag, use the following code:

<script src="//www.google-analytics.com/analytics.js"></script>
<script>
  tracker = ga.create('UA-XXXXXXX-1', 'example.com');
  tracker.send('pageview');
</script>

Then you call the event tracking code like this:

tracker.send('event', 'Category', 'Action', 'Label');

This will ensure that the tracking beacon is sent to Google and acknowledged before the page the user navigated to starts loading.

This suggests that Universal Analytics requires some kind of additional acknowledgment beyond what the old ga.js analytics code required. So when you attach an event to a click that brings the user to another page, that acknowledgement can't be sent because the browser has left the page and dropped the current javascript execution stack.

Maybe this problem is specific to certain execution environments (I'm using Chrome 34 on OSX Mountain Lion), which might explain why more developers aren't noticing this problem.

coredumperror
  • 8,471
  • 6
  • 33
  • 42
2

today I needed to setup analythics for the first time and I found myself in the same trouble.

I found that the bast way to deal with the multiple trackers to avoid the getAll(), is this:

<script>
(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','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-xxxxxx-y', 'auto', 'tracker');
ga('tracker.send', 'pageview');
ga('tracker.send', 'event', 'test', 'click', 'automaticEvent')

Note that you have to pass a "name" to the create method, and then you send an event to that tracker with ga([trackerName].send, ...)

Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers

coffidev
  • 959
  • 8
  • 6
2

If anyone is trying to send an event to Google Analytics and wondering why the send function is doing nothing without any clear hint, I recommend using the debug version of their library. It will log some useful hints in the browser console.

Instead of getting the script from https://www.google-analytics.com/analytics.js, get it from https://www.google-analytics.com/analytics_debug.js. I found this out from their documentation.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
1

I cannot see anything wrong with the code itself. Have you tried using the alternative event tracking?

ga('send', {
  'hitType': 'event',          // Required.
  'eventCategory': 'button',   // Required.
  'eventAction': 'click',      // Required.
  'eventLabel': 'contact form'
});

I would also suggest testing the website with GA Debug Chrome addon, which allows you to see the tracking beacon was sent or not.

"Official" debugging documentation for Universal Analytics is still missing as of now, but hopefully it will be added soon as ga_debug.js provides lot of useful ways how to find out what's wrong with Analytics implementation...

Petr Havlik
  • 3,307
  • 1
  • 19
  • 17
  • Actually to fix it I just reverted to the Classic Analytics...I tried this code and it didn't work. Not sure what is wrong with either the new beta Analytics (or my implementation) but reverting fixed it. – squeezemylime Apr 04 '13 at 02:03
0

I have the same problem, and it looks like events are tracked, but GA dashboard doesn't allow to browse them. This is the only way how I could interprete the "Visits with events: 1071" but "Total events: 0" that GA dashboard shows me.

UPD: With GA Chrome debug, have found a problem; 1st method is not working (sends the event without any data attached), but the 2nd one is OK.

Yuriy Silvestrov
  • 422
  • 4
  • 10
0

You should also consider that it is likely that the page gets reloaded after the submit event was fired before the ga script was able to execute the 'send' method. To avoid this you could employ the 'hitCallback' mechanism, i.e. prevent the submit, call the ga send-method and submit the form data in the callback.

Nicolas Zimmer
  • 424
  • 4
  • 10
0

I got it working - my example is using the new Universal Analytics.

<script type="text/javascript">
    function sliderOnChange() {
    var period = window.convertDays(($("#PeriodSlider").slider("value")));
    var amount_of_credit = $("#AmountOfCreditSlider").slider("value");
    var gaEventInput = "£" + amount_of_credit + " for " + period;
    ga('send', 'event', 'slider', 'sliding', gaEventInput);
}
</script>
  1. Make sure Google Analytics / Google Tag Manager filters are not excluding any traffic from different domain. (Maybe you are testing it to get this working using different domain)
  2. Recheck your GA id and domain in ga('create', 'UA-39570713-1', 'site.com');
  3. Create a new profile in Google Analytics (GA) for testing purposes and debug your html in the same domain you define in GA.
  4. Change the date to be today in GA - you might also need to wait some time before it appears in GA
0

I recommend sending GTM event via window.dataLayer.push({ event: 'EVENT_NAME', ...data }) and in GTM creating a trigger to fire a tag which sends event to Google Analytics. You'll have the best debugging experience with GTM preview and you'll be sure that events will be sent from GTM to GA, because GTM takes care of that.

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
0

onclick ga() function not working for me, I have also added the 'analytics.js' in <head> section -

<a mat-list-item routerLink='/dashboard' onclick="ga('send', 'event', 'Dashboard', 'Click', 'demoClick, 30);">
   <mat-icon color="accent">home</mat-icon>
   <span class="side-item">Dashboard</span>
</a>

gtag() function working fine for me, only the 'gtag.js' added in <head> section, 'analytics.js' not required or can be removed -

<a mat-list-item routerLink='/dashboard' id="sideNavDashboard" onclick="gtag('event', 'Click', {'event_category':'Dashboard', 'event_label':'demoClick', 'value':'30'});">
   <mat-icon color="accent">home</mat-icon>
   <span class="side-item">Dashboard</span>
</a>

Result (Google Analytics output) -

enter image description here

Pinaki
  • 792
  • 8
  • 17
0

I was seeing everything except Events (both real-time and report). My steps included:

  • Calling Google and they found out that my GTM tag for Google Optimize was stopping all events to be sent to Analytics.
  • Removed the Optimize tag from Google tag manager and events started popping up in Analytics.

Try pausing some tag if you have this issue. Also connect the event tag to some goal.

allenski
  • 1,652
  • 4
  • 23
  • 39
0

I am using Vue.js and it seems I have to create ga each time, even though it was already created on the window:

ga('create', yourGtagId, 'auto');
ga('send', {});
Stuart Cusack
  • 129
  • 1
  • 5
-1

In my case it didn't work because I loaded the HTML file directly from the file system.

Loading the page via a web server did the trick.

For local development a tool like https://github.com/tj/serve does a great job.

Francesc Rosas
  • 5,915
  • 2
  • 30
  • 16
-2

The only way I solved the problem was rolling back to the previous version of Analytics (non-beta):

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-39570713-2']);
  _gaq.push(['_setDomainName', 'optimino.com']);
  _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>
squeezemylime
  • 2,102
  • 3
  • 18
  • 26
  • 1
    this implies that your account was not setup to use analytics.js, which will only work with Universal Analytics. You need to create a new GA account and select Universal Analytics, not Classic. – Brian Jul 19 '13 at 02:33
  • 1
    FYI - I noticed that Adblock Plus was blocking the new analytics.js file from Google. – William Isted Jan 03 '14 at 17:54
-4

You can also use a jquery plugin I wrote for the new Universal Analytics: https://github.com/pascalvgemert/jquery-analytics-event-tracking

pascalvgemert
  • 1,247
  • 1
  • 13
  • 28