Search code examples
javascripthtmlgoogle-chrome-devtoolsevent-listener

Prevent or Listen for a user removing event listeners in developer tools?


How can I prevent or listen for a user removing event listeners in developer tools?

Is this possible?

Sample Removal via Developer Tools

In the example above, when a user removes an "Event Listener", I would like to act upon the action. Is there an event listener for event listeners?


Solution

  • const removeEventListenerOriginal = EventTarget.prototype.removeEventListener;
    const p = document.querySelector("p");
    const onClick = e => console.log("clicked", e.target.tagName);
    
    
    EventTarget.prototype.removeEventListener = function(...args) {
      const [eventType, handler, capture] = args;
    
      console.log(`Event Listener Removed For`, this, {
        eventType,
        handler,
        capture
      });
    
      // your logic here
    
      // call the original function or not. its up to you
      removeEventListenerOriginal.call(this, ...args);
      // or removeEventListenerOriginal.apply(this, args);
    }
    
    p.addEventListener("click", onClick);
    // try removing the event from dev console
    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo</p>