How does one capture a Mac's command key via JavaScript?
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) or93
(Right Command)
You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
You can also look at the event.metaKey
attribute on the event if you are working with keydown events. Worked wonderfully for me! You can try it here.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ⌘+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ⌘+x, it will output 120, true
This only seems to work in Safari - not Chrome