[cross-posted on Google Products Forum http://productforums.google.com/d/topic/analytics/ZrB14a-6gqI/discussion ]
I am using the following code at http://www.cs.bris.ac.uk/Research/Algorithms/
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<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>
which I just copied directly from http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920 .
However, it doesn't actually seem to report any clicks on the links where I have added onClick="recordOutboundLink(this, 'Outbound Links', 'Postdoc advert');return false;", for example. I have seen a number of complaints about this online but I haven't found a solution that works.
What am I doing wrong?
P.S. The closest related online complaint seems to be http://productforums.google.com/forum/#!topic/analytics/4oPBJEoZ8s4 which just claims the code is broken.
Here's what I'm using, which has been working for me. I'm using jQuery to add the onclick handler to any link with a class of "referral", but I'd expect adding it directly in the HTML to work as well.
$(function() {
$('.referral').click(function() {
_gaq.push(['_trackEvent', 'Referral', 'Click', this.href]);
setTimeout('document.location = "' + this.href + '"', 100);
return false;
});
});
edit: I believe your syntax for invoking a tracker by name is wrong. Since you aren't using a named tracker when you set up tracking at page load, you shouldn't try to name it later either. See the documentation for _gaq.push.
More precisely:
The var myTracker declaration is unused, so you can just delete that line. Variables declared within the scope of recordOutboundLink aren't visible when other functions, such as _gaq.push, are running, so it can't be relevant.
You should simply use '_trackEvent' instead of 'myTracker._trackEvent'.
You can also try this automated external link script
Set a longer timeout 2 seconds maybe, as it takes a certain amout of time for the _gaq.push to actually push to the server, and 100 milliseconds isnt long enough for it to send (the push gets cancelled as soon as the document.location changes). Unless _gaq.push uses a blocking call (doesnt execute the next line till the push is complete), but i dont think that is the case i think most of that uses asynchronous requests.
Related
I'm retrieving content via a jQuery get Ajax call and add it to an element afterwards. The HTML code is added without any problem, just the JS code gets lost. What am I doing wrong? When I look at the response in Firebug it is still there, it's just not added to the HTML element.
My Ajax request:
function get_overlay_content(path)
{
$.get(path, function(data) {
$("#overlay_content").html(data).fadeIn(500);
$(function()
{
// do something
});
});
}
The response in Firebug:
<div id="imprint" class="overlay_box">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="overlay_close" onclick="close_overlay();"><img src="/2012/images/overlay_close.png" id=""></div>
# ETC
The HTML after update:
<div id="overlay_content">
<div id="imprint" class="overlay_box">
<div id="overlay_close" onclick="close_overlay();"><img src="/2012/images/overlay_close.png" id=""></div>
<div class="overlay_heading"><img src="/2012/images/heading_download.png" height="65"></div>
# etc.
My guess is that it has something to do with encoding. What do you think?
Thanks!
Olaf
SOLVED:
Thanks to Uzi, the solution was quite simple, following the Google guide Asynchronous Tracking Usage Guide
But for everyone to understand: If you have one main file (index.html) from where you retrieve partials (lets call it /partials/_download_pdfs.html) via an AJAX GET request (e.g. jQuery.get()) all you have to do to track every AJAX request with Google Analytics is the following:
Add the tracking code for Analytics ABOVE the rest of your Javascript
and your AJAX GET request, put the following code in a callback function (if you don't put it in a callback it might slow down your actual request)
$.get(path_to_track, function(data) {
// Fade in effect:
$("#container").html(data).fadeIn(500);
// this part is interesting:
_gaq.push(['_setAccount', 'UA-XXX-1']);
_gaq.push(['_trackPageview', path_to_track]);
// Do other stuff in the callback
});
That's it. If you want to track PDF downloads on a page you retrieved with an AJAX GET request with jQuery (as I did), just add the following code to the partial (eg /partials/_download_pdfs.html)
<script type="text/javascript">
$(document).ready(function() {
$(".pdf_link").click(function(){
_gaq.push(['_setAccount', 'UA-XXX-1']);
_gaq.push(['_trackPageview', '/pdf/' + $(this).attr("id")]);
});
});
</script>
If I understand correctly, you are fetching HTML code using AJAX.
That block of code contains a script tag, and you expect the script to run one the request is complete.
Unfortunately it doesn't work this way, since as far as the DOM concerned, this is just an element.
I'm not sure why you need an AJAX code for google analytics to run, but in case it contains dynamic data, just make the AJAX call return the parameter you need and have a function running this code locally.
I have the asynchronous JavaScript from Google added to my HTMl page which adds the tracker:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Then in an external JS file which is definitely loaded after ga.js I have the following:
function activateAnalyticsTracking(href) {
_gaq.push(['trackEvent', "test", "tester"]);
console.log("_gaq.push called");
}
Now my console outputs "_gaq.push called", and I don't have any other vars on the page called _gaq, so I don't understand why, when I use a HTTP logging tool like Fiddler2 I don't see a call made to Google-analytics.
I do see a call though when I simply run _gaq.push(['_trackEvent', "test", "tester"]) from the console, so the code for that call is definitely right.
I have this function used specifically because I run other events when I link is clicked, so I'd like to use it, can anyone help me understand why this wouldn't work?
TIA
Cheers,
Blaise.
Seems like you're missing one underscore in _trackEvent. It should look like this:
_gaq.push(['_trackEvent', "test", "tester"]);
I was playing around with custom variables in Google Analytics and wasn't sure why the following actually works. Why does Google's tracking code get executed first, especially since it is at the bottom of the page?
Both scripts are in self-executing functions, so how does javascript determine which one to execute first?
// top of the page
<script type="text/javascript">
$(function ()
{
_gaq.push(['_setCustomVar', 1, 'Account', 'PartTime', 1]);
});
</script>
// bottom of the page
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxxxx']);
_gaq.push(['_setDomainName', '.xxxxxxxx.com']);
_gaq.push(['_trackPageview']);
(function ()
{
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
The first one does execute first, and isn't in a self executing function.
It consists of a call to the $ function and has one argument: an anonymous function.
$ is a very badly named function. The name itself is meaningless and it has been adopted by half a dozen different libraries to do half a dozen different things.
In jQuery, if you pass a function to $ it runs that function when the ready event is triggered (but the end of the HTML document being parsed). This is probably what is happening here.
I am attempting to add google analytics tracking to an Adobe Air app created with HTML and javascript.
I have tried adding the ga.js file and using it like I would in a webpage:
<script type="text/javascript" src="lib/js/ga.js"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-********-1");
pageTracker._initData();
pageTracker._trackPageview('/test');
</script>
But this doesn't seem to register anything on the analytics dashboard.
Have also tried using the GA for flash actionscript library but I can't seem to create an instance of the GATracker as it needs a DisplayObject?
EDIT
using the information from grapefrukt I tried the following:
air.Sprite = window.runtime.flash.display.Sprite;
air.GATracker = window.runtime.com.google.analytics.GATracker;
var tracker = new air.GATracker( new air.Sprite(), "UA-XXXXXXX-X", "AS3", false );
but I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference
NOTE: I originally misread your question to be about how to use gaforflash, but I'll post this anyway since I've already typed it up and it might be of some use.
You can the constructor whatever DisplayObject you like, normally you'd use your document class, but anything will work. As far as I can understand it's only really used for displaying debug info.
var tracker:AnalyticsTracker = new GATracker( new Sprite, "UA-XXXXXXX-X", TrackerMode.AS3, false );
Setting the TrackerMode to AS3 let's the flash communicate directly with the tracking servers, so you don't need the javascript from google's servers.
I can't help you with the communication between js/as3, but that should be fairly easy.
Probably not useful to the OP, but just spent the whole day working around this so hopefully my solution will save someone else that time.
So the reason the ga.js code can't be used directly from an AIR app written in javascript is that AIR won't set the cookie for pages that are stored within the application itself. To work around this, I downloaded ga.js to the application and modified it so that it doesn't rely on the document.cookie function.
In the application, I have:
<script type="text/javascript">
var cookies = {};
document.__defineSetter__('_cookie', function(c) {
var epos = c.indexOf('=');
var spos = c.indexOf(';', Math.max(0, epos));
if (epos == -1 || spos == -1) { return; }
var name = c.substring(0, epos);
var value = c.substring(epos + 1, spos);
cookies[name] = value;
});
document.__defineGetter__('_cookie', function() {
var a = [];
for (var name in cookies) {
a.push(name + '=' + cookies[name]);
}
return a.join('; ');
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-1']);
_gaq.push(['_trackPageview', path])
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
// custom GA code which uses document._cookie instead of
// document.cookie
ga.src = 'js/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Ideally, we'd be able to override the cookie method, but unfortunately, it doesn't seem possible in webkit as implemented for AIR. So in ga.js, I replaced all instances of J.cookie with J._cookie. Once that's done, ga.js should believe that it's writing cookies and function normally.
In the interest of full disclosure, I actually access the above analytics code through an iframe, but since ga.js is being served locally, I suspect it's no longer necessary and didn't want to complicate the solution by adding the bridge logic.
Wonder if somebody is able to clarify the following;
Using the aysnc google analytics code placed in the head of the document as follows
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456-1']);
_gaq.push(['_setDomainName', '.somedomain.co.uk']);
_gaq.push(['_trackPageview', pageUrl]);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
On some the pages I am tracking I also use custom events to track video plays and which forms are used. These events use a further _gaq.push() call at various points on the page.
My question is should the final section of the initial analytics code (the section that calls ga.js be split and placed at the end of the page code or will any calls made once the script has loaded still be passed to Analytics regardless of the position on the page.
Thanks in advance.
No, the final section of the initial analytics code need not be placed lower down. You can call as many _gaq.push() calls as you like throughout the page, they'll still successfully pass to analytics.
The _gaq.push() event calls will send new requests to Google Analytics in addition to the first one you make (_trackPageview). You can check those event calls my inspecting how many requests your page makes for _utm.gif in a tool like Firebug.