Skip to content

Instantly share code, notes, and snippets.

@jubstuff
Created September 19, 2024 11:22
Show Gist options
  • Save jubstuff/da44171d56db18a712c0d2157ed72103 to your computer and use it in GitHub Desktop.
Save jubstuff/da44171d56db18a712c0d2157ed72103 to your computer and use it in GitHub Desktop.
A simple utm link passthrough
(function() {
// Helper function to get UTM parameters from the URL
function getUTMParams() {
const urlParams = new URLSearchParams(window.location.search);
const utmParams = {};
['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'].forEach(param => {
if (urlParams.has(param)) {
utmParams[param] = urlParams.get(param);
}
});
return utmParams;
}
// Helper function to append UTM parameters to a given URL
function appendUTMParamsToUrl(url, utmParams) {
if (Object.keys(utmParams).length === 0) return url; // If no UTM params, return original URL
const urlObj = new URL(url);
Object.keys(utmParams).forEach(key => {
urlObj.searchParams.set(key, utmParams[key]);
});
return urlObj.toString();
}
// Main function to modify the hrefs of specific links
function appendUTMToLinks(targetUrl) {
const utmParams = getUTMParams();
if (Object.keys(utmParams).length === 0) return; // Do nothing if no UTM params exist
const links = document.querySelectorAll(`a[href^="${targetUrl}"]`);
links.forEach(link => {
link.href = appendUTMParamsToUrl(link.href, utmParams);
});
}
// Example: Modify all links that point to "https://example.com"
const targetBaseUrl = "https://example.com"; // Change this to your target URL
appendUTMToLinks(targetBaseUrl);
// Optional: Automatically run this on all clicks on the page
document.body.addEventListener('click', function(event) {
const target = event.target.closest('a');
if (target && target.href.startsWith(targetBaseUrl)) {
target.href = appendUTMParamsToUrl(target.href, getUTMParams());
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment