In one of my recent projects, the client requested that I transfer the UTM Parameters along with them when the user arrives from different campaigns to other pages on the website.
To be precise, the request was that these parameters should be passed when the user specifically clicks on one of the links or takes actions that lead to the web application under a different domain.
So, since this is a very reasonable and quite common request (especially for passing these parameters from landing pages), I’ll share with you in this post the script I used and briefly describe how it works.
What Does the Script Do?
The script scans all the links on the website, and when it finds a link leading to the same external application, it first checks if the link contains any UTM parameters. If these parameters are not present in the link, it adds those specific UTM parameters that the user arrived with to the links, meaning the same parameters that exist in the URL address.
A better explanation might be provided with an example. Let’s say I landed on a certain landing page with the following parameters:
https://lp.com/?utm_source=google&utm_medium=cpc&utm_campaign=name-campaign&utm_term=keyword&utm_content=fb-banner
And let’s assume that on the landing page, there’s a link to our application, and for the sake of the example, the link looks like this:
https://app.com/
Using this script would change this link to the following:
https://app.com/?utm_source=google&utm_medium=cpc&utm_campaign=name-campaign&utm_term=keyword&utm_content=fb-banner
The Script Looks Like This:
<script>
(function () {
const targetDomain = "app.co.il"; // Set target domain
const urlParams = new URLSearchParams(window.location.search);
const utmParams = [...urlParams.entries()]
.filter(([key]) => key.startsWith('utm_'))
.map(([key, value]) => `${key}=${value}`)
.join('&');
if (utmParams) {
document.querySelectorAll('a[href]').forEach(link => {
if (link.href.includes(targetDomain) && !link.href.includes("utm_")) {
link.href += (link.href.includes('?') ? '&' : '?') + utmParams;
}
});
}
})();
</script>
Some Points to Note
- Note that in line number 3, you’ll find the specific domain (the link to the application). Only links to this specific domain will be affected by the script. In other words, in this case, any link containing the domain app.com will be affected by the change.
- The script should be placed at the end of each page. If you’re using Google Tag Manager, the script should run on the DOM Ready action.
- The script is not relevant for Organic Referrers.
- In the script we presented, we’re defining a specific domain, but you can use any URL address you want.
That’s it. Any improvements or ideas to enhance this script will be welcomed with open arms… 🙂