Search code examples
javascriptkeyboard-shortcutskeyboard-eventsuserscriptstampermonkey

How do I disable / remove website keyboard hotkey on imgur.com? Specifically, the upload accent / tilde (`) command


I thought I found a tampermonkey script but it just doesn't work. Do you have any wisdom?

https://greasyfork.org/en/scripts/31704-imgur-remove-key-listener

How do I disable website shortcut keyboard hotkeys? I use Push to talk discord and the key interferes with my browsing experience.

I search on google for queries like "unbind website hotkeys -browser" and "script disable remove website keyboard hotkey" and "disable imgur hotkey" but no results on first 20 links.

// ==UserScript==
// @name        Imgur remove key listener
// @namespace   xxx
// @description Removes the key shortcuts on imgur
// @include     *://imgur.com/*
// @version     1
// @grant       none
// @locale       en
// ==/UserScript==

$(document).unbind('keydown').unbind('keyup');

When I press tilde / accent key on keyboard an upload dialogue should not appear on imgur website.


Solution

  • The listener(s) don't look to be added synchronously, so a userscript that runs synchronously won't remove the listeners.

    An alternative (and a good general solution to similar issues) would be to add a listener to window, in the capturing phase, and call stopPropagation on the event:

    ['keydown', 'keyup'].forEach((eventName) => {
      window.addEventListener(
        eventName,
        (e) => {
          e.stopPropagation();
        },
        true // capturing phase - very important
      );
    });
    

    This will prevent listeners added to children nodes from triggering. To also prevent listeners added to window after this listener was added from triggering, you can call e.stopImmediatePropagation().

    The only case when this sort of technique won't work would be if the page adds their own capturing listener to window before your userscript runs.

    To make sure your script executes as fast as possible (you want your own listener to be attached ASAP), you can put

    // @run-at document-start
    

    in the metadata block, which can help, but isn't entirely reliable, unfortunately.