Blocked Link Navigation Error in JavaScript
Let's say we have a link:
<a href="">link</a>
Let's get our link into a variable:
let link = document.querySelector('a');
Let's attach a click handler to our link. We will prevent the default link behavior to avoid page reload:
link.addEventListener('click', function(event) {
console.log(this.textContent);
event.preventDefault();
});
It seems that we have completely protected ourselves from unexpected behavior. In reality, this is not the case. The point is that if a syntax error occurs, the JavaScript code simply won't execute, the link blocking won't work, and navigation will occur.
In this case, we won't see either the result of the code execution or an error in the console, because the page will reload. Let's intentionally make an error in the code and see it in practice:
link.addEventListener('click', function(event) {
thiss.textContent = 'text'; // syntax error
event.preventDefault();
});
This problem has a characteristic sign: if you look at the console at the moment of clicking the link, we will momentarily see a red error in the console, which almost immediately disappears.
Of course, we won't have time to read the error text,
which significantly complicates
finding it. However, there is a clever trick. You need
to put a hash symbol in the link's href.
In this case, navigation won't occur
and we will see the error thrown
into the console:
<a href="#">link</a>