How does one capture a Mac's command key via JavaScript?
Solution 1:
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.
Solution 2:
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.
Solution 3:
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
Solution 4:
Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
document.onclick = function (event) {
if (event.shiftKey || macKeys.shiftKey) {
//do something interesting
}
}
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.