Skip to content

Instantly share code, notes, and snippets.

@CanRau
Last active April 22, 2019 04:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CanRau/18995476d503a113697e720003d98699 to your computer and use it in GitHub Desktop.
Save CanRau/18995476d503a113697e720003d98699 to your computer and use it in GitHub Desktop.
Removes all query parameters from the url beginning with 'utm_', leaves anchors (#) and other query params alone
/**
* GTM utm_ remover
* License: MIT
* Author: @CanRau
* Version: 0.2.0
*
* Removes all query parameters from the url beginning with 'utm_'
* Leaves anchors (#) and other query params alone, so
* example.com/?session=SESSIONID&utm_source=instagram#content
* would become
* example.com/?session=SESSIONID#content
*
* Works only in Browsers supporting the History API
* https://caniuse.com/#feat=history
*
* Usage:
* 1. Store this script in a Google Tag Manager variable
* 2. Open the tag you want this to get fired (I use Google Universal Analytics - Pageview - All pages)
* 3. Enable override settings
* 4. Define a field called 'hitCallback'
* 5. Set the value to the in 1. created variable using the lego brick icon
* 6. Save & publish
*
* Changelog:
* 0.2.0: improves regex
*/
function() {
return function() {
if (!!(window.history && history.pushState)) {
if (/(\?|&)utm_.*=/.test(window.location.search)) {
window.history.replaceState({}, document.title, document.location.pathname + document.location.search.substring(1).split('&').filter(function(x) {return !/^utm_.*=/.test(x)}).join('&').replace(/^(.*)/, '?$1') + document.location.hash)
}
if (/\?$/.test(document.location.href)) {
window.history.replaceState({}, document.title, document.location.pathname)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment