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.