Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  135] [ 3]  / answers: 1 / hits: 7949  / 1 Year ago, mon, december 12, 2022, 12:00:00

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


Failed


Is there a way to fix this? It seems doesn't seem to recognize the new construct URL.


More From » javascript

 Answers
3

The original value is /example?gclid_id=786.



The URL constructor only works for relative URLs, if you provide a base as second argument.


But you can avoid this problem, if you read the actual property value - and not the attribute.


var original = link.getAttribute('href');

this gets you the content of the attribute, as it was written in the HTML code. If you use


var original = link.href;

instead, you should get an absolute URL, that the URL() constructor will accept directly.


https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/href:



The HTMLAnchorElement.href property is a stringifier that returns a string containing the whole URL



[#6] Tuesday, August 23, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
santiago

Total Points: 375
Total Questions: 106
Total Answers: 97

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;