How does google analytics track events when user navigates to other page inside one domain - google-analytics

In Google's documentation it is said that an event can be tracked in the following way:
<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a>
or older version:
<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>
I was looking with Firebug to the request that are made when a click on a link and I see there aborted request:
http://www.google-analytics.com/__utm.gif?utmwv=4.7.2&utmn=907737223&....
This happens because browser unload all javascript when user navigates to a new page. How in this case event tracking is performed?
Edit:
Since one picture can be worth a thousand words...
When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)

The problem is that there isn't enough time for the script to finish running before the user is taken to the next page. What you can do is create a wrapper function for your GA code and in the onclick, call the wrapper function and after the GA code is triggered in your wrapper function, set a time out and update location.href with the link's url. Example:
click me
<script type='text/javascript'>
function wrapper_function(that,category,action,opt_label,opt_value) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
window.setTimeout("window.location.href='" + that.href + "'", 1000);
}
</script>
code will vary a bit based on your link but hopefully you get the idea - basically it waits a little bit before taking the user to the target url to give the script some time to execute.
Update:
This answer was posted several years ago and quite a lot has happened since then, yet I continue to get feedback (and upvotes) occasionally, so I thought I'd update this answer with new info. This answer is still doable but if you are using Universal Analytics then there is a hitCallback function available. The hitCallback function is also available to their traditional _gaq (ga.js) but it's not officially documented.

This problem is answered in Google's documentation:
use
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
or
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var pageTracker=_gat._getTracker("UA-XXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
This more or less the same as the answer from Crayon Violet, but has a nicer method name and is the official solution recommended by Google.

As above, this is due to the page being unloaded prior to the Async call returning. If you want to implement a small delay to allow gaq to sync, I would suggest the following:
First add a link and add an extra class or data attribute:
My Link
Then add into your Javascript:
$("a[data-track-exit]").on('click', function(e) {
e.preventDefault();
var thatEl = $(this);
thatEl.unbind(e.type, arguments.callee);
_gaq.push( [ "_trackEvent", action, e.type, 'label', 1 ] );
setTimeout(function() {
thatEl.trigger(event);
}, 200);
});
I don't really condone this behavior (e.g. if you are going to another page on your site, try to capture the data on that page), but it is a decent stop-gap. This can be extrapolated not just for click events, but also form submits and anything else that would also cause a page unload. Hope this helps!

I had the same issue. Try this one, it works for me. Looks like that ga doesnt like numbers as a label value. So, convert it to string.
trackEvent: function(category, action, opt_label, opt_value){
if(typeof opt_label === 'undefined') opt_label = '';
if(typeof opt_value === 'undefined') opt_value = 1;
_gaq.push([
'_trackEvent',
String(category),
String(action),
String(opt_label),
opt_value
]);
}

Related

Social shares tracking in GA

This is pretty much covered topic for original FB/Twitter buttons. But what if I have my own "share on fb" button? Like this:
<div id="fb_share"><a target="_blank" href="http://www.facebook.com/share.php?u=blah-blah">Share on FB</a></div>
so I've come up with the folloing solution:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location
});
//console.log('tracked');
});
That is placed AFTER the Google Analytics code.
Despite the fact it wont catch FB callback - it is supposed to do the trick but for some reason I still cannot see any results in Analytics so the question is this: will the solution actually work? In fact it could be even like this I believe:
FB
Your 'share on Facebook' links causes the page to navigate (and not open a new window/tab). When this navigation happens, most mainstream browsers cancel all pending HTTP requests for the current page and then navigates to the new page (fb.com)
In this scenario, one of the pending HTTP requests will be the GA event tracking call which will therefore never complete and never be received by the GA servers.
What you need to use is the GA hit callback functionality, this essentially cancels the native navigation (to FB), sends the tracking call and waits enough time for it to complete and then does a JavaScript redirection to the next page.
You should read the google docs here
In your case your event tracking function should be similar to this:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location,
'hitCallback': function(){
window.location = this.href;
}
});
//console.log('tracked');
return false;
});
So I've made the following changes:
Added the hitCallback property to the event tracking call. this is an anonymous function that is called once the GA servers have sent their response to the event tracking.
added a 'return false' statement which cancels the native functionality and then relies on the hitCallback function to do the navigating.

Google Analytics file tracking

