How do I track Google visualization chart events in Google analytics? - javascript

I am running Google charts embedded in my site and I need to be able to track user interactions with the charts via select events as documented here: https://developers.google.com/chart/interactive/docs/events?hl=en#the-select-event
Following the analytics.js documentation, I added the following code to the head of my chart Javascript code:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'click');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
(I replaced the dummy ID with the property ID for the site I want to track)
When I ran this code both in a standalone script in a browser and as embedded in my Wordpress site, the relevant Google Analytics events dashboard reported getting no hits.
I don't have much experience with this API so I am sure I am missing something out. Could anyone tell me what this is? I would really a appreciate a working example where Google chart events can get picked up by GA.
All help appreciated.
Nick

First, there is not ga('send', 'click');. Valid interaction types are 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing' (and most of them require additional parameters).
Since you want to track events that are initiated by the user I suggest you place the tracking call in the event callbacks (after you have loaded the analytics script at the top of the page).
If you look at the example linked in the documentaion in your question:
// google.visualization.table exposes a 'page' event.
google.visualization.events.addListener(table, 'page', myPageEventHandler);
...
function myPageEventHandler(e) {
alert('The user is navigating to page ' + e['page']);
}
Then the response to the user interaction is handled in the myPageEventHandler function, the callback for that event. So you could do in that callback whatever change to the visualization is appropriate and then send e.g. an event tracking call:
function myPageEventHandler(e) {
alert('The user is navigating to page ' + e['page']);
ga('send','event','chartevent','click on chart');
}

Related

Get Google Analytics Linker params with multiple trackers on the page

My question is for someone with experience using Google Analytics Linker Plugin programmatically. However my example has a bit complicated setup.
I'm currently working on the website which is using Google Tag Manager for loading GA scripts. It loads several GA scripts on the same page for different purposes.
This website also has a custom dropdown with related domains and I have to use GA Linker Plugin in order to keep them connected. I have to do it manually through the code on every domain element click event. I used the setup suggested by Google Analytics docs:
// inside onclick handler
ga(function(tracker) {
var linkerParam = tracker.get('linkerParam');
// apply to url and navigate window.location.href = url etc.
});
Obviously this doesn't work in my case because of multiple trackers on the page:
// inside onclick handler
ga(function(tracker) {
// tracker is undefined :(
});
I managed to check how many trackers are available and requested linkerParam on each:
// inside onclick handler
ga(function () {
var trackers = ga.getAll();
trackers.forEach(function (tracker) {
console.log(tracker.get('name'), tracker.get('trackingId'), tracker.get('linkerParam'));
});
});
// outputs
// gtm1 UA-XXXYYY-1 _ga=2.234343242.904959305.3434234324-394093204.3094039402
// gtm2 UA-XXXYYY-2 _ga=2.234343242.904959305.3434234324-394093204.3094039402
// gtm3 UA-XXXYYY-3 _ga=2.234343242.904959305.3434234324-394093204.3094039402
As you can see all trackers have the same linker param value, but different names and tracking ids. My question are -
Is it safe to use just first tracker from the list as long as all values are the same (e.g. ga.getAll()[0].get('linkerParam'))?
Or will it be safer to create a specific name for one of the GA trackers in GTM and get it by name in code, e.g:
// inside onclick handler
ga(function () {
var tracker = ga.getByName('websiteTracker');
console.log(tracker.get('name'), tracker.get('trackingId'), tracker.get('linkerParam'));
});
// outputs
// gtm3 UA-XXXYYY-3 _ga=2.234343242.904959305.3434234324-394093204.3094039402
Thanks!
You might be overthinking the problem. Google Analytics through GTM has a simple, built-in way to implement cross-domain tracking. For each GA property that you are loading through GTM, simply set the domains you want to link in the "Cross-Domain Tracking" fields of the Analytics Setting variable or in the over-riding settings in the GA tag.
Bounteous has a very detailed article on how to implement and debug this here.
This has worked in almost all cases in which I want to implement cross-domain tracking through GTM - even if it is for numerous domains.
In the case that you actually need to do this programmatically, I'm pretty sure you can use the same linker param for all the GA properties. You can verify and debug your implementation by doing something like:
Open up the real-time report in the GA property you want to test cross-domain tracking
Visit domain1.com with these UTM values appended: domain1.com?utm_source=test&utm_medium=test
You should be able to filter the real-time traffic by source / medium by clicking on "test" as source or medium under the traffic sources tab.
Navigate to the content tab of the real-time report, you should see the page path and page title for domain1.com
For each domain you want to test that cross-domain tracking works, click the link in your navigation
If everything works, your filtered real-time view should update to the page path and title of domain2.com
If cross-domain linking isn't working, the filtered real-time report will not update. Removing the filter, you should see "domain1.com / referral" or "(direct) / (none)" as the source / medium depending on your referral exclusions.
Hopefully this will help you configure cross-domain tracking or debug efficiently.

