Home > Back-end >  Failed to construct 'URL': Invalid URL
Failed to construct 'URL': Invalid URL

Time:12-12

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 to construct 'URL': Invalid URL

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

CodePudding user response:

you need base.

A string or any other object with a stringifier — including, for example, an or element — that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored.

docs/Web/API/URL/URL

CodePudding user response:

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

  • Related