javascripttampermonkeygreasemonkey-4

Remap arrow keys to another keys with JavaScript on GreaseMonkey/TamperMonkey


I'm trying to set up a TamperMonkey script to reassign the Right Arrow key to F key.

I tried this code, but so far, nothing happens when I press F.

    (function(){
document.addEventListener('keydown', function(e) {
 // pressed F
  if (e.keyCode == 70 && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
  keyCode == 39 // this should trigger the right arrow
  }
}, false);
})();

Can someone enlighten me on this, please?


Solution

  • You'll want to use the KeyboardEvent constructor and then run dispatchEvent on either the entire document or a specific element via document.querySelector, document.getElementById, etc.

    Run the snippet below to see this in action.

    (BTW, using KeyboardEvent.keyCode is depricated in favor of KeyboardEvent.key. It still works in major web browsers for backwards compatibility, but it's been officially deprecated in the standards)

    (Also make sure your TamperMonkey script is running at document-end if you're wanting to run the keyboard event on a custom DOM element)

    window.addEventListener('keydown', (e) => {
        if (e.key == 'ArrowRight') console.log('right arrow pressed');
    });
    
    // Your TamperMonkey script starts here
    (() => {
        window.addEventListener('keydown', (e) => {
            if (e.key == 'f' && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
                console.log('f pressed');
    
                // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
                const keyboardEvent = new KeyboardEvent('keydown', {
                    key: 'ArrowRight',
                    keyCode: 39,
                    bubbles: true,
                    cancelable: true,
                    shiftKey: false,
                    ctrlKey: false,
                    altKey: false,
                    metaKey: false,
                });
    
                // https://stackoverflow.com/a/44190874/12101554
                // replace `document` with a specific element if you want to do a specific
                document.dispatchEvent(keyboardEvent);
            }
        });
    })();
    <p>
      press right arrow &amp; f key to see things happen
    </p>
    <button onclick="document.querySelector('.as-console').innerHTML = ''">clear console</button>

    However, there isn't a way to disable f from doing other things on that website. If you want to do this, you can install AutoHotKey (Wikipedia Link), create an AutoHotKey script with this one line:

    f::^Right
    

    https://www.autohotkey.com/docs/misc/Remap.htm#Remap

    When you start this AHK script, AHK will intercept the key event before (most) programs and modify it.