3

What I am trying to do is to redirect the user to the next page right after sending an event to Google Analytics:

_gaq.push(['_trackEvent', 'xxx' ...]);
window.location = 'some url ...';

The above code manages to register events because I can see them in the GA report. However I suspect that some events were lost because the browser redirects the user to the new page before the track pixel loads.

My questions are:

  1. Does _gaq.push() block until the event has successfully reached Google's server?
  2. If not, what is the best way to make achieve what I need?

Thanks!

mtrbean
  • 903
  • 7
  • 15
  • Related: http://stackoverflow.com/questions/3427580/race-condition-and-using-google-analytics-asynchronous-gaq-synchronously – Rob Hruska Sep 20 '13 at 15:14

4 Answers4

1

Google has a support page that says you might want to add a delay after calling _gac.push, however they claim that this is to give the Google Analytics JavaScript a chance to load. They don't say that it's to ensure the request is sent.

First, delay the outbound click by a fraction of a second.

This delay will hardly be noticeable by the user, but it will provide the browser more time load the tracking code. Without this method, it's possible that a user can click on the outbound link before the tracking code loads, in which case the event will not be recorded.

I haven't checked @pixelfreak's claim of handling onbeforeunload, but it seems that's what they do.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
0

Maybe you can try this method, but I have not tried

_gaq.push(['_trackEvent', 'xxx' ...]);
_gaq.push(function(){location.reload()});
user873792
  • 323
  • 2
  • 8
0

Just use 1 sec delay. Like this:

_gaq.push(['_trackEvent', 'xxx' ...]);
setTimeout(function(){window.location = 'some_url'}, 1000);
mrded
  • 4,674
  • 2
  • 34
  • 36
0

This is my observation based on some quick research. That function is part of Google Analytic's asynchronous API, so it should not block anything, otherwise, it's not async. :)

Digging through the obfuscated ga.js, you can kinda see that the tracking is probably called onbeforeunload, which fires when you leave a page.

It really doesn't matter if the tracking pixel loads completely, it's a fire & forget. As long as the request is initiated and reaches Google's server, it'll get tracked. The response (in this case, the pixel image) is a by-product.

pixelfreak
  • 17,714
  • 12
  • 90
  • 109
  • Uhm, no ? 1) "push" is native javascript, the only google specific thing here is the name of the array to which the data is added. And the image request is not a byproduct, it is the data that is sent to google. That's why Google suggests to add a timeout before a redirect or, with Universal Analytics, to use hit callbacks. – Eike Pierstorff May 12 '14 at 12:30