Search code examples
javascriptdom-eventsuserscriptspreventdefault

Disallow .preventDefault() everywhere


I'm trying to write a userscript to block all .preventDeault() calls globally for keyboard events and use my own hotkeys instead of being forced to use those defined by different websites. The problem is I can't figure out how one can unbind something like that without looking into a concrete website's code. I don't want to block all JS - just the things that should be in my control instead of developers' - but I don't understand how to make it simple and global.


Solution

  • Disabling the ability to prevent default in a website's code is likely to make that site unstable and possibly unusable.

    You could create an override of preventDefault on KeyboardEvent (which is a subclass of UIEvent, which is a subclasss of Event where the standard preventDefault is implemented), like this:

    KeyboardEvent.prototype.preventDefault = function() { };
    

    (The writable, enumerable, and configurable flags on Event's preventDefault are all true, so no need for Object.defineProperty here.)

    Example:

    KeyboardEvent.prototype.preventDefault = function() { };
    
    // This event handler *should* prevent typing in the input, but doesn't because we've broken preventDefault
    document.getElementById("the-input").addEventListener("keydown", function(e) {
      e.preventDefault();
    }, false);
    <input id="the-input" type="text">

    Compare that to the version that doesn't override preventDefault:

    // This event handler prevents typing in the input, because we haven't broken preventDefault
    document.getElementById("the-input").addEventListener("keydown", function(e) {
      e.preventDefault();
    }, false);
    <input id="the-input" type="text">

    That may work, at least for a subset of modern browsers, but again, I'd strongly recommend against it.