Transferring UTM Parameters Across Pages Using Google Tag Manager (GTM)

Picture this:

You're the mastermind behind an electrifying promotional campaign, steering a surge of eager traffic toward a bespoke landing page, let's dub it "" The allure of the campaign's centerpiece, a compelling Call-to-Action—think "Unleash Your Spark: Claim Your Shocking Discount!"—propels visitors forward. With a click, they're transported to the next phase of the journey, finding themselves at the doorstep of ""

Here, the curtain rises on a pivotal scene:

Visitors are beckoned to take that triumphant leap, be it installing a revolutionary app, entering a sweepstakes, or sealing the deal with a sign-up flourish.

Amidst this crescendo of action, as conversions crescendo and a triumphant surge of success fills the air, a beacon fires in the digital landscape—none other than a Google Analytics event. But the ensuing analysis reveals a plot twist: in the annals of GA reports, all laurels appear to be placed upon the initial act, ""

The rationale is sound:

Each visitor's journey, though diverse, finds its inception here, cascading onward to "" Yet, beneath the surface, a yearning persists—to trace the true inception point that set hearts ablaze and screens alight.

Now, envision a conventional solution:

The seamless dance of cross-domain tracking, gracefully uniting these distinct online realms. However, let's acknowledge the occasional quandary. Some situations, like shadows cast upon the moon, thwart the viability of this ideal fix (and we shall demystify these conundrums shortly).

