Skip to content
Home » Blog » How to Preserve UTM Parameters After the Button Click & to the Next Page

How to Preserve UTM Parameters After the Button Click & to the Next Page

The Script to Use

Here’s a script you can use to preserve UTM parameters from a landing page through a button click to the next page:

// Get the current UTM parameters from the URL
const urlParams = new URLSearchParams(window.location.search);
const utmParams = {};
// Loop through each UTM parameter and add it to the utmParams object
urlParams.forEach((value, key) => {
  if (key.startsWith('utm_')) {
    utmParams[key] = value;
  }
});
// Add a click event listener to the button
const button = document.getElementById('my-button');
button.addEventListener('click', () => {
  // Add the UTM parameters to the next page's URL
  const nextPageUrl = 'https://example.com/next-page?' + new URLSearchParams(utmParams);
  window.location.href = nextPageUrl;
});

Here’s how this script works:

  1. First, it gets the current UTM parameters from the URL using the URLSearchParams API.
  2. It loops through each parameter and adds it to an object called utmParams.
  3. It adds a click event listener to a button with the ID “my-button”.
  4. When the button is clicked, it creates a new URL for the next page by appending the UTM parameters to the URL using new URLSearchParams(utmParams).
  5. Finally, it sets the window.location.href to the new URL, which will take the user to the next page while preserving the UTM parameters.

Note that this script assumes that the UTM parameters are in the format utm_source, utm_medium, utm_campaign, etc. If your parameters have different names, you’ll need to modify the script accordingly. Also, make sure to replace https://example.com/next-page with the actual URL of your next page.