Skip to content

Instantly share code, notes, and snippets.

@mglinski
Last active January 11, 2024 18:08
Show Gist options
  • Save mglinski/272a1997f3814534ca83adf73432146c to your computer and use it in GitHub Desktop.
Save mglinski/272a1997f3814534ca83adf73432146c to your computer and use it in GitHub Desktop.
Ensure current page UTMs are set on all page links using javascript

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

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

  • 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

Hopefully this saves someone time in the future.

(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);
// skip if existing utm params exist
linkSearchParams.forEach(function (value, key) {
if (key.startsWith("utm_")) doNotProcess = true;
});
if (doNotProcess) return;
// merge query string params and then write new link back to a tag
checkUrl.search = new URLSearchParams({
...Object.fromEntries(utmParamQueryString),
...Object.fromEntries(linkSearchParams),
});
item.href = checkUrl.href;
}
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment