Last active
January 31, 2023 03:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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