Skip to content

Instantly share code, notes, and snippets.

@phpenterprise
Last active October 30, 2020 12:03
Show Gist options
  • Save phpenterprise/67e541ebf2b2cb41c9dae7b3307d4e9c to your computer and use it in GitHub Desktop.
Save phpenterprise/67e541ebf2b2cb41c9dae7b3307d4e9c to your computer and use it in GitHub Desktop.
Auto Migrate UTM Tags
(MigrateUTM = {
release: '1.0.2',
settings: {
debug: true,
delay: 2000,
tags: [
'utm_medium',
'utm_source',
'utm_campaign',
'utm_term'
]
},
data: {},
setEvents: function () {
this.debug('set events');
this.getParams();
this.detectElements();
},
detectElements: function () {
this.debug('detect links');
var elements = document.querySelectorAll('a[href], form');
if (!elements.length) {
return;
}
this.debug('total elements: ' + elements.length);
for (var i in elements) {
this.migrateParams(elements[i]);
}
},
migrateParams: function (element) {
var url;
if (element && element.href) {
url = this.replaceURL(element.href);
if (url) {
element.href = url;
}
}
if (element && element.action) {
url = this.replaceURL(element.action);
if (url) {
element.action = url;
}
}
},
getParams: function () {
this.debug('detecte params');
var urlParams = new URLSearchParams(window.location.search);
this.data.params = {};
for (var i in this.settings.tags) {
var tag = this.settings.tags[i];
this.data.params[tag] = urlParams.get(tag) || '';
}
this.debug('detected:');
this.debug(this.data.params);
},
addParam: function (url, key, value) {
if (!url || !url.match(/^http/ig) || parseInt(value) === 0) {
return url;
}
this.debug('add param ' + key + ' => ' + value);
url = new URL(url);
url.searchParams.append(key, value);
return url.href;
},
replaceURL: function (url) {
if (!this.data || this.data.params === undefined) {
return;
}
this.debug('replace URL ' + url);
for (var key in this.data.params) {
url = this.addParam(url, key, this.data.params[key]);
}
return url;
},
debug: function (a) {
if (typeof console === 'object' && this.settings.debug) {
console.log(a)
}
},
init: function () {
this.debug('start script');
if (document.readyState === 'complete') {
setTimeout(function () {
MigrateUTM.setEvents();
}, MigrateUTM.settings.delay);
} else {
window.onload = function () {
setTimeout(function () {
MigrateUTM.setEvents();
}, MigrateUTM.settings.delay);
}
}
return 'MigrateUTM complete';
}
}).init();
@phpenterprise
Copy link
Author

phpenterprise commented Oct 21, 2020

Auto Migrate UTM Tags

image

Convert and add UTM tags to all links on a page including the action URL of the forms.

Installation method:

Add the script in the "script" tags on your HTML page using the Google Tag Manager or adding directly to the "header" of the template, inside the "head" tag, for that it is loaded on all pages of the your website.

Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment