stevecomrie
stevecomrie

Reputation: 2483

Google Analytics tracking

I'd like to remove the Google Analytics URL tracking code from the browser bar so that when a user copy / pastes the URL to share they don't bring along all the tracking data with them, which is both useless and able to skew the data down the road.

So I'm using history.js to run replaceState to basically get rid of the tracking data from the URL after a brief pause.

<script type="text/javascript">
setTimeout(function() {
    if( window.location.search.indexOf( "utm_campaign" ) >= 1 ) {
        window.history.replaceState( null, document.title, window.location.pathname);
    }
}, 1000 );
</script>

Does anyone see any possible complications or problems with such a method?

Upvotes: 0

Views: 555

Answers (1)

Tim Groeneveld
Tim Groeneveld

Reputation: 9039

The only problem that you might have is that Google Analytics might not have been fully loaded by the time that your timeout code runs.

With the Google Analytics tracker, there is an API that lets a function be queued after the GA data has been sent off to Google.

You can do something like this:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
_gaq.push(function() {
  var newPath = location.pathname + location.search.replace(/[?&]utm_[^?&]+/g, "").replace(/^&/, "?") + location.hash;
  if (history.replaceState) history.replaceState(null, '', newPath);
});

(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);
})();

Notice line 4, where a function is pushed to the _gaq object.

This function will replace the URL straight after the GA request has been sent.

Upvotes: 1

Related Questions