Tracking of external links with Google Analytics - google-analytics

I have a problem with tracking external links. It's not like my solution does not work at all, the problem is, it works only in very few cases. Like 1% of clicks is actually tracked in Analytics. First I had the timeout set to 100ms and thought it might be too short, but even with 500 nothing changed.
Anyone has an idea what might go wrong here?
<script type="text/javascript">
(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-XXXXXXXX-X', 'domain.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
ga('send', 'event', 'category', 'action');
} catch(err){}
setTimeout(function() {
document.location.href = link.href;
}, 500);
}
My links look like this:
a class="post" onclick="recordOutboundLink(this, 'Outbound Links', 'domain.com');" href="http://www.external.com" rel="nofollow">Click here
In Analytics I check in goals for "category = Outbound Links"
Thanks in advance!

There are a few issues with your code, but you should be using Universal Analytics built-in hitCallback function:
HTML:
<a class="post" onclick="recordOutboundLinks('Outbound Link', this.href); return false;" href="http://www.external.com" rel="nofollow">Click here</a>
JS:
<script type="text/javascript">
function recordOutboundLinks(category, link){
try {
ga('send', 'event', category, link, {'hitCallback': function() {
document.location.href = link;
}});
} catch(err){}
}
</script>

Looks like the issue is that you aren't preventing the default event for the link, so it doesn't matter what you set the timeout to.. your function gets executed but then the browser proceeds to execute the default event for the link: that is to follow the target specified in the href. You can update your code to this:
link (noticed use of event instead of this):
<a class="post" onclick="recordOutboundLink(event, 'Outbound Links', 'domain.com');" href="http://www.external.com" rel="nofollow">Click here</a>
function:
<script type="text/javascript">
function recordOutboundLink(event, category, action) {
try {
event.preventDefault(); // prevent default link action
ga('send', 'event', 'category', 'action');
} catch(err){}
setTimeout(function() {
document.location.href = event.target.href;
}, 200);
}
</script>
In my experience, a timeout of 100-200ms should be enough to get GA code to ping but you may have to play with that a little yet, because it's not guaranteed. Alternatively, you can write code to hook into when ga finishes its thing, and it would be easier if you are already using a framework like jQuery.. But overall I agree with Blexy in that you should switch to UA which provides a callback function (and in his example, he prevents the default by appending return false in the onclick).

Related

Analytics pageview/ event code is result in stats

I am trying to get statistics about sign ups on my website.
The analytics code is in the header:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=...."></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '....');
</script>
Then I have a form and sending it (with a page reload, not ajax) and in the success snippet in razor I placed the ga code:
#if (success)
{
<script type="text/javascript">
ga('send', 'event', 'Supplier sign up', 'click', '/signup/success');
</script>
<p>success message</p>
}
The success message appears and I can see the script in the page inspect but I don't get any stats in Google Analytics.
Am I missing something? In the past (a few years ago) I was using a similar code and it worked. Has anything changed recently? Do I need to enable something in the Analytics or my code is wrong?
I am following the documentation:
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
The implementation method for your GA is through gtag.s, not GTM or analytics.js.
Thus you need to modify your success to:
#if (success)
{
<script type="text/javascript">
gtag('event', 'click', {'event_category': 'Supplier sign up', 'event_label': '/signup/success'});
</script>
<p>success message</p>
}
You have mixed two GA libraries. You use gtag.js for page view, so you need to use gtag.js (not analytics.js) for events.
https://developers.google.com/analytics/devguides/collection/gtagjs/events

Google Goal conversion not working when I download pdf

Google Goal conversion not working when I download pdf.
Here I followed following steps:
<html>
<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', 'auto');
ga('send', 'pageview');
</script>
<a href="/wp-content/uploads/2017/03/SEO-ebook-Final.pdf" onClick="javascript:_gaq.push(['_trackPageview','/wp-content/uploads/2017/03/SEO-ebook-Final.pdf']);">Ok<a/ class='bold-uppercase'>
</html>
gaq.push us classic Google analytics code as in ga.js. Your Google Analytics snippet shows you are using analytics.js which is universal analytics.
So basically you are mixing things you shouldn't be.
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com
code ripped from Track outbound links

Polymer - Track app usage with Google Analytics

