Pass UTM TAGS Webflow page to all links such as other subdomains/sites

<script>
document.addEventListener('DOMContentLoaded', function(event) {

// create urlParams variable (constant) from URLSearchParams class using current window
const urlParams = new URLSearchParams(window.location.search);
// set UTM medium, source and campaign variables (constants) based on results of URSearchParams
const utm_medium = urlParams.get('utm_medium') || "";
const utm_source = urlParams.get('utm_source') || "";
const utm_campaign = urlParams.get('utm_campaign') || "";
const utm_term = urlParams.get('utm_term') || "";
const utm_content = urlParams.get('utm_content') || "";

const ref_link = urlParams.get('ref') || "";

// get the Outbound button element
links = document.querySelectorAll("a");

links.forEach(function(outboundLink) {
// edit Outbound button element property by appending the URL parameters
var finalLink = "";
if (utm_medium != "")
finalLink += "utm_medium=" + encodeURIComponent(utm_medium);

if (utm_source != "")
{
if (finalLink != "")
finalLink += "&";

finalLink += "utm_source=" + encodeURIComponent(utm_source);
}

if (utm_campaign != "")
{
if (finalLink != "")
finalLink += "&";

finalLink += "utm_campaign" + encodeURIComponent(utm_campaign);
}


if (utm_term != "")
{
if (finalLink != "")
finalLink += "&";

finalLink += "utm_term=" + encodeURIComponent(utm_term);
}

if (ref_link != "")
{
if (finalLink != "")
finalLink += "&";

finalLink += "ref=" + encodeURIComponent(ref_link);
}

if (finalLink != "")
outboundLink.href += "?" + finalLink;

// log final Outbound button link to console
// console.log(outboundLink.href);
});

    } );
</script>
Based on https://stackoverflow.com/a/65297467

Leave a Reply