Is there a way to catch click events earlier than .stopPropagation() gets executed onclick?

34 Views Asked by At

The purpose of document.body.onclick = e => console.log(e.target); is to catch all clicks. Unfortunately, the click on the first link won't be displayed in the console. Is there a way to grab links from the page, even those that have stopPropagation()?

https://jsfiddle.net/htLw9cxy/

function myFuncCanNotBeEdited(e) {
  e.stopPropagation();
  //...
  //and do some other important code here
}

document.body.onclick = e => console.log(e.target);
<body>
  <div style="border: 1px solid red; padding: 10px;">
    <a href="#" onclick="myFuncCanNotBeEdited(event);">Edit</a>
    <a href="#">Remove</a>
  </div>
</body>

1

There are 1 best solutions below

0
Keith On

Ok, this is really hacky, so be careful as it involve modifying built in prototype.

You can intercept globally the stopPropagation prototype.

Below I've knocked up a very simple Snippet, you could extend to do more checks, making sure it's a link etc.

const oStop = PointerEvent.prototype.stopPropagation;

PointerEvent.prototype.stopPropagation = function (e) {
  console.log(this.target);
  oStop.call(this);
}

function myFuncCanNotBeEdited(e) {
  e.stopPropagation();
}

document.body.onclick = e => console.log(e.target);
<body>
  <div style="border: 1px solid red; padding: 10px;">
    <a href="#" onclick="myFuncCanNotBeEdited(event);">Edit</a>
    <a href="#">Remove</a>
  </div>
</body>