Google Analytics single page application hitType pageview not working?

I made the caching of my web app much more aggressive and essentially made it a single page web app.
Even though I thought I implemented Google Analytics correctly according to the documentation, I am getting lots of "not set" pages. So I am guessing something is wrong with my code.
Here's how I believe I send a pageview:
ga('send', {
hitType: 'pageview',
page: pagePath
});
Where pagePathcontains a synthetic page address.
What is wrong about this?
for the single page web application you should have to apply the GA where the change of Route or hash occurs.
And there you should have to include following line of code in without removing the previously written code on the one time loaded page:
window.ga('send', 'pageview', location.hash);
Try this:
ga('send', 'pageview', 'page path');
There is a alternative method using GTM , where you can easily (!!) set-up virtual pageviews, more info on this link
EDIT:
This is an example of one of my sites where i set the fields for a Virtual Pageview in GTM
for SPA Solution,
you could try this one
ga('set', 'page', '/new-page.html');
ga('send', 'pageview');
https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

Track outbound Google Analytics link in new analytics.js

I have new analytics.js on a new webpage. This webpage has to be linked analytically to the existing webpages, managed by other people.
They sent me a line of code to do it:
_gaq.push(['_link', $(this).attr('href')]);
This is the old version of the analytics. I understand, that the same thing in new analytics can be accomplished using:
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
To where on the second I should put '_link' and $(this).attr('href') parameters?
There is not much documentation on the Google website. I have enabled official linker plugin, but they say, that this is not enough.
Edit: Bit of js after loading analytics.js looks like this:
ga('create', 'UA-12312312-1', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['friendlydomain.com'] );
ga('set', {page: window.location.href});
ga('send', 'pageview');
Where UA-12312312-1 is their tracking id. I can see, that ga parameter is added to the links going towards friendlydomain.com
This line of code:
_gaq.push(['_link', $(this).attr('href')]);
is not for outbound link tracking, it's the linker for Cross Domain tracking (see the documentation for the old ga.js library).
To accomplish the same with analytics.js it would be best to use the autolink plugin. This appends the client id to outgoing links; the linked pages must have linking enabled in the configuration to receive the parameter from the url and set it as client id when the tracker is created. GA will then use the client id to merge the sessions on both domains into one.
This will work only if both pages run analytics.js. Also you need to set both domains in the referral exclusion list in the property settings.
analytics.js is fairly flexible, so it mostly depends on how you want to view the data on the GA site.
One possible solution would be...
ga('send', 'event', 'link', 'click', $(this).attr('href'));
Also, the docs are fairly comprehensive. You might consider re-reading them here: https://developers.google.com/analytics/devguides/collection/analyticsjs/events#event_fields

How to remove the base url of your website from Google Analytics trackings?

