0

I am using the below script to dynamically change links with query parameters. The links are dynamically changed when I click on the button.

example.com/abc?client_id=123

The problem is when a user lands on the site with this URL from Google Ads - example.com/abc?gclid_id=786, and then clicks on the button the URL is dynamically changed to example.com/abc?gclid=786?client_id=123

I want it example.com/abc?gclid=786&client_id=123

Can I modify the existing script if the users come from Google change the parameter to &client_id=123 and when the user comes organically change the script to ?client_id=123

The parameter values are dynamic and they are mapped with cookie values (This is sorted). The main problem is & and ?

<script>

(function () {


var links = document.querySelectorAll('a[href*=abc]');
  
var clientId = '?client_id={{Read Cookie Value}}'

links.forEach(function(link) {
              
var original = link.getAttribute('href');
link.setAttribute('href', original+clientId)
              
              
              
 })


}) ();
  
</script>
8
  • Instead of concatenating query parameters manually, please use the URL API and its searchParams property, which also correctly encodes parameters: const url = new URL(link.getAttribute('href')); url.searchParams.set("client_id", cookieValue); link.href = url;. Commented Dec 9, 2022 at 13:52
  • I am looking for answers to & and ? dynamic changes. Commented Dec 9, 2022 at 13:55
  • Yes, that’s what the URL and URLSearchParams API does automatically. Have you tried it already? Commented Dec 9, 2022 at 13:56
  • So you are saying when a user lands on the site from Google Ads, the GLCLID parameter will be added. Then when the user clicks on the button, my script will add '&' to click_id instead of '?' Commented Dec 9, 2022 at 14:00
  • 1
    The code in my comment literally provides the solution. You could also simply read the documentation. The linked question explains exactly how URL parameters are added. Commented Dec 9, 2022 at 14:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.