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

JavascriptDom Events

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - 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) or 93 (Right Command)

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

Solution 2 - Javascript

You can also look at the event.metaKey attribute on the event if you are working with keydown events. Worked wonderfully for me! https://jsbin.com/cinojahoyu/edit?js,output">You can try it here.

Solution 3 - Javascript

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 - Javascript

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.

Solution 5 - Javascript

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
});

Solution 6 - Javascript

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()

Solution 7 - Javascript

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.

Solution 8 - Javascript

var element = //the DOM element to listen for the key on.
element.onkeyup = function(e) {
   if(e.metaKey) {
      //command key was pressed
   }
}

Solution 9 - Javascript

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDataGreedView Question on Stackoverflow
Solution 1 - JavascriptIlya SemenovView Answer on Stackoverflow
Solution 2 - JavascriptSunnyView Answer on Stackoverflow
Solution 3 - JavascriptcryptopayView Answer on Stackoverflow
Solution 4 - JavascriptMichael ZelenskyView Answer on Stackoverflow
Solution 5 - JavascriptKoen.View Answer on Stackoverflow
Solution 6 - JavascriptDinis CruzView Answer on Stackoverflow
Solution 7 - JavascriptJames MilnerView Answer on Stackoverflow
Solution 8 - JavascriptJacob RelkinView Answer on Stackoverflow
Solution 9 - JavascriptCui MingdaView Answer on Stackoverflow