As we embark on this odyssey of insight, prepare to navigate a terrain where innovation thrives. I shall illuminate a path—akin to a luminescent trail—empowering the transference of UTM parameters. These digital emblems, wielded like magic tokens, shall journey from their genesis at "," etching their tale upon the annals of the subsequent saga at "" This endeavor takes center stage, resonating most profoundly when traditional cross-domain pursuits encounter their own curtain call (an unraveling I'll orchestrate in the paragraphs to come).

Understanding the Issue: Bridging the Gap in Information and Tracking Conversions

Imagine you're promoting a sophisticated product named "Tealbox Digital," available on the App Store, specifically the Shopify App Store in this instance. However, the space provided on the App Store page isn't sufficient to comprehensively showcase the product's range of benefits, extensive features, and other crucial details. To address this limitation, you've taken the strategic decision to create a dedicated landing page designed to provide an in-depth overview of "Tealbox Digital." This landing page serves as an expansive canvas where you can present key selling points, detailed feature descriptions, an engaging video, and a prominently placed "Get App Now" button, serving as the prominent call-to-action (CTA) element.

The visitor's journey commences with their arrival on the initial landing page. Here, they're exposed to the comprehensive narrative surrounding "Tealbox Digital," assimilating its distinctive value propositions and functionalities. The persuasive power of the content prompts the visitor to take the next step: clicking the prominently displayed "Get App Now" button. Upon this action, the visitor is seamlessly transitioned from the landing page to the actual App Store page where "Tealbox Digital" is hosted.

This transition is akin to a bridge connecting the preliminary engagement with the final installation of the app. The ultimate objective is realized when the visitor proceeds to install the app, thereby completing the conversion process. Consequently, the journey unfolds as follows:

  • Landing Page Entry: Visitors encounter the landing page, meticulously crafted to showcase "Tealbox Digital," its distinct attributes, and the value it brings.

  • CTA Interaction: Engaged by the content, visitors are prompted to engage further by clicking the "Get App Now" button, signifying their intent to proceed with the installation process.

  • App Store Arrival: Clicking the CTA directs visitors to the App Store page housing "Tealbox Digital," where they can delve deeper into the specifics and execute the app installation.

  • Conversion Completion: Successful app installation signifies the realization of the conversion goal, marking the culmination of the visitor's journey from discovery to tangible action.

In essence, this strategic maneuver bridges the informational and transactional phases, effectively guiding visitors from their initial introduction to the comprehensive product narrative on the landing page to the decisive moment of app installation via the App Store. This process is facilitated by the presence of UTM parameters—utilized as tracking mechanisms—in the inbound links, which serve as navigation markers guiding visitors across this digital landscape.

Transferring UTM Parameters Across Pages Using Google Tag Manager (GTM)| When the UTM parameters are missing

Solving the Puzzle: A Comprehensive Solution

In this enhanced version:

  • You can transfer various query parameters beyond UTMs.
  • Bypass the need for creating specific URL variables.
  • Extend the solution to cover links across multiple domains.
  • The solution remains effective even with optional query parameters missing (e.g., utm_campaign).

An effective strategy involves the seamless transfer of UTM parameters from These parameters will be automatically integrated into all links guiding users to Accomplishing this requires the collaborative power of Google Tag Manager and a customized script.

(function() {
  var domainsToDecorate = [
          '', // Replace with your company's domains
      queryParams = [
          'utm_medium', // Add or remove desired query parameters for transfer

  // Do not edit anything below this line
  var links = document.querySelectorAll('a');

  // Check if links contain domains from the domainsToDecorate array and then decorate
  for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
      for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
          if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
              links[linkIndex].href = decorateUrl(links[linkIndex].href);

  // Decorate the URL with query parameters
  function decorateUrl(urlToDecorate) {
      urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
      var collectedQueryParams = [];
      for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
          if (getQueryParam(queryParams[queryIndex])) {
              collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]));
      return urlToDecorate + collectedQueryParams.join('&');

  // Borrowed from
  // A function that retrieves the value of a query parameter
  function getQueryParam(name) {
      if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec( {
          return decodeURIComponent(name[1]);


Once a visitor arrives at and the Page URL includes parameters like utm_medium, utm_source, or any other URL parameters of your interest, a specific tag will be triggered. This tag springs into action, meticulously scanning the entirety of the page, on the lookout for links that encompass the domain(s) leading to the final destination page— in this context.

Upon discovering such a link, the script proceeds to:

  • Retrieve URL parameters (e.g., UTMs) from the browser's address bar.
  • Append these parameters to the identified link that bears the signature of ""
  • As a result of this process, the transformation is evident. Previously, a link such as will now undergo an automatic makeover, morphing into This evolution offers a renewed visitor journey:
Transferring UTM Parameters Across Pages Using Google Tag Manager (GTM)| Result of Enhanced UTM Parameters

Solution Limitations and Considerations

Notably, this solution isn't universally applicable and may encounter limitations in specific scenarios:

  1. URLs Containing #: In instances where the URLs intended for enhancement encompass the symbol #, it's advised to revert to the previous version of the solution. This ensures a seamless process in scenarios where the older approach proves more effective.

  2. Existing URL Parameters: If the URLs earmarked for augmentation already include query parameters originating from the Custom HTML tag, the script will not overwrite them. Instead, it will supplement these existing parameters, leading to potential redundancy.

Should you identify additional situations where the script's behavior deviates from expectations, then feel free to contact us. Our team of experts will actively investigate and address any concerns you raise.

Enacting the Solution – GTM Integration

To bring this solution to life within Google Tag Manager (GTM), follow these steps:

Transferring UTM Parameters Across Pages Using Google Tag Manager (GTM)| Google Tag Manager Integration Tag Configuration
  1. Create a Custom HTML Tag:
  • Within your GTM workspace, access the "Tags" section.
  • Click "New" to generate a new tag.
  • Choose the "Custom HTML" tag type.
  1. Insert the JavaScript Code:
  • Paste the JavaScript code previously furnished in the script section into the "HTML" field of the custom HTML tag.
  1. Assign Trigger:
  • Next, you need to set a trigger to control when this tag executes. Configure the tag to activate on the specific pages where the script's action is desired.
  1. Save and Publish:
  • After configuring the tag and its trigger, save your changes.
  • Finally, publish the changes to ensure they take effect.

By following these steps, the custom HTML tag incorporating the provided JavaScript code will be seamlessly integrated into your Google Tag Manager setup. This tag acts as a conduit, facilitating the execution of the script on the designated pages according to your chosen trigger settings.

Customising the Domain List 

On line 3, you'll encounter the domainsToDecorate array:

  var domainsToDecorate = [
          '', //add or remove domains (without https or trailing slash)
  • Within this section, you should input the domain(s) associated with your ultimate landing page(s). When a visitor arrives at the interim landing page, the script scans for links containing the domain(s) specified within the domainsToDecorate array.
  • In essence, if the visitor's path spans a website > >, you need to insert "" into the domainsToDecorate array.
  • Should you intend to enhance URLs from just one domain, you can retain just that domain entry. Alternatively, if you're expanding to encompass four domains, you're free to do so. Ensuring accuracy is crucial; refrain from introducing typos, missing commas, or improperly placed apostrophes.
  • For a more precise approach, it's possible to fine-tune the process to specific links. Instead of "," you might specify ""

Here's a sample involving a single domain (remember to replace this domain with your own):

  var domainsToDecorate = [

Feel empowered to tailor the list to your distinct requirements, optimizing your solution with meticulous precision.

Including URL Parameters for Transfer 

Now, proceed to configure the list of URL parameters you intend to extract from the current page URL and subsequently apply to specific outgoing links.

For instance, if the Page URL where a visitor is currently located reads like this:, the parameters (such as utm_medium) will be integrated into all URLs linking to, for instance:

Within the provided JavaScript code, focus on the queryParams array as shown below:

queryParams = [
          'utm_medium', //add or remove query parameters you want to transfer

This array facilitates the declaration of the specific query parameters you wish to transfer. Notable features of this setup include:

  • Effortless Parameter Management:
    You're relieved from the need to create GTM variables for individual parameters, streamlining the setup process.
  • Comprehensive Parameter Transfer:
    The recent update broadens the scope beyond UTMs, permitting the transfer of any URL parameter (query parameter)
  • Optional Parameter Inclusion:
    Parameters listed in the queryParams array are non-mandatory. If a parameter, let's say utm_campaign, isn't present in the Page URL, the script will function seamlessly without interruption.
  • Handling Special Characters:
    Remarkably, the solution adeptly handles special characters. Even a "+" sign within UTMs remains unaltered and unencoded as %2B.

For example, let's say you're targeting the following parameters:

queryParams = [

Upon configuring this parameter array, proceed to save the tag. You're now ready to move to the subsequent step: setting up an appropriate trigger.

Configuring the Trigger

To ensure the Custom HTML tag is selectively activated only when the URL encompasses at least one of your specified query parameters, you need to set up an appropriate trigger. Building upon the earlier example, where these query parameters were specified within the Custom HTML tag:

queryParams = [

Follow these steps to configure the trigger:

  1. Trigger Type: DOM Ready:
  • Choose the trigger type "DOM Ready" since you want the tag to fire once the DOM is fully loaded.
  1. Firing Conditions:
  • Select "Fire on some DOM Ready Events" to define conditions for the trigger's activation.
  • For the condition itself, you'll employ a Regular Expression (RegEx) pattern to account for the presence of the query parameters. In this scenario, the pattern is utm_medium=|utm_source=|utm_campaign=|ref=.
  1. Pattern Explanation:
  • The pattern is constructed by adding an equals sign (=) after each parameter, and these parameters are separated by a pipe symbol (|), which in RegEx signifies "OR".
  • Alternatively, you could create a more concise expression like utm_(medium|source|campaign)=|ref=.
  1. Applying the Pattern:
  • The trigger condition, as discussed above, captures URLs containing any of the specified parameters. This ensures that the tag activates only on pages where these parameters are present in the URL.

Even if you're not entirely familiar with regular expressions, you can simply list all the query parameters you're interested in, add an equals sign after each one, and separate them with a ‘|’.

By configuring the trigger in this manner, you ensure that the Custom HTML tag fires selectively based on the query parameters detected in the URL, making the solution responsive to your specified conditions.

Transferring UTM Parameters Across Pages Using Google Tag Manager (GTM)| Google Tag Manager Integration Trigger Configuration

Testing the Implementation 

After implementing the changes, it's time to conduct tests to ensure the solution is functioning as expected. Enable Preview and Debug mode in Google Tag Manager and proceed with the following tests:

Test with Query Parameters:

Make sure the Page URL contains at least one of the query parameters you intend to transfer. For example, if your Page URL is, you've satisfied this condition.

  • Click the Defined Link:
    Click a link that contains the domain name specified in the custom script. In this case, it's
  • Check the Redirected URL:
    Once redirected, examine the Page URL (e.g., in the browser's address bar. It should include the UTM parameters transferred. For instance,
  • Test Without Parameters:
    Conversely, ensure you test scenarios where the address bar contains no UTMs or other parameters. In such cases, links to should remain unaltered.
  • Testing External Links:
    Finally, test a few external links unrelated to These should not contain any UTM parameters, as intended.

Reflecting on the Solution 

In this blog post, the procedure of transferring UTM parameters (or any URL parameters) between pages has been elucidated. This methodology proves immensely beneficial when an intermediate landing page draws visitors, who then proceed to a final destination page hosted on a different domain.
This approach serves as a contingency (plan B) when Cross-domain tracking isn't feasible for various reasons. It combats the default data loss in attribution and prevents Google Analytics from incorrectly labeling the intermediate landing page as the primary referral.

By employing the shared script, you can proficiently retain and utilize UTM parameters from the initial landing page, adorning selected links with these parameters.

Keep in mind, however, that navigation between the intermediate and final landing pages will initiate a new session, resulting in two distinct entries in your GA reports for the same individual.

Though relatively uncommon, this situation arises periodically, offering a practical solution. A reader recently inquired about a related topic, prompting the exploration and sharing of this effective approach.

The seamless transfer of UTM parameters is the key to understanding the intricate dance of your audience across your digital landscape. By harnessing the power of our solution, you'll gain unprecedented insights into the journey of your visitors, from that initial spark of interest to the triumphant moment of conversion.

Curious about the power of seamless UTM parameter transfer? Reach out to us today, and let's embark on a journey to enhance your tracking, so your marketing efforts shine in the digital landscape.

Get in touch with us

Don’t worry about making a large commitment without knowing much about what we can offer. Book a call with us, help us understand your business and then we’ll offer you a free ad account audit and an actionable marketing strategy. Like the strategy? Hire us! Don’t want to hire us? No problem. The strategy is on us!
Book Intro Call

Best Part?

Are you a digital business looking to win the BFCM (Black Friday Cyber Monday) this Thanksgiving? Get in touch with us and we’ll send over a free guide on the best BFCM myth-busters!

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.