7

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?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Amir
  • 211
  • 3
  • 14

1 Answers1

13

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
});
Eduardo
  • 22,574
  • 11
  • 76
  • 94
  • 1
    Be careful, it will NOT work if someone has AdBlock or Ghostery on. If you want to execute the location change for AdBlock users, use setTimeout without pushing it to the ga array in a function. – Daniel W. Dec 08 '15 at 12:33