Search code examples
javascriptchromium

Javascript: How to be the very first receiver of a mouse/key event


I'd like to recognize any mouse input within a website before any other object has a chance of processing it.
Is there a native solution to this?

Why do I need to get it first?
The site uses event.stopPropagation() on some mouse events. I want to see these events before they are propagated

Notes:

  • I case specifically about chromium. There is no need for cross browser support; But I'd like to avoid chromium hacking.
  • window.addEventListener ("mousedown", ...) doesn't work; it would receive events after other elements already stopped their propagation
  • document.body.addEventListener ("mousedown", ...) doesn't work; it would receive events after other elements already stopped their propagation

Solution

  • You can specify useCapture (the third parameter in addEventListener) as true:

    window.addEventListener('mousedown', function(){
      console.log("first")
    })
    
    window.addEventListener('mousedown', function(){
      console.log("second") //should fire first
    }, true)
    
    window.addEventListener('mousedown', function(){
      console.log("third")
    })