Skip to content

Instantly share code, notes, and snippets.

@dillansimmons
Last active June 2, 2024 14:32
Show Gist options
  • Save dillansimmons/a2c1ebad5788dc2a2d9cb45669d9396e to your computer and use it in GitHub Desktop.
Save dillansimmons/a2c1ebad5788dc2a2d9cb45669d9396e to your computer and use it in GitHub Desktop.
Pass current UTMS to in page links Javascript
// JS for grabbing utm params and parsing into url
var getRefQueryParam = function() {
var temp = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function() {
var decode = function(s) {
return decodeURIComponent(s.split("+").join(" "));
};
temp[decode(arguments[1])] = decode(arguments[2]);
});
return temp;
};
// Get all the UTM parameters before the page finishes rendering
//Variables
var utmParamQueryString = '',
utmParamQueryStringTrimmed = '',
utm_source = '',
utm_medium = '',
utm_content = '',
utm_campaign = '',
(function() {
utm_source = getRefQueryParam("utm_source");
utm_medium = getRefQueryParam("utm_medium");
utm_content = getRefQueryParam("utm_content");
utm_campaign = getRefQueryParam("utm_campaign");
if (utm_source) {
utmParamQueryString += '&utm_source=' + utm_source;
}
if (utm_medium) {
utmParamQueryString += '&utm_medium=' + utm_medium;
}
if (utm_content) {
utmParamQueryString += '&utm_content=' + utm_content;
}
if (utm_campaign) {
utmParamQueryString += '&utm_campaign=' + utm_campaign;
}
// if there are utm values add them all up
if (utmParamQueryString.length > 0) {
utmParamQueryString = utmParamQueryString.substring(1);
utmParamQueryStringTrimmed = utmParamQueryString;
utmParamQueryString = '?' + utmParamQueryString;
}
})();
// Grab all links you want to target - change the class to whatever you are using i.e .utm-passthrough
var navlinks = document.querySelectorAll('a.utm-passthrough');
// Loop through all links
Array.prototype.forEach.call(links, function (link) {
// Take the href and append the UTM parameters
link.href += utmParamQueryString;
});
@mglinski
Copy link

mglinski commented Jan 11, 2024

I took the examples of @khanhicetea and @dillansimmons above and made a hybrid version using URL and URLSearchParams classes for all of the heavy lifting. This will not work on older browsers.

This will propagate any query param starting with utm_ into all <a href="..." /> tags on the current page, taking care to follow the following rules:

  • No other query params will be injected except ones starting with utm_
  • Only links with the same exact domain name will have utm params injected
  • If a link has existing UTM params already, this will skip those links and not clobber existing UTM params
  • Existing query params in each link will be preserved
(function () {
    // use URLSerachParams to get strings <- does not work in Internet Explorer
    let deleteParams = [];
    const utmParamQueryString = new URLSearchParams(window.location.search);
    utmParamQueryString.forEach(function (value, key) {
        if (!key.startsWith("utm_")) deleteParams.push(key);
    });
    for (var key in deleteParams) utmParamQueryString.delete(key);
    if (utmParamQueryString) {
        // get all the links on the page
        document.querySelectorAll("a").forEach(function (item) {
            const checkUrl = new URL(item.href);
            // if the links hrefs are not navigating to the same domain, then skip processing them
            if (checkUrl.host === location.host) {
                let doNotProcess = false;
                const linkSearchParams = new URLSearchParams(checkUrl.search);
                linkSearchParams.forEach(function (value, key) {
                    if (key.startsWith("utm_")) doNotProcess = true;
                });
                if (doNotProcess) return;
                checkUrl.search = new URLSearchParams({
                    ...Object.fromEntries(utmParamQueryString),
                    ...Object.fromEntries(linkSearchParams),
                });
                item.href = checkUrl.href;
            }
        });
    }
})();

Hopefully this saves someone time in the future.

@flornet
Copy link

flornet commented Jun 2, 2024

Thanks !

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