views:

489

answers:

2

I'm trying to capture the clicks of certain download links and track them in Google Analytics. Here's my code

var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
    linkpath = links[i].pathname;
    if( linkpath.match(/\.(pdf|xls|ppt|doc|zip|txt)$/) || links[i].href.indexOf("mode=pdf") >=0 ){
     //this matches our search
     addClickTracker(links[i]);
    }
}
function addClickTracker(obj){
    if (obj.addEventListener) {
     obj.addEventListener('click', track , true);
    } else if (obj.attachEvent) {
     obj.attachEvent("on" + 'click', track);
    }
}
function track(e){
    linkhref = (e.srcElement) ? e.srcElement.pathname : this.pathname;
    pageTracker._trackPageview(linkhref);

 }

Everything up until the pageTracker._trackPageview() call works. In my debugging linkhref is being passed fine as a string. No abnormal characters, nothing. The issue is that, watching my http requests, Google never makes a second call to the tracking gif (as it does if you call this function in an "onclick" property). Calling the tracker from my JS console also works as expected. It's only in my listener.

Could it be that my listener is not deferring the default action (loading the new page) before it has a chance to contact Google's servers? I've seen other tracking scripts that do a similar thing without any deferral.

A: 

Try

pageTracker._trackPageview('/pagex/downloadlink.html')

Also, just for fun make sure the GA code is loaded first before this script. Sometime GA is picky and weird like that.

Let me know if that helps

@ctrentmarketing

Yeah, I tried tracking a static path as you suggested, which didn't work either. Definitely made sure that GA is loaded before this script, and no dice.
dmrnj
I feel like I owe this question an update since it's almost a year later and I've run into this problem many times. My _pageTracker object was using _setDomainName(), but I was trying this code locally. When the domain conflicts, the tracking JS obviously loads, but the tracking pixel never gets called.
dmrnj
A: 

Well here is an update, I have been using this script to accomplish this task for me: http://www.tatvic.com/trackExternal.js

ctrentmarketing
^Yeah, that doesn't solve the problem I was having, which was the actual server responding, and as you can see from my update below that it had nothing to do with that code, but the tracking code itself.
dmrnj