Running JavaScript after Google Analytics

I use Google Analytics and redirect after completing the analytics request.

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 does not work correctly.

The redirection is performed correctly (as an analytics callback) in Firefox, but not in other browsers (IE, Chrome, Safari), so I am losing analytics data.

At the moment, I set the timeout to 1 s, but this is not a real solution.

Any help on how to implement this correctly?

+6
source share
1 answer

Now there is no good solution to this problem. The best you can do is add a timeout to delay the redirect. There is currently no callback in _trackPageview. When he returns, it means that he started tracking, but did not guarantee that he successfully registered the pageview until the __utm.gif request was completed.

1 timeout may be too long. I usually save a timeout of about 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 two years since I originally posted this answer, and since then Google Analytics has come a long way.

Now there is the right 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 switched to Universal Analytics using analytics.js, the equivalent will look like this:

 ga('create', 'UA-XXXXXXX-X') ga('send', 'pageview', { 'hitCallback': function() { window.location.href = newUrl; } }); 

EDIT 2

Here's a better way to do this, to make sure your code runs even if the Google Analytics code is blocked or modified by the 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 }); 
+11
source

Source: https://habr.com/ru/post/908604/


All Articles