Skip to content

Instantly share code, notes, and snippets.

@elidickinson
Forked from paulirish/utmstrip.user.js
Last active May 24, 2016 08:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elidickinson/9128677 to your computer and use it in GitHub Desktop.
Save elidickinson/9128677 to your computer and use it in GitHub Desktop.
Strips visible utm_ strings off URLs on your site, but makes sure Google Analytics tracks them first
// utmstrip.js strips utm_* strings from the URL bar of your site, but afer Google Analytics
// has had a chance to grab them. Based on Paul Irish's utm-stripping user script.
//
// Source: https://gist.github.com/elidickinson/9128677
//
// Install Notes:
// - This script should run *after* you have added all your "_trackPageview" or "_trackEvent"
// calls to the _gaq variable.
// - It doesn't matter of Google Analtyics has actually finished loading yet, but if you
// you tell it to strip the utm_* strings before _trackPageview sees them, it won't know
// they were there.
// don't do anything if _gaq isn't even defined yet
if (((typeof _gaq != "undefined") && (typeof _gaq.push == "function"))) {
// add the logic to strip utm tags to the _gaq command queue so that we can schedule
// it to run after tracking calls to Google have already seen the utm values
_gaq.push(function(){
// ----- The below bit of showoff & magic is by Paul Irish's utmstrip.user.js v1.1
// See https://gist.github.com/paulirish/626834
if (/utm_/.test(location.search) && window.history.replaceState){
// thx @cowboy for the revised hash param magic.
var oldUrl = location.href;
var newUrl = oldUrl.replace(/\?([^#]*)/, function(_, search) {
search = search.split('&').map(function(v) {
return !/^utm_/.test(v) && v;
}).filter(Boolean).join('&'); // omg filter(Boolean) so dope.
return search ? '?' + search : '';
});
if ( newUrl != oldUrl ) {
window.history.replaceState({},'', newUrl);
}
}
// ----- end magic from https://gist.github.com/paulirish/626834
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment