Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript execute after google analytics

I am using Google Analytics and doing redirect after analytics request has finished.

I am using this code:

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-12345678-1']);

_gaq.push(['_trackPageview']);

_gaq.push(function () {
     window.location.replace("myRedirectToUri");
});

This is not executed correctly.

Redirect is done correctly (as analytics callback) on Firefox, but not on other browsers (IE, Chrome, Safari) so I lose analytics data.

At the moment I have set timeout of 1 sec but that is not the real solution.

Any help how to implement this correctly?

like image 623
Amir Avatar asked Feb 16 '12 10:02

Amir


1 Answers

Right now there's no good solution to this problem. The best you can do is to add a timeout to delay the redirection. Currently there's no callback to the _trackPageview. When it returns it means that it started the tracking, but it's not garanted that it have successfully registered the pageview until the __utm.gif request is complete.

1 sec timeout may be too much. I usually keep the timeout around 200-400 ms.

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);

_gaq.push(['_trackPageview']);

_gaq.push(function () {
     setTimeout(function(){
         window.location.href = newUrl;
     }, 200);
});

EDIT:

It's been 2 years since I originally initially posted this answer and since then Google Analytics has come a long way.

Now there's a proper way to do this:

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);

_gaq.push(['_set','hitCallback',function(){
  window.location.href = newUrl;
}]);  

_gaq.push(['_trackPageview']);  

And if you have migrated to Universal Analytics using analytics.js the equivalent would be:

ga('create', 'UA-XXXXXXX-X')

ga('send', 'pageview', {
  'hitCallback': function() {
    window.location.href = newUrl;
  }
});

EDIT 2

Here's the more proper way to do this to make sure your code executes even if Google Analytics code is blocked or tampered by an extension or adBlocker.

var t = undefined;

var myCode = function(){
  window.clearTimeout(t);
  t = undefined;
  window.location.href = newUrl;

};

t = setTimeout(myCode, 3000);

ga('create', 'UA-XXXXXXX-X')

ga('send', 'pageview', {
  'hitCallback': myCode
});
like image 136
Eduardo Avatar answered Oct 17 '22 20:10

Eduardo