How to Track Page Views with Google Analytics During JavaScript Redirects

I’m having trouble getting my Google Analytics tracking to work properly when doing page redirects with JavaScript.

Here’s my setup:

  • I have a landing page that needs to redirect users to an external site.
  • I want to track this redirect event in Google Analytics before the user leaves.
  • Right now, the redirect works but the Analytics data isn’t being recorded.

This is my current implementation:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function performRedirect(){
    window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany"
}
</script>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-9876543-1']);
  _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('performRedirect()', 2500)">
<h1>Redirecting you to our new app store page in a few seconds...</h1>
</body>
</html>

The redirect function works fine when I remove the Analytics code, but with it included, the tracking doesn’t seem to fire properly. I’ve tried different methods including PHP redirects but haven’t had any success.

What’s the correct way to ensure Google Analytics tracking completes before redirecting users to another domain?

Any solution would be helpful, doesn’t have to be JavaScript specifically.

Dealing with the exact same headache on our affiliate tracking pages. The problem is browsers kill pending network requests when you change locations, so your GA beacon never gets sent.

I found navigator.sendBeacon works way better than hitCallback for redirects. It’s built for page unload scenarios:

function performRedirect(){
    // Send tracking data with beacon
    if (navigator.sendBeacon) {
        var data = 'v=1&tid=UA-9876543-1&cid=' + Math.random() + '&t=event&ec=redirect&ea=external&el=playstore';
        navigator.sendBeacon('https://www.google-analytics.com/collect', data);
    } else {
        // Fallback for older browsers
        _gaq.push(['_trackEvent', 'Redirect', 'External', 'Play Store']);
    }
    
    // Small delay then redirect
    setTimeout(function(){
        window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany";
    }, 100);
}

The sendBeacon API is built for this exact use case and survives page navigation. Been using this for 6 months now - tracking reliability went from maybe 60% to consistently above 95%. Just make sure you construct the measurement protocol payload correctly with your actual tracking ID.

skip the javascript headaches and use a server-side redirect with measurement protocol. post your tracking data to google-analytics.com/collect, then hit them with a 302 redirect. way more solid than client-side tricks and you won’t deal with browser quirks or beacon support issues.

Had the exact same problem with our SaaS trial signups. Analytics needs a few hundred milliseconds to finish its HTTP request before the page redirects.

The newer gtag with transport beacon solved it completely. Way more reliable than those old _gaq methods:

function performRedirect(){
    gtag('event', 'redirect_click', {
        'event_category': 'outbound',
        'event_label': 'playstore',
        'transport_type': 'beacon',
        'event_callback': function(){
            window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany";
        }
    });
    
    // Backup redirect after 500ms
    setTimeout(function(){
        window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany";
    }, 500);
}

The beacon parameter handles browser compatibility and falls back automatically. Event callback waits for tracking to finish before redirecting.

Your ga.js setup is deprecated anyway - Global Site Tag is much more reliable. I’ve been using this method for two years without losing any data.

Your redirect’s happening too fast for GA to send the tracking data. Hit this exact issue a few years back with redirect pages for our mobile app campaigns.

Your code’s running the tracking and redirect independently. GA needs time to actually send that data before the page unloads.

Here’s what fixed it for me:

function performRedirect(){
    // Track the event first
    _gaq.push(['_trackEvent', 'Redirect', 'External', 'Play Store']);
    
    // Use hitCallback to ensure tracking completes
    _gaq.push(['_set', 'hitCallback', function(){
        window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany";
    }]);
    
    // Fallback redirect in case GA fails
    setTimeout(function(){
        window.location.href = "https://play.google.com/store/apps/developer?id=MyCompany";
    }, 1000);
}

The hitCallback fires after GA successfully sends the data. setTimeout’s your safety net if GA fails to load or takes forever.

Tracking an event instead of just a pageview also gives you better data about these redirects in your reports.

One more thing - do you actually need JavaScript redirects? A simple 302 redirect with the tracking pixel might be cleaner depending on what you’re doing.