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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With