Skip to content

Instantly share code, notes, and snippets.

@agarbund
Last active September 4, 2018 10:54
Show Gist options
  • Save agarbund/5436ddfacd9f4d0b5ba4e90c362fb5a3 to your computer and use it in GitHub Desktop.
Save agarbund/5436ddfacd9f4d0b5ba4e90c362fb5a3 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/jiqiwag
// script which reads UTM params from the URL and adds them to all links on the current page
$(document).ready(function() {
var utms = ['medium', 'source', 'campaign', 'term', 'content'], utmStrings = [];
var domain = ''; // add domain here, only links to given domain will be siffixed with utm params
var domainRegexp = new RegExp(domain.replace(/\./g, '\\.'));
utms.forEach(function(utm) {
var match = window.location.search.match(new RegExp('utm_' + utm + '=([^&]+)'));
if(match) {
utmStrings.push('utm_' + utm + '=' + match[1]);
}
});
if(utmStrings.length) {
$('a').each(function() {
var link = this.href, prefix, params = '';
if(
link.match(domainRegexp) &&
!link.match(/[?&]utm_/)
) {
prefix = link.match(/\?/) ? '&' : '?';
this.href = link + prefix + utmStrings.join('&');
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment