Google Analytics Goals not getting tracked - google-analytics

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! :)

Related

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

Google Analytics for Single Page Application with # views

I'm trying to implement Google Analytics on Single Page Application. I'm trying to use Autotrack to track the virtual page views. But, it's not working.
Code:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXX-1', 'auto');
ga('require', 'urlChangeTracker', {
shouldTrackUrlChange: function(newPath, oldPath) {
newPath = newPath.split('?')[0];
oldPath = oldPath.split('?')[0];
return newPath != oldPath;
}
});
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/autotrack/0.6.4/autotrack.js"></script>
Quoting from related github issue:
"The urlChangeTracker plugin does not support tracking URL hash changes. This is mentioned in the overview section of the plugin documentation.
Since almost all browsers in use today support the History API, that's what you should be using when creating SPAs. Hash changes should only be used for in-page navigation to anchor links."

Load Google Analytics from tampermonkey

I'm trying to place Google Analytics code inside a Tampermonkey userscript, however the code simply doesn't work as evidenced by:
The callback function for the pageview doesn't fire and
I don't show up as an "active user on site" in Real-Time view for Google Analytics
Here is the script, nice and simple (some values obfuscated):
// ==UserScript==
// #name GA Injector
// #namespace mynamespace
// #version 0.1
// #description Injects google analytic code for testing
// #match mywebpage
// #copyright 2014 me
// #require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
Console.log('This part works okay');
(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', 'mytrackingcodeishere', 'auto');
ga('send', 'pageview', {
'hitCallback': function() {
console.log('Tracking worked okay!');
}
});
The script works fine when run in Chrome's javascript console, what is it about Tampermonkey or my configuration that prevents Google Analytics from being run?
Try simply injecting this entire code into the page scope, like this:
var script = document.createElement('script');
script.innerHTML = "..Your JS Code..";
document.body.appendChild(script);
If it does works when run from console, it will this way.

Tracking of external links with 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).

What is return _gaLink(this,'#);

When tracking links, do i need to put this code at the end?
return _gaLink(this,'#');
What exactly doe it do? My understanding of this is not clear.
Are you looking to tracking outgoing/external links? There is no Google Analytics function called _gaLink. Can you post up a snippet of your code?
_link() is used for X-Domain tracking, please see the documentation
If you simply wish to track "outbound links", i.e. links to other sites, then use this piece of code (not this requires jQuery):
///////////////////
// _trackOutbound
jQuery(document).ready(function($) {
$('a[href^="http"]:not([href*="//' + location.host + '"])').live('click', function(e) {
_gaq.push(['_trackEvent', 'outbound', 'click', this.href.match(/\/\/([^\/]+)/)[1]]);
_gaq.push(['t2._trackEvent', 'outbound', 'click', this.href.match(/\/\/([^\/]+)/)[1]]);
});
});

Resources