Problem executing trackPageview with Google Analytics.

Posted by dmrnj on Stack Overflow See other posts from Stack Overflow or by dmrnj
Published on 2009-08-11T22:01:20Z Indexed on 2010/06/11 8:03 UTC
Read the original article Hit count: 265

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events