I am using this script in Google Tag Manager as a Custom HTML tag to replace button-click URLs. I am getting this error in Chrome - Failed to construct 'URL': Invalid URL
Objective
When a user lands on the site, he lands on /example?gclid=898
, when he clicks on the button, I want to extract the cookie value and append it to the URL via search params API. The final URL will look something like this - /example?gclid=898&client_id=123
The below code is used in Custom HTML Tag in Google Tag Manager.
<script>
(function () {
var links = document.querySelectorAll('a[href*=example]');
links.forEach(function(link) {
var original = link.getAttribute('href');
console.log(original);
var url = new URL(original);
console.log('This is new URL :' + url);
url.searchParams.append('client_id',{{Read Cookie Value}});
console.log(url);
link.setAttribute('href', url);
})
}) ();
</script>
This is the error I get on the console:
Uncaught TypeError: Failed to construct 'URL': Invalid URL
Is there a way to fix this? It seems doesn't seem to recognize the new construct URL.