I am trying to pass the UTM parameters from my facebook ads to all pages on my website.
example query string: www.mysite.com/?utm__source=facebook&utm_medium=psocial&utm_campaign=summer&utm_content=pool&fbclid=1234Jfshio
Typically the utm parameters will exist on the first page the user visits, but once they navigate to a new page the query string is lost.
I want the query string to be appended to the end of the URL on all of the pages my user navigates to during their session.
I have to do this so they when they open a chat with our LiveChat service, the start URL that is captured by our service contains the utm parameters from the ad they clicked.
Here is the code I am currently using - but it is not working as intended:
<script type="text/javascript">
 (function() {
 var utmInheritingDomain = "brilliance.com", // REPLACE THIS DOMAIN 
 utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
 links = document.getElementsByTagName("a"),
 utms = [
 "utm_source={{url - utm_source}}", // IN GTM, CREATE A URL VARIABLE utm_source
 "utm_medium={{url - utm_medium}}", // IN GTM, CREATE A URL VARIABLE utm_medium
 "fbclid={{url - fbclid}}" // IN GTM, CREATE A URL VARIABLE fbclid
 ];
 
 for (var index = 0; index < links.length; index += 1) {
 var tempLink = links[index].href,
 tempParts;
 if (tempLink.indexOf(utmInheritingDomain) > 0) { // The script is looking for all links with the utmInheritingDomain
 tempLink = tempLink.replace(utmRegExp, "");
 tempParts = tempLink.split("#");
 if (tempParts[0].indexOf("?") < 0 ) {
 tempParts[0] += "?" + utms.join("&"); // The script adds UTM parameters to all links with the domain you've defined
 } else {
 tempParts[0] += "&" + utms.join("&");
 }
 tempLink = tempParts.join("#");
 }
 links[index].href = tempLink;
 }
 }());
</script> 
    