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

12

262

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

Rhondarhondda answered 10/10, 2010 at 23:26 Comment(2)
Use this github.com/madrobby/keymasterOccultism
There is a javascript-lib for that: keymaster.js (no dependencies like jquery)Yong
R
340

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.

Renin answered 13/10, 2010 at 9:38 Comment(5)
Know that Opera is now also under the Webkit category. I think just listening for 91, 93, and 224, will get the job done. 17 is Ctrl, by the way. Did old Opera not differentiate Cmd and Ctrl??Shrewsbury
It seems that event.metaKey works in the current versions of Safari, Firefox and Chrome like a charm. IMO it is much clear solution.Culberson
In response to Miroslav's comment, just note that it only works on keydown events, not keyup.Nyberg
In response to @Nyberg 's comment: e.key === 'Meta' works for both keydown and keyup. So this can be used instead of e.metaKeyAshtoreth
@Nyberg You helped me a lot with comment about keydown / keyup . Because I was stuck in keypress event not understanding, what is wrong with it))Mistaken
T
235

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.

Teplica answered 31/3, 2011 at 13:22 Comment(9)
That doesn't seem to be set for me with Firefox 4.0.1 on MacOS. Given that the accepted answer and the linked reference both disagree with what you've said as well, I think this answer is incorrect.Ineducation
The accepted answer gives another, more painful, way to make it work, while the linked reference says that "According to the DOM 3 standard, on the Macintosh, the Option key should activate event.altKey and the Command key should activate event.metaKey. These attributes seem to work correctly on all modern browsers tested" ! The answer works for me under Firefox 5.0 on MacOS. I'll try and test it in older versions.Teplica
Also, the accepted answer wrongly says that "Mac/Apple key is not considered as a modifier key", even though the given reference says the contrary ! Here is a script that shows the .metaKey modifier working under Mac Firefox 3.6.3 -> 5.0.Teplica
.metaKey indeed works in latest Firefox, Safari and Opera. In Chrome, .metaKey triggers on Control (not on Command).Renin
FWIW, cmd+e doesn't work for me in your script. Ctrl triggers the CMD icon you haveEstellestella
cmd+e doesn't fire the event for me either (chrome). ctrl+e does.Witching
I think the trick (even in Chrome) is that this works for keydown but NOT for keyup or keypress.Benzocaine
You are right @philfreo, tested here in Chrome. I updated the answer and the example accordingly.Teplica
You might want to add a call to event.preventDefault() to prevent the browser and/or OS from processing the command key.Aggrade
Y
18

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

Ypsilanti answered 16/11, 2013 at 22:39 Comment(1)
what is the status in 2017?Elizabethelizabethan
C
16

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.

Cameraman answered 20/4, 2015 at 10:54 Comment(0)
R
9

keyCode and which are now deprecated so it's advisable to avoid the answers that use those here.

One way to do this now is using the key property on the event argument that comes with DOM keyup and keypress events. Here's a simple example of how to do it:

document.onkeypress = (event) => {
    if (event.key === 'Meta') {
        console.log("Mac or Windows key was pressed!");
    } else {
        console.log("Another key was pressed")
    }
}

This will trigger on the cmd key press on Mac (See Meta on the MDN docs). The only thing to note here is it will also trigger on the Windows key press too for the users keyboard/OS that support it.

If you need more granular understanding of which Meta key has been pressed, you can use the code property on event which can be either MetaLeft or MetaRight depending on which physical meta key ( cmd) was pressed.

Riding answered 23/12, 2021 at 18:17 Comment(0)
K
7

For people using jQuery, there is an excellent plugin for handling key events:

jQuery hotkeys on GitHub

For capturing +S and Ctrl+S I'm using this:

$(window).bind('keydown.ctrl_s keydown.meta_s', function(event) {
    event.preventDefault();
    // Do something here
});
Kiakiah answered 28/3, 2012 at 16:56 Comment(3)
Works too well. All other key presses get captured too.Exhilarative
Is it cross browser supported?Fromenty
If you visited the link in my answer, you would've known: github.com/tzuryby/jquery.hotkeys#jquery-compatibilityKiakiah
T
3

Here is how I did it in AngularJS

app = angular.module('MM_Graph')

class Keyboard
  constructor: ($injector)->
    @.$injector  = $injector
    @.$window    = @.$injector.get('$window')                             # get reference to $window and $rootScope objects
    @.$rootScope = @.$injector.get('$rootScope')

  on_Key_Down:($event)=>
    @.$rootScope.$broadcast 'keydown', $event                             # broadcast a global keydown event

    if $event.code is 'KeyS' and ($event.ctrlKey or $event.metaKey)       # detect S key pressed and either OSX Command or Window's Control keys pressed
      @.$rootScope.$broadcast '', $event                                  # broadcast keyup_CtrS event
      #$event.preventDefault()                                             # this should be used by the event listeners to prevent default browser behaviour

  setup_Hooks: ()=>
    angular.element(@.$window).bind "keydown", @.on_Key_Down              # hook keydown event in window (only called once per app load)
    @

app.service 'keyboard', ($injector)=>
  return new Keyboard($injector).setup_Hooks()
Tellford answered 16/1, 2017 at 11:27 Comment(0)
T
2
var element = //the DOM element to listen for the key on.
element.onkeyup = function(e) {
   if(e.metaKey) {
      //command key was pressed
   }
}
Toomer answered 10/10, 2010 at 23:39 Comment(1)
var element = document.body; element.onKeyUp = function(e) { if(e.metaKey) { console.log('cmd pressed') } }Rhondarhondda
Z
1

With a KeyboardEvent.metaKey: boolean

fromEvent(window, 'keydown').pipe(takeUntil(this._ngUnsubscribe)).subscribe(
  (res: KeyboardEvent) => {
    console.log(res.metaKey && res.key === 'Enter');
  }
);

This example is for RxJS' fromEvent but applies to any KeyboardEvent.

Zymosis answered 30/11, 2023 at 2:0 Comment(0)
T
0

This show capture the mac command and windows ctrl

#Mac command

$("#my_input").on('change keyup input', function() {
    var e = window.event || e; var key = e.keyCode; if(key == 93) {
        alert("Hello");
}
});

#Windows ctrl

$("#my_input").on('change keyup input', function() {
    var e = window.event || e; var key = e.keyCode; if(key == 17) {
        alert("Hello");
}
});

#Both

$("#my_input").on('change keyup input', function() {
    var e = window.event || e; var key = e.keyCode; if(key == 17 || key == 93) {
        alert("Hello");
}
});
Transonic answered 7/6, 2023 at 14:5 Comment(0)
P
0
document.addEventListener('keydown', (e) => {
    if((e.key == 'Meta' && /Mac OS/.test(navigator.userAgent)) || e.ctrlKey) {
      // CTRL or CMD pressed
    }
})
Pinsk answered 13/10, 2023 at 21:1 Comment(0)
M
-1

if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple

https://www.npmjs.com/package/vue-shortkey

v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"
Morph answered 16/8, 2019 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.