Javascript Redirect with Google Analytics

25,584

Solution 1

Using meta refresh worked like a charm! Legacy FTW! Thanks, @Balexandre

<html>
<head>
<meta http-equiv="refresh" content="5; url=https://market.android.com/developer?pub=Fractal%20Systems">
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</head>
<body>
<h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 5 seconds.</h2>
</body>
</html>

RECAP: I am now able to redirect while tracking those redirects using Google Analytics!

Meta Refresh (Taken from wikipedia)

Examples

Place inside to refresh page after 5 seconds:

<meta http-equiv="refresh" content="5">

Redirect to http://example.com/ after 5 seconds:

<meta http-equiv="refresh" content="5; url=http://example.com/">

Redirect to http://example.com/ immediately:

<meta http-equiv="refresh" content="0; url=http://example.com/">

Solution 2

Note: _gaq.push allows pushing of functions onto the queue. The following code should redirect after 250 milliseconds (to allow time for the tracking pixel) after the _trackPageview:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
    setTimeout(function() {
        window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
    }, 250);
});

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

Solution 3

If you're using the new GA code you can simply replace this line ga('send', 'pageview'); with this code:

ga('send', 'pageview', {
  'hitCallback': function() {
      window.location = "http://www.your-site.com";
  }
});

Example in full:

  (function(i,s,o,g,r,a,m){
    i['GoogleAnalyticsObject']=r;
    i[r]=i[r]||function() {
        (i[r].q=i[r].q||[]).push(arguments)
    },i[r].l=1*new Date();
    a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];
    a.async=1;
    a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-xxxxxxx-2', 'auto');

ga('send', 'pageview', {
  'hitCallback': function() {
      window.location = "http://www.your-site.com";
  }
});

Solution 4

I'd suggest changing your Google Analytics code to be synchronous instead of asychronous by changing it to this:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>

This should guarantee that it runs before your redirect code kicks in and it should be out of the way of your redirect script so there is no interference. As you have it now, you're playing a guessing game for how long the GA script will take to load and that it will load and do it's job in under 3 seconds. That may usually be the case, but there is no reason to load it asynchronously like you are and have to play that game. Load it synchronously and it will do it's job before your javascript redirect fires.

It might even be possible to just put the redirect directly after the GA code like this and minimize the time that your placeholder page is displayed:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1234567-8']);
  _gaq.push(['_trackPageview']);
</script>
<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript">
  window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
</script>

Solution 5

The code provided by Mike works indeed. However, I found that removing the timer entirely works as well. The __utm.gif request is then aborted, but all information has been sent. The window just redirects and doesn't wait for the reply (which is simply a 200 status). I tested this and it seems to be working nicely.

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1234567-8']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
  window.location = "https://market.android.com/developer?pub=Fractal%20Systems";
});


(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Share:
25,584
TryTryAgain
Author by

TryTryAgain

All around Technology Lover. Built my first PC at age 8, first full-time paid computer job at age 14, been in IT ever since. English Literature and Philosophy of Technology educated human who spends most of his time on Stack Overflow...go figure! I've been a leech on the Stack Exchange Networks for all too long, now I've started answering and asking questions and I'm really enjoying all too many of the Stack Exchange communities! #SOreadytohelp Android Developer Market Page Google.com/+MichaelLawler LinkedIn Profile

Updated on February 28, 2020

Comments

  • TryTryAgain
    TryTryAgain about 4 years

    I need help figuring out how to successfully redirect while including Analytics code.

    The code for that redirect file:

    <head>
    <script type="text/javascript">
    function delayedRedirect(){
        window.location = "https://market.android.com/developer?pub=Fractal%20Systems"
    }
    </script>
    <script type="text/javascript">
    
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1234567-8']); <!--I have my real ID there-->
      _gaq.push(['_trackPageview']);
    
      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    
    </script>
    </head>
    <body onLoad="setTimeout('delayedRedirect()', 3000)">
    <h2>ADW.BuuF.Theme is no more! You will be redirected to new and better apps in 3 seconds.</h2>
    </body>
    </html>
    

    This works as a redirect only if I don't include my Analytics code. I've tried moving the code around with no change.

    QUESTION How can I add a redirect, of any kind, and still be able to track with Google Analytics?

    I've tried PHP redirects with no success and am pretty sure htaccess redirects wont help although I'm open to suggestions.

    The reason I'm using a JavaScript redirect is so I can continue to track with Google Analytics and also show a little message or make a custom page with the delay.

    Thanks for any help. Doesn't have to be JS, please, any input is welcome if you know of a solution.

  • TryTryAgain
    TryTryAgain over 12 years
    Thanks, that does work with all redirect methods I've tried. Good to know.
  • DS_web_developer
    DS_web_developer about 12 years
    any ideas of how to redirect fast (and not 5s)?
  • TryTryAgain
    TryTryAgain about 12 years
    @DS_web_developer This solution worked for me, you could try and simply change the content=5 value to something else, but that isn't the most robust...you should use stackoverflow.com/a/8692588/805031
  • kontur
    kontur over 11 years
    Perfect answer. You might add a simple text link to the redirect url in the body text, so that users without javascript can reach the redirect url. Additionally, the google reference doc with the section on pushing functions can be found here: developers.google.com/analytics/devguides/collection/gajs/…
  • aruno
    aruno over 11 years
    I'm not convinced you need a timeout - the request for the image should always go out before the redirect - it doesn't matter if the client never receives any data back
  • mike
    mike over 11 years
    @Simon_Weaver Agreed that it's not important that the client never receives any data back, but it appears (at least with Chrome & Firefox) that the browser will not make the tracking pixel request if the window changes too quickly after the request is started. Google even has a note about using a delay, but their code is mucked up, mixing sync & async style analytics.
  • fredrik
    fredrik about 11 years
    @mike Do you remember where you found the note about using delay from google?
  • kizzx2
    kizzx2 almost 11 years
    Some people block GA so using a <meta> tag redirect as a fallback is a good idea.
  • user1997781
    user1997781 about 10 years
    This solution works beautifully...but if a user has JavaScript disabled, will GA not only not work, but the page won't redirect as well? Would it be best to have a meta redirect after this script, just in case?
  • Tosh
    Tosh over 9 years
    auto should be quoted
  • Koen.
    Koen. about 9 years
    Using jQuery in this case is way much overhead, and most of all, unnecessary.
  • Jeff
    Jeff about 9 years
    I would love to see this answer updated to also include an answer with the new universal tracking code.