I'm using Google Analytics to track my pages, and I've added, last week, this code which I've found to try to track my PDF downloads, but this doesn't work :
Link to PDF :
<a href="pdf/my-pdf.pdf"
onClick="javascript:pageTracker._trackEvent('PDF','Download','My New PDF');
void(0);">
PDF
</a>
GA Tracking Code (minified) :
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
Of course, I changed my UA Values for the same of this post.
How can I edit this to allow for file download tracking ?
Edit
PDF
function trackLink(e)
{
e.preventDefault();
_gaq.push(['_trackEvent','Download','PDF', e.target.href]);
window.setTimeout('location.href="'+e.target.href+'"',100);
return false;
}
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
Note: XX's have been added for the purpose of the post and are not in the actual code.
Okay so a couple things here. Firstly, as gerl pointed out, you are using the wrong GA syntax for the version of the core code you have. So you need to fix your code according to that answer, regardless. But there is another issue to consider: timing.
First, more often than not, the GA code isn't going to have enough time to execute, before the browser redirects to the target URL. There are 2 ways you can get around this: force a timeout of ~100ms before redirect, or make your pdf open up in a separate tab/window.
Personally, I think the latter is a better solution. Since the pdf is loaded into a separate window, you don't need to worry about delaying the redirect to give GA a chance to execute. Also, most people prefer things like pdfs to open up in a separate tab/window, so that they aren't taken away from the page they are on. To do this, add a `target='_blank' to the link:
PDF
But if you really want to stick with having the pdf open in the same window/tab, then you will need to force a timeout. I don't like this option as much as the first, because what ~100ms is usually enough time to wait, it's not a guarantee that it's enough time. You can increase the timeout, but the more you do, the longer the visitor has to wait before the redirect occurs, which makes for a bad user experience. But this is one way you could do it:
PDF
<script type="text/javascript">
function trackLink(e) {
e.preventDefault();
_gaq.push(['_trackEvent','Download','PDF', e.target.href]);
window.setTimeout('location.href="'+e.target.href+'"',100);
return false;
}
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
Also note that if you upgrade to universal analytics, that version has timeout/callback funcationality built in to link tracking (that article talks about outbound link tracking but the principle of using the callback function to do the redirect is the same).
You have pageTracker instead of _gaq.. Try this instead:
onclick="_gaq.push(['_trackEvent','Download','PDF', 'pdf/my-pdf.pdf']);"
Instead of writing a function, you can just add something into the html of the element... perhaps something like this?
<a href="pdf/my-pdf.pdf" onClick="_gaq.push(['_trackEvent', 'PDF','Download','My New PDF']);">
That ought to do it.
I had a similar problem with this sort of thing when trying to decide which type of GA code to use.
This question I posted might help (using ga vs. _gaq.push):
ga or _gaq.push for Google Analytics event tracking?
pdf
That should do the job! More info here: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
Also, you can always test if your event tracking is working by looking in Real Time Analytics.
See this link: https://support.google.com/analytics/answer/1136920?hl=en
It shows how to use the hitCallback to help with the issue of the browser redirecting before the event gets pushed.
I think this would be how to modify your code:
PDF
<script type="text/javascript">
function trackLink(e) {
e.preventDefault();
ga('send', 'event', 'Download', 'click', 'PDF', {'hitCallback':
function () {
document.location = e.target.href;
}
});
return false;
}
(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', 'auto');
ga('send', 'pageview');
</script>

Tracking external links with Google Analytics trackPageview() not working

I have set up external link tracking as Goals in Google Analytics according to the GA documentation.
Here is the page in question: http://playmoreatthey.org/ - the external links on the page are formatted such as
Bayside Family YMCA
I set up the goal as a "head match" to the URL: /G1/bayside_family.com
I checked back four days later, and there are no results in the goals or pageviews for the phony "pagename" (/G1/bayside_family.com) specified in the JavaScript attached to each external link.
Looks like on your page you are using GA's async style code _gaq.push(...) but in your onclick you are using their old, "traditional" style code. You need to use
onclick="_gaq.push(['_trackPageview','/G1/bayside_family.com']);"
If you are using jQuery you can automatically track all the links on your site using this script:
// Outbound Link Tracking with Google Analytics
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$("a").on('click', function(e){
var url = $(this).attr("href");
if($.trim(url).indexOf("javascript:") == 0) return;
if (e.currentTarget.host != window.location.host) {
_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
var target = $(this).attr("target");
if (e.metaKey || e.ctrlKey || target == "_blank") {
var newtab = true;
}
if (!newtab) {
e.preventDefault();
if(target) {
setTimeout('window.open("' + url + '", "' + target + '");', 100);
} else {
setTimeout('document.location = "' + url + '"', 100);
}
}
}
});
I found the script here: http://wptheming.com/2012/01/tracking-outbound-links-with-google-analytics/comment-page-1/#comment-39716
At the site you can find a debug version that will let you confirm that the script is working correctly.
I deviated from the original script by adding support for links with javascript (aka href="javascript:..."). Also I added code to honor the target attribute.
Here is a jsFiddle so you can see the script in action: http://jsfiddle.net/luisperezphd/45NPe/
One recommended way of doing this is through Events. That way your pageviews metric will not be inflated by the virtual pageviews tracked using the _trackPageview method.
http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920
I add this as an answer because Crayon Violent's comment above contains a broken link. At least someone will be able to edit this answer if the link needs to change again in the future.

Use Google Analytics (Asynchronous version) to track outgoing clicks without breaking target=_blank

I want to track users clicking links to external sites. I'm happy to use the asynchronous version of GA as this allows (in most browsers) the page to continue loading instead of halting at the script tag and waiting for google-analytics.com/ga.js to download and execute.
Google recommends this function:
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
<a href="http://www.example.com" onClick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">
The problems with this solution:
It could take 10ms, it could take 300ms for the event to be tracked, but it'll change the page after 100ms no matter what happens. And if the tracking is too slow the page will change before it's been tracked.
document.location = means the original link is ignored and therefore target=_blank does not open new tabs/windows.
Possible solutions:
Busy wait (do {curDate=new Date();} while(curDate-date<millis)) for 100ms while the tracking has a chance to send it's request off then return true. Bad because busy waiting consumes all CPU available.
Use window.open so that new tabs/windows can be opened, which leads me to my current favourite:
In the click handler use $(this).attr("target", "_blank"); and then just return true after pushing the tracking command onto _gaq.
This works because open a new tab leaves the current one to finish executing the tracking call.
$(document).ready(function(){
var localserver = document.location.hostname;
// unfortunately misses if any uppercase used in link scheme
$("a[href^=http://],a[href^=https://]")
.not("a[href^=http://"+localserver+"]")
.not("a[href^=http://www."+localserver+"]")
.click(function(e){
$(this).attr("target", "_blank");
_gaq.push(['_trackEvent',
'Outgoing Click',
$(this).attr("href"),
$(this).text()
]);
return true;
});
});
With the one small downside of always opening a new tab for external links, I can't see any other problems.

jQuery $.get refreshing page instead of providing data

I have written some code using jQuery to use Ajax to get data from another WebForm, and it works fine. I'm copying the code to another project, but it won't work properly. When a class member is clicked, it will give me the ProductID that I have concatenated onto the input ID, but it never alerts the data from the $.get. The test page (/Products/Ajax/Default.aspx) that I have set up simply returns the text "TESTING...". I installed Web Development Helper in IE, and it shows that the request is getting to the test page and that the status is 200 with my correct return text. However, jQuery refreshes my calling page before it will ever show me the data that I'm asking for. Below are the code snippets from my page. Please let me know if there are other code blocks that you need to see. Thank you!
<script type="text/javascript">
$(document).ready(function() {
$(".addtocart_a").click(function() {
var sProdIDFileID = $(this).attr("id");
var aProdIDFileID = sProdIDFileID.split("_");
var sProdID = aProdIDFileID[5];
// *** This alert shows fine -- ProdID: 7
alert("ProdID: " + sProdID);
$.get("/Products/Ajax/Default.aspx", { test: "yes" }, function(data) {
// *** This alert never gets displayed
alert("Data Loaded: " + data);
}, "text");
});
});
</script>
<input src="/images/add_to_cart.png" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$aAddToCart_7" type="image" id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_aAddToCart_7" class="addtocart_a" />
The easiest way is to tell jQuery not to return anything.
$(".addtocart_a").click(function(e){
// REST OF FUNCTION
return false;
});
Good luck! If you need anything else let me know.

Resources