Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get GET parameter from link and prevent opening

I want to prevent links leading to a specific domain from opening, but store the included GET parameters to call another function using Javascript.

Example link: http://sub.example.com/?service=address&id=23

Therefore I have this at the moment:

[].forEach.call(document.querySelectorAll("a[href*='sub.example.com'"), function(a){
    a.setAttribute('onclick', '
        var url = new URL(this.href);
        var service = url.searchParams.get("service");
        console.log(service); 
        return false;
    ')
})

I suggest that it has something to do with the creation of the URL object, but unfortunately I do not get any error messages in Edge DevTools. I do not get any output on the console and as the link still opens, return false; also is not reached.

Can anybody give me a hint? Thanks in advance.

like image 887
Gardinero Avatar asked Feb 27 '26 12:02

Gardinero


1 Answers

You cannot have newlines inside strings delimited with single or double quotes. It is better practice to use addEventListener and event.preventDefault instead.

[].forEach.call(document.querySelectorAll("a[href*='sub.example.com'"), function(a) {
  a.addEventListener('click', function(e) {
    e.preventDefault();
    var url = new URL(this.href);
    var service = url.searchParams.get("service");
    console.log(service);
  });
})
<a href="http://sub.example.com/?service=address&id=23">Link</a>
like image 114
Unmitigated Avatar answered Mar 01 '26 01:03

Unmitigated