Skip to content

Instantly share code, notes, and snippets.

@jsn789
Last active July 12, 2023 12:59
Show Gist options
  • Save jsn789/3dc5c0b868e2568f1602148cb8829ccf to your computer and use it in GitHub Desktop.
Save jsn789/3dc5c0b868e2568f1602148cb8829ccf to your computer and use it in GitHub Desktop.
Persist UTM Parameters in a URL by decorating on-page <a> elements. Required on all pages.
// Script to persists the listed querystring parameters across the length of the session.
(function() {
var domainsToDecorate = [
'exampledomain.com' //add or remove domains (without https or trailing slash)
],
queryParams = [
'utm_medium', //add or remove query parameters you want to transfer
'utm_source',
'utm_campaign',
'utm_adgroup',
'utm_content',
'utm_term',
'gclid',
'fbclid'
]
//decorate all links on the page
var links = document.querySelectorAll('a');
// check if links contain domain from the domainsToDecorate array and then decorates
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
// decorates the URL with query params
function decorateUrl(urlToDecorate) {
//urlToDecorate uncessary ?
//check if there are any parameters existing
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
//YL: added as a fix to ensure url is not modified when UTMs are not in place
if(collectedQueryParams.length < 1){
urlToDecorate = urlToDecorate
}
else{
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment