Virtual pageview in place of real pageview in Google Analytics - javascript

I'd like to have better error page reporting in Google Analytics. Currently, if someone does something on my site which causes a problem, they see an error page instead of the content they expected. The URL remains the same. So if they went to www.example.com/view_my_profile and there was a problem with their profile, they would see an error page at that URL.
What I'd like to do is send Google Analytics a virtual pageview of something like www.example.com/error/view_my_profile/ (maybe an event captures the extra parameters better?). That's easy enough. But I want this virtal pageview to happen instead of the /view_my_profile real pageview. Because that real page wasn't actually viewed and it would be registering an extra pageview on my site.
Is this as simple as leaving out the _trackPageView call in the google analytics snippet below or am I asking for trouble?
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-${gaAccount}-1']);
_gaq.push(['_trackPageview']);

Way over-complicating things..just use _trackPageView like normal but pass a value (virtual URL) to it for the URL you want it to be. It will count as a page view for the URL you pass it instead of the current URL.

You can do this without complication. As long as you load ga.js, instantiate var gaq, and set the account, you can make any calls you want, including _trackPageview with only a virtual pageview value.
You don't even need to call the organic _trackPageview -- you could just do event tracking. In fact, you might want to consider doing an organic pageview, coupled with an Event Tracking that passes some detailed error tracking info to you. Because there can be up to 4 parameters, you can log more and better structured data.
So, on your 404 page, you could call something like:
_gaq.push(['_trackEvent', '404 Error', location.pathname, document.referrer, time_stamp_value]);
(where you've previously defined time_stamp_value as a non-float Number.)
Something that simple will allow you to create hierarchies for your errors, count them more easily, and even do things like the referring page and a timestamp value, without cluttering your pageview information.

Related

Sending Google Analytics event then immediately navigating away

Can I send a Google Analytics event and immediately navigate away, like so?
_gaq.push(['_trackEvent', 'foobar']);
window.location = "/";
If Google Analytics does some kind of AJAX request when this is called then it should work whether we stay on the page or not. My concern is that it seems it may sometimes just be putting stuff in an array for later processing. I'm thinking this only happens initially, when Google Analytics hasn't had time to be initialized yet, but I'd like to be certain of this.
I did a test with GA debug, and it seemed to have worked, but I'm not sure if that means it always will depending on loading speed and what not.
Can I do this and never lose any events?
The way I've done it is like so:
_gaq.push(['_trackEvent', '...', '...', '...']);
_gaq.push(function(){
// do stuff here
});
$('#logo').on('click', function(){
var curPage = window.location.href;
_gaq.push(['_trackEvent', curPage, '#logo']);
_gaq.push(function(){
window.location.href = '/';
});
});
The second push call will always run after the first one, because Google queues all push calls, so that the first one will run and complete, then the second one will run and complete. Google lets you put functions in the push method so you can queue them.
Source: https://developers.google.com/analytics/devguides/collection/gajs/#PushingFunctions
I add a slight delay (via setTimeout) if the new page isn't being opened in a new window.
I haven't had a chance to try this yet, but Google's new Universal Analytics has a hitCallback function that is executed after the data has been sent.
#mike mentions hitCallback method which is described in analytics.js documentation:
In some cases, like when you track outbound links, you might want to know when the tracker is done sending data. That way you can send a user to their destination only after their click has been reported to Google Analytics. To solve this, the send command allows you to specify a hitCallback function in the field name object that will execute as soon as analytics.js has completed sending data.
Which is fantastic, except the snippet is still in public beta. If for some reason (ahem technophobic policies ahem) you're limited to ga.js functionality, you can use this workaround:
_gaq.push(['_set', 'hitCallback', function(){
document.location='someOtherPage.html';
}]);
_gaq.push(['_trackEvent', 'category', 'event', 'value']);
Another sensible suggestion is to have a fallback to have the callback executed immediately if _gaq is not defined.
It looks like your concern about losing the event is legitimate, see this question. One answer there seems a little fragile with regards to Google changing their code, but would let you confirm the event tracking before navigating to the link. That would probably be "near-immediate".

Tracking Varnish hits and misses in Google Analytics?

I'm looking to collect data on page load speeds via Google Analytics, and would like to split this between pages that have been returned having HIT the Varnish cache, and those that have MISSED the cache.
Before looking into this I just assumed I'd get JS to have a look at the varnish headers in the page response, and create a GA custom var to track this on a per-page basis. Of course, JS doesn't have access to the page headers, so I'm at a bit of a loss currently. I've made server-side GA tracking work ing the past (via php-ga) but this needs to tie in to real-world page load time.
Just a thought, but you could set a cookie in the "vcl_deliver" subroutine. Something like this:
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.Set-Cookie = "VarnishHit=Yes;Path=/;";
}
return (deliver); }
This basically says: if the obj has more than one hit, set a cookie saying so. You will need to make sure you do not over write any other cookies, so maybe just concatenate this to you existing Set-Cookie, if you are using cookies. For more info on the obj.hits look here:
https://www.varnish-cache.org/docs/3.0/reference/vcl.html
Here is the line that matters:
obj.hits
The approximate number of times the object has been delivered. A value of 0 indicates a cache miss. This variable is also available in vcl_deliver.
That will give you access to this information from within Javascript using the document.cookie variable. I believe that jQuery has some plugins to make this easier, here is one I found: https://github.com/carhartl/jquery-cookie on Google. Once you can check for the existence of the cookie in JS you should be able to use the GA API to log a event. I hope that helps.

Google Analytics: Is _gaq.push() a blocking function?

What I am trying to do is to redirect the user to the next page right after sending an event to Google Analytics:
_gaq.push(['_trackEvent', 'xxx' ...]);
window.location = 'some url ...';
The above code manages to register events because I can see them in the GA report. However I suspect that some events were lost because the browser redirects the user to the new page before the track pixel loads.
My questions are:
Does _gaq.push() block until the event has successfully reached Google's server?
If not, what is the best way to make achieve what I need?
Thanks!
Google has a support page that says you might want to add a delay after calling _gac.push, however they claim that this is to give the Google Analytics JavaScript a chance to load. They don't say that it's to ensure the request is sent.
First, delay the outbound click by a fraction of a second.
This delay will hardly be noticeable by the user, but it will provide the browser more time load the tracking code. Without this method, it's possible that a user can click on the outbound link before the tracking code loads, in which case the event will not be recorded.
I haven't checked #pixelfreak's claim of handling onbeforeunload, but it seems that's what they do.
This is my observation based on some quick research. That function is part of Google Analytic's asynchronous API, so it should not block anything, otherwise, it's not async. :)
Digging through the obfuscated ga.js, you can kinda see that the tracking is probably called onbeforeunload, which fires when you leave a page.
It really doesn't matter if the tracking pixel loads completely, it's a fire & forget. As long as the request is initiated and reaches Google's server, it'll get tracked. The response (in this case, the pixel image) is a by-product.
Maybe you can try this method, but I have not tried
_gaq.push(['_trackEvent', 'xxx' ...]);
_gaq.push(function(){location.reload()});
Just use 1 sec delay. Like this:
_gaq.push(['_trackEvent', 'xxx' ...]);
setTimeout(function(){window.location = 'some_url'}, 1000);

Google Analytics Events - Triggering a user exit

I am looking for a way to simulate with Google Analytics _gaq.push that the user has left the page (so GA stops counting on Average time on site).
This is some code I use to track AJAX pages in Google Analytics (it counts a page view):
_gaq.push(['_trackPageview', '/ajax/save']);
What I am looking for is something such as:
_gaq.push(['_exitCurrentPage', 'http://example.com/']);
Does anything with that functionality exist?
Thanks in advance,
Xavi
I don't think that there's any specific functionality in GA for this but you could just set a cookie called something like dont_track then set it to simulate the page exit. You could then check for the cookie's existence before calling your normal tracking code and stop execution if it exists.

how to cross direct user with google analytics

After a user fills in my "new" user form on "example-one.com", the "create" controller creates the record in the db. Then it does a redirect_to to an external site "payment-checkout.com". I have setup the Google Analytics code on both sites.
Google provides two functions _link and _linkByPost for use to use in any links or forms that go to your external domains. The problem is the user is being redirected by the controller action outside of the view and I cant use those two javascript functions to pass on the relevent G.A. info - what do i do?
Can anyone help?
The way _link works is by passing the Google Analytics cookies from your first domain via a query string to your second domain. The second domain, if configured correctly, will accept those URL parameters and apply them as cookie values for the purposes of tracking.
So, it shouldn't be difficult for you to apply your own version of the _link function.
Specifically, the _link function passes the following cookies:
__utma, __utmb, __utmc, __utmx, __utmz, __utmv and __utmk
Into a query string as such: ?__utma=87278922.614105561.1288923931.1294376393.1298325957.6&__utmb=87278922.1.10.1298325957&__utmc=87278922&__utmx=-&__utmz=87278922.1288923931.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&__utmv=-&__utmk=72493274
So, all you need to do to replicate the _link function is, before you apply the server side redirect, grab the cookie values, and apply them as a query string on the URL you're redirecting to.
Now, that's not the only thing you'll need to do to get this working. The Google Analytics configuration on the payment site will need to be configured with _setAllowLinker set to true, as well as potentially disabling the domain hash and setting a particular domain name for the tracking cookies; it depends on your configuration. You can find out more about that in Google Analytics Cross Domain Tracking Guide.
#yc's approach looks like the best bet but if that doesn't work, I would suggest having your controller redirect the user to a "temp" page on your site itself and show some text like "Checking out....Please wait..." and using Javascript trigger the call to the "_link" function to redirect the user to the "payment-checkout.com" (again using Javascript).
I assume you're also tracking the page the user returns to and want to measure how many users you lose in the process in between?
My knowledge of the Google Analytics API is fairly limited, so maybe there's a better solution, but you could consider rendering a page containing the GA code and triggering the _link() function from there?
It might also be possible to perform an AJAX call on submitting the form (maybe using remote_form_for) and handling the GA redirect in an RJS-response:
page << "_gaq.push(['_link', 'http://example.com/test.html']);"
However, I'm not sure how well that would fit into your application.

Categories