I've a question related to the simple tracking functionalities of Google Analytics.
I've realized my website with reveal.js, so my site follows a step navigation
http://[mywebsite.nl]/#/cover
http://[mywebsite.nl]/#/welkom
http://[mywebsite.nl]/#/pagina1
http://[mywebsite.nl]/#/pagina2
and I setup google analytics to track statistics.
My tracking issue is that when I land on my http://[mywebsite.nl] and I'm redirected to http://[mywebsite.nl]/#/cover it happens that the same page is tracked twice.
Is there a way to remove the tracking of the / of the website?
Thanks
You can take a look at Google's analytics.js tutorial, it allows some customization:
https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
Page - The page path and query string of the page (e.g. /homepage?id=10). This value must start with a / character.
GA is nice to use as is, it provides some valuable insights.
But it is generally more valuable to track not page views but user actions.
GA is about page views, but as soon as you really want to understand users behaviour you need to track actions. I would recommend to take a look at http://www.devmetrics.io or http://mixpanel.com analytics.
You specify event and its properties. That means that you have full control.
var pageName = document.location.pathname;
// custom pageName processing if you need
devmetrics.userEvent('page_load', [pageName]);
....
// inside button handler:
devmetrics.userEvent('button_click', [pageName]);
I wouldn't recommend stripping the hostname from your pageviews, that can cause other issues with data quality.
Ideally, you would use a 3xx redirect to redirect from your main page to /#/cover, or don't send a hit before your site redirects. If that's not possible, you could try using a filter to drop hits from the URL you don't want to be double-counted.
You might try Google Tag Assistant Recordings to validate that your flow works as expected.
It was easier than I thought, sometimes we tend to over complicate things..
This is the super easy answer I was looking for, it is necessary a small tune on the javascript code
(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');
if(window.location.pathname != '/'){
ga('create', 'UA-XXXXXXXXX', 'auto');
ga('send', 'pageview');
}
It is just necessary to check the window.location.pathname and call the analytics function only for the desired urls.

Google Analytics: How to track pages in a single page application?

Currently in my website, I used HTML5's pushState() and popState in links to increase the speed. However, this doesn't really change the real URL and it looks like it will affect and mess up the Google Analytics's code. (doesn't show a url change) Is there a possible solution for this? Thanks,
If you are using the newer analytics.js API, Google's documentation requires the following code to trigger the event:
ga('send', 'pageview', '/some-page');
If you are using the older ga.js API, David Walsh suggests AJAX websites to use the _gaq.push method:
_gaq.push(['_trackPageview', '/some-page']);
I know it's old question but since this question is first result in Google about tracking pushState() in Google Analytics and all answers are wrong I decided to answer it.
In other answers they mentioned to use directly ga('send' ..... ) but this is wrong way to do it.
First you have to 'set' parameters and then use 'send' to track it.
If you want to update only url, use following code
// set new url
ga('set', 'page', '/new-page');
// send it for tracking
ga('send', 'pageview');
If you want to update url and title, add title parameter to it
// set new url and title
ga('set', {
page: '/new-page',
title: 'New Page'
});
// send it for tracking
ga('send', 'pageview');
Source Single Page Application Tracking - Web Tracking (analytics.js)
February 2018 Update - Global Site Tag (gtag.js)
Google Analytics has a new tracking code snippet, so the other answers might not work for gtag.
This is the default tracking code. It only runs once even though we try to run it each URL changes.
gtag('config', 'GA_TRACKING_ID');
But with a page_path parameter we can make GA run manually.
gtag('config', 'GA_TRACKING_ID', {'page_path': '/new-page.html'});
And we can make something like this.
var origin = window.location.protocol + '//' + window.location.host;
var pathname = window.location.href.substr(origin.length);
gtag('config', 'GA_TRACKING_ID', {'page_path': pathname});
Single page application tracking with gtag.js (Google documentation)
Recent answer (2017)
You can now use Google's autotrack.js, a script that enhances analytics.js.
It includes a plugin that automatically tracks URL changes for single page applications.
You just need to include the script and the following line in your html:
ga('require', 'urlChangeTracker');
2020 Update
If you are using Google Analytics 4 you don't need to push the event anymore IF you enabled the Page views option in the Enhanced measurement feature in Data Streams menu.
At the time of writing, here in September 2013,
Google Analytics has a new JavaScript API.
After you've included Google's new "analytics.js" asynchronous snippet, use the send pageview command to track pages:
ga('send','pageview');
After your pushState madness, use this send pageview command to track your asynchronous navigation. According to Google's Documentation on Page Tracking with Analytics.js, the send pageview command will magically read and track the new location given by pushState, as it will, in the moment the send pageview command is called, use the following values by default (though you can specify them):
var locationToTrack = window.location.protocol+'//'
+window.location.hostname
+window.location.pathname
+window.location.search;
var titleToTrack = document.title;
var pathToTrack = location.pathname+location.search;
Note, Google's standard analytics snippet includes an initial send pageview command.
Update:
I've implemented Google Analytics tracking on my website in the way above that I described -- however, it does not seem to be successfully tracking any of the pushState page views.
I'm going to try specifying the location, title, and page name explicitly on the send pageview command, and see if GA tracks properly.
I'll post back with the results, unless I forget.
Using ga('send', 'pageview') was not registering a pageview on GA.
The way that worked for me is:
window.ga.getAll()[0].set('page', location);
window.ga.getAll()[0].send('pageview');
I can use it after changing the url with history.pushState.
I also had problems with ga('send','pageview');, after using history.pushState.
The workaround was simply make the URL explicit.
ga('send','pageview','/my-url')

Categories