Problem executing trackPageview with Google Analytics

风流意气都作罢 提交于 2019-12-23 06:01:14

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/1263212/problem-executing-trackpageview-with-google-analytics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!