I'm trying to use Google Analytics (web) with my polymer app (updating the tracker object in routing.html as per this GA SPA doc). I used the Polymer Starter Kit as a starting point. I'm not seeing any pageviews though, apart from / - what's the suggested way of tracking app usage?
routing.html
page('/topstories', function () {
app.route = 'topstories';
window.ga('set', 'page', '/topstories');
});
page('/about', function () {
app.route = 'about';
window.ga('set', 'page', '/about');
});
index.html
<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-xxxxxxxxx-1', 'auto');
ga('send', 'pageview');
</script>
In addition to setting the page value on the tracker, you also have to send the pageview hit to Google Analytics. In your route callback functions you'll need to add the line:
ga('send', 'pageview');
You could also write a function that does all this for you, so you don't have to repeat the set and send calls every time.
function updatePage(path) {
return function() {
app.route = path.slice(1);
ga('set', 'page', path);
ga('send', 'pageview');
}
}
The your page route declarations would look like this:
page('/topstories', updatePage('/topstories'));
page('/about', updatePage('/about'));
My solution takes advantage of the middleware-ish page.js handler:
// Routes
page('*', scrollToTop, closeDrawer, function(ctx, next) {
ga('set', 'page', ctx.path); // simply add
ga('send', 'pageview'); // these rows
next();
});
But this also fires as the / route is initialised, so to not double count visits, remove the final ga('send', 'pageview'); from your <script> block.

Google Universal analytics cross domain tracking

I am trying to track cross-domain calls using Universal Analytics, I've copy-pasted the code right from the google documentation and for some reason it is not decorating the external link with the expected parameter (like _ga=1.182119591.1441315536.1362115890410).
Following there is the exact code we tried:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript" >
var UAAccount = 'UA-0000000-0';
var UATrackerName = 'pageTracker';
(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','http://www.google-analytics.com/analytics.js','ga');
ga('create', UAAccount, 'auto', {'allowLinker': true });
ga( UATrackerName + '.send', 'pageview');
function decorateMe(event) {
event = event || window.event; // Cross browser hoops.
var target = event.target || event.srcElement;
if (target && target.href) { // Ensure this is a link.
ga('linker:decorate', target);
}
}
// Cross browser way to listen for events.
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
$( document ).ready(function() {
var linker;
var myLink = document.getElementById('pippo'); // Add event listeners to link.
addListener(myLink, 'mousedown', decorateMe);
addListener(myLink, 'keydown', decorateMe);
});
</script>
</head>
<body>
anchor
</body>
</html>
I've tried to use the dynamic linker instead of decorating each link:
ga('require', 'linker');
ga('linker:autoLink', ['goo.gl']);
but without success: the external link will be without the _ga parameter.
For some reason you are giving the tracker a name of 'pageTracker', but you are not using that name when calling the object methods, including create and linker methods:
ga('create', 'UA-XXX-Y', {name: 'pageTracker'});
ga('pageTracker.linker' ...);
ga('pageTracker.require' ...);

Google Analytics Goals not getting tracked

I realize that there's a plenty of questions about not working GA goal tracking. I did my homework and read lots of them before posting my question.
Here's my issue... This is the documentation that I used to create my code: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
I am using the analytics.js version
<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-xxxxxxxxxxx-x', 'mywebsite.com');
ga('send', 'pageview');
</script>
I tried to implement the code via both pure javascript and jQuery but neither seems to work.
Here's my code:
link to be tracked:
Get In Touch Today
jQuery approach:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#cta-footer-btn').on('click', function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
});
</script>
I also tried the pure js approach suggested:
<script>
var downloadLink = document.getElementById('cta-footer-btn');
addListener(downloadLink, 'click', function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
/**
* Utility to wrap the different behaviors between W3C-compliant browsers
* and IE when adding event handlers.
*
* #param {Object} element Object on which to attach the event listener.
* #param {string} type A string representing the event type to listen for
* (e.g. load, click, etc.).
* #param {function()} callback The function that receives the notification.
*/
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>
Neither seems to be tracking the link clicks.
Any thoughts or suggestions why this is not working will be greatly appreciated.
Thanks!
Make sure you have the analytics tracking code inserted in the head section of the document (not necessary, but makes sure that the required library is fully loaded along with the ga object before making any references to ga() functions), and also make sure jQuery is also loaded before being used. You can use the console (usually F12 in browsers) to check for any error being thrown. These are are general steps to verify if you have tracking installed properly.
It might take a while before data starts showing up in reports if you have just installed, so don't worry. You can install the GADebug extension for Chrome to check if tracking beacons are sent properly.
Also, you can use the click() function from jQuery. It works fine for me.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#cta-footer-btn').click( function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
});
</script>
Hope that helps! :)

Resources