Search code examples
javascriptdom-events

How does one capture a Mac's command key via JavaScript?


How does one capture a Mac's Cmd key via JavaScript?


Solution

  • EDIT: As of 2019, e.metaKey is supported on all major browsers as per the MDN.

    Note that on Windows, although the ⊞ Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.

    This is only for the command key on MacOS/keyboards.


    Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown/keyup and record when a key is pressed and then depressed based on event.keyCode.

    Unfortunately, these key codes are browser-dependent:

    • Firefox: 224
    • Opera: 17
    • WebKit browsers (Safari/Chrome): 91 (Left Command) or 93 (Right Command)

    You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.