Mousetrap Usage Guide

· 3 min read

For web hotkey listening and handling, you can use mousetrap.js. This library is no longer maintained, but it’s still very useful and recommended.

Here’s an introduction to its usage.

https://static.1991421.cn/2023/2023-11-19-151351.jpg

Features

Supports single/combined keys/Gmail-style/Konami Code key bindings

  1. Gmail-style means like g i, where consecutive key inputs can execute an action. The advantage of this hotkey style is that it easily avoids browser/plugin hotkeys
  2. Konami Code is somewhat like in Contra where specific key combinations trigger 30 lives. Personally, I think this type of key binding is quite suitable for web easter eggs if necessary

In addition to basic hotkey binding features, Mousetrap also has some extensions to solve specific needs

  1. Pause/unpause

    Stop and resume this Mousetrap’s bindings

  2. Record

    Hotkey recording, useful when implementing custom web hotkeys

  3. Bind dictionary

    Supports dictionary format for binding multiple hotkeys at once.

Usage

  1. The Mousetrap constructor parameter is the element to bind hotkey listening to. If not provided, it defaults to document

    let mousetrap = new Mousetrap(window);
    
  2. bind

    mousetrap.bind(['command+k','g i'], function(e,combokey) { highlight(combokey); });
    

    Note: The second parameter of the callback is the key combination, such as command+k or g i

  3. unbind

      mousetrap.unbind(['command+k']);
    

    Note: The keys for unbind are the same as for bind, so they can also be arrays/strings

  4. trigger

      mousetrap.trigger(['g i']);
    
  5. stopCallback

      mousetrap.stopCallback = function () {
        return false;
      };
    

    Controls callback prevention logic. By default, hotkey bindings are not triggered in input/textarea/editable situations. As shown above, it triggers in all request situations

  6. reset()

      mousetrap.reset();
    

    Reset means delete all bindings

  7. addKeycodes

      Mousetrap.addKeycodes({
        144: 'numlock'
      });
    

    Add keycode mappings, usually don’t need to change. This is because the library is aging, and the entire implementation uses keycode instead of key. Currently MDN no longer recommends using KeyCode

  8. record

    mousetrap.record(function(sequence) {
                alert('You pressed: ' + sequence.join(' '));
            });
    

    Note: The record timeout is fixed at 1s and does not support continuous recording

Mousetrap Issues

  1. The record timeout is hardcoded to 1s. Currently, you need to modify the source code to extend it as a parameter, or change the value to solve this

        function _restartRecordTimer() {
            clearTimeout(_recordTimer);
            _recordTimer = setTimeout(_finishRecording, 1000);
        }
    
  2. Mousetrap uses event bubbling. If you want to use event capturing, you also need to modify the source code to extend support

        function _addEvent(object, type, callback) {
            if (object.addEventListener) {
                object.addEventListener(type, callback, false);
                return;
            }
    
            object.attachEvent('on' + type, callback);
        }
    
  3. The record plugin import and packaging will encounter errors because i is undefined in the for loop, which causes errors in strict mode packaging.

     ```js
      for (i = 0; i < modifiers.length; ++i) {
                     _recordKey(modifiers[i]);
                 }
     ```
    

Final Thoughts

If you need to implement hotkey binding in WEB, you can still consider using Mousetrap