Passing UTM Name/Value Pairs to Specific Links on a Website

Adding UTM parameters to links is useful for tracking marketing efforts, e.g. if you have a banner or an email with links to a landing page, you’ll want to know which method (banner or email) generated the most page visits and form fills. Google has a campaign URL builder that will generate URLs with UTMs for you. In Google Analytics, you can find pageviews to the landing page by UTM parameter. However, if you want to track any subsequent pages after the landing page, then you’ll need a way to pass the UTMs along to the subsequent pages. In my particular situation, I needed to pass UTMs to a 3rd-party site. The visitor flow would be like this

  1. Click a banner on the home page of example.com. The banner has UTMs in the query string, e.g. example.com/landing-page?utmsource=home-page-banner
  2. Land on an overview page on example.com, e.g. example.com/landing-page
  3. Maybe visit other pages on example.com
  4. Return to example.com/landing-page
  5. Click a link to register for something on a 3rd-party site, e.g. foo.com/register

By default, only the first pageview of example.com/landing-page would include UTMs in the URL. To pass the UTMs to the link to the 3rd-party site, something extra needed to be done. I chose the following approach, which works well.

  1. Write JavaScript code that runs on all pages.
  2. If a URL contains UTM params, save the UTM name/value pairs as session cookies, overwriting any existing UTM cookies.
  3. If a page has any <a> tags with the class “appendUTM”, then rewrite the href value by appending the UTM params.

I then added the class “appendUTM” to any links where I wanted to append the UTMs. In my case, it was the links to the 3rd-party registration site.

Below is the code that accomplishes this.