Jump to content

Passing UTM parameters onwards to other sites

Go to solution Solved by jpeter,

Recommended Posts

Posted

We have Google Ads which pass UTM parameters to our site and need to pass them onwards to other sites.
Specifically, we have a Donate button that points to our donation page - on another site - which must have the UTMs.  
Does anyone know the correct way to do this? Is there any easy way to do this across all pages/buttons easily?

Thanks in advance

  • Replies 2
  • Views 1.9k
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

  • Solution
Posted

@StudioFine 

Add the following JavaScript code to the Footer using Code Injection. Just update the LINKS array to whatever relative or absolute path(s) you'd like to add the query parameters to. 

This script loop through all of the links on the page and add the query parameters from the URL to the links that are defined in the LINKS variable. 

(function () {

  const LINKS = [
    '/some/relative/path',
    'https://www.example.com/donate'
  ];

  // Function to attach query parameters to a list of links
  function attachQueryParametersToLinks() {
    const selectors = LINKS.map(link => `a[href="${link}"]`);
    const links = document.querySelectorAll(selectors.join(','));
    const urlSearchParams = new URLSearchParams(window.location.search);

    // Iterate over the links and update their href attributes
    links.forEach(link => {
      const originalHref = link.getAttribute('href');
      const linkSearchParams = new URLSearchParams(link.search);
      const mergedSearchParams = new URLSearchParams([...urlSearchParams, ...linkSearchParams]);
      link.setAttribute('href', `${originalHref}?${mergedSearchParams.toString()}`);
    });
  }

  if (document.readyState == 'complete') {
    attachQueryParametersToLinks()
  } else {
    window.addEventListener('DOMContentLoaded', attachQueryParametersToLinks);
  }
})()

Be sure to place the javascript between <script> tags e.g.:

<script>
  // Add JS here
</script>

 

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment


×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.