Search code examples
javascriptmacosdom-eventskeypresskeyboard-events

How to capture a Mac's command (⌘) key press in JavaScript?


In JavaScript how can we capture the Cmd / key event made on Mac & physical iPad keyboards?


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.


    Old, now outdated answer

    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.