Skip to content

Instantly share code, notes, and snippets.

@bjornpagen
Last active January 31, 2023 03:00
Show Gist options
  • Save bjornpagen/40f2ebc12e20ac6ec307bc96d7d74f4b to your computer and use it in GitHub Desktop.
Save bjornpagen/40f2ebc12e20ac6ec307bc96d7d74f4b to your computer and use it in GitHub Desktop.
Append UTM parameters to specific domains in a webpage using JavaScript. The function loops through all the links on a page and checks if the link is part of the specified domains. If it is, the UTM parameters from the URL are added to the link.
function appendUTMParams(domains) {
// Get all the links on the page
var links = document.getElementsByTagName("a");
// Get the UTM parameters from the URL
var search = window.location.search;
var params = new URLSearchParams(search);
// Array of allowed UTM parameters
var allowedUTMs = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
// Loop through each link
for (var i = 0; i < links.length; i++) {
var link = links[i];
var href = link.getAttribute("href");
// Check if the link is in the list of domains
for (var j = 0; j < domains.length; j++) {
if (href.indexOf(domains[j]) !== -1) {
// Append only the allowed UTM parameters to the link
var utmParams = "";
for (var [key, value] of params.entries()) {
if (allowedUTMs.indexOf(key) !== -1) {
utmParams += key + "=" + value + "&";
}
}
if (utmParams) {
href += "?" + utmParams.slice(0, -1);
}
link.setAttribute("href", href);
break;
}
}
}
}
// Call the function on page load
document.addEventListener("DOMContentLoaded", function() {
var domains = ["stripe.com"];
appendUTMParams(